blob: f88334a05ea64918d9c6b183b3d6813c32337eed [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
James Molloy4de84dd2015-11-04 15:28:04 +000017#include "llvm/ADT/SetOperations.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000022#include "llvm/Analysis/ConstantFolding.h"
Joseph Tremoulet0d808882016-01-05 02:37:41 +000023#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000027#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000028#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Constants.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DerivedTypes.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/MDBuilder.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000040#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000042#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Type.h"
Evan Chengd983eba2011-01-29 04:46:23 +000044#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000045#include "llvm/Support/Debug.h"
46#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000047#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Jingyue Wufc029672014-09-30 22:23:38 +000048#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000049#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000050#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000052using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000053using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000054
Chandler Carruth964daaa2014-04-22 02:55:47 +000055#define DEBUG_TYPE "simplifycfg"
56
James Molloy1b6207e2015-02-13 10:48:30 +000057// Chosen as 2 so as to be cheap, but still to have enough power to fold
58// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
59// To catch this, we need to fold a compare and a select, hence '2' being the
60// minimum reasonable default.
Peter Collingbourne616044a2011-04-29 18:47:38 +000061static cl::opt<unsigned>
James Molloy1b6207e2015-02-13 10:48:30 +000062PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
63 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
Peter Collingbourne616044a2011-04-29 18:47:38 +000064
Evan Chengd983eba2011-01-29 04:46:23 +000065static cl::opt<bool>
66DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
67 cl::desc("Duplicate return instructions into unconditional branches"));
68
Manman Ren93ab6492012-09-20 22:37:36 +000069static cl::opt<bool>
70SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
71 cl::desc("Sink common instructions down to the end block"));
72
Alp Tokercb402912014-01-24 17:20:08 +000073static cl::opt<bool> HoistCondStores(
74 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
75 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000076
James Molloy4de84dd2015-11-04 15:28:04 +000077static cl::opt<bool> MergeCondStores(
78 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
79 cl::desc("Hoist conditional stores even if an unconditional store does not "
80 "precede - hoist multiple conditional stores into a single "
81 "predicated store"));
82
83static cl::opt<bool> MergeCondStoresAggressively(
84 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
85 cl::desc("When merging conditional stores, do so even if the resultant "
86 "basic blocks are unlikely to be if-converted as a result"));
87
David Majnemerfccf5c62016-01-27 02:59:41 +000088static cl::opt<bool> SpeculateOneExpensiveInst(
89 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
90 cl::desc("Allow exactly one expensive instruction to be speculatively "
91 "executed"));
92
Sanjay Patel5264cc72016-01-27 19:22:45 +000093static cl::opt<unsigned> MaxSpeculationDepth(
94 "max-speculation-depth", cl::Hidden, cl::init(10),
95 cl::desc("Limit maximum recursion depth when calculating costs of "
96 "speculatively executed instructions"));
97
Hans Wennborg39583b82012-09-26 09:44:49 +000098STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000099STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +0000100STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +0000101STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +0000102STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Manman Ren93ab6492012-09-20 22:37:36 +0000103STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +0000104STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +0000105
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000106namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000107 // The first field contains the value that the switch produces when a certain
Sanjay Patel9361d352015-09-10 16:31:19 +0000108 // case group is selected, and the second field is a vector containing the
109 // cases composing the case group.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000110 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
111 SwitchCaseResultVectorTy;
112 // The first field contains the phi node that generates a result of the switch
Sanjay Patel9361d352015-09-10 16:31:19 +0000113 // and the second field contains the value generated for a certain case in the
114 // switch for that PHI.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000115 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
116
Eric Christopherb65acc62012-07-02 23:22:21 +0000117 /// ValueEqualityComparisonCase - Represents a case of a switch.
118 struct ValueEqualityComparisonCase {
119 ConstantInt *Value;
120 BasicBlock *Dest;
121
122 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
123 : Value(Value), Dest(Dest) {}
124
125 bool operator<(ValueEqualityComparisonCase RHS) const {
126 // Comparing pointers is ok as we only rely on the order for uniquing.
127 return Value < RHS.Value;
128 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000129
130 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000131 };
132
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000133class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000134 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000135 const DataLayout &DL;
Jingyue Wufc029672014-09-30 22:23:38 +0000136 unsigned BonusInstThreshold;
Chandler Carruth66b31302015-01-04 12:03:27 +0000137 AssumptionCache *AC;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000138 Value *isValueEqualityComparison(TerminatorInst *TI);
139 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000140 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000141 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000142 BasicBlock *Pred,
143 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000144 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
145 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000146
Devang Pateldd14e0f2011-05-18 21:33:11 +0000147 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000148 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chen Li1689c2f2016-01-10 05:48:01 +0000149 bool SimplifySingleResume(ResumeInst *RI);
150 bool SimplifyCommonResume(ResumeInst *RI);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000151 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000152 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000153 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000154 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000155 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000156 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000157
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000158public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000159 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
160 unsigned BonusInstThreshold, AssumptionCache *AC)
161 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000162 bool run(BasicBlock *BB);
163};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000164}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000165
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000166/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000167/// terminator instructions together.
Chris Lattner76dc2042005-08-03 00:19:45 +0000168static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
169 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000170
Chris Lattner76dc2042005-08-03 00:19:45 +0000171 // It is not safe to merge these two switch instructions if they have a common
172 // successor, and if that successor has a PHI node, and if *that* PHI node has
173 // conflicting incoming values from the two switch blocks.
174 BasicBlock *SI1BB = SI1->getParent();
175 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000176 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000177
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000178 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
179 if (SI1Succs.count(*I))
180 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000181 isa<PHINode>(BBI); ++BBI) {
182 PHINode *PN = cast<PHINode>(BBI);
183 if (PN->getIncomingValueForBlock(SI1BB) !=
184 PN->getIncomingValueForBlock(SI2BB))
185 return false;
186 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000187
Chris Lattner76dc2042005-08-03 00:19:45 +0000188 return true;
189}
190
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000191/// Return true if it is safe and profitable to merge these two terminator
192/// instructions together, where SI1 is an unconditional branch. PhiNodes will
193/// store all PHI nodes in common successors.
Manman Rend33f4ef2012-06-13 05:43:29 +0000194static bool isProfitableToFoldUnconditional(BranchInst *SI1,
195 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000196 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000197 SmallVectorImpl<PHINode*> &PhiNodes) {
198 if (SI1 == SI2) return false; // Can't merge with self!
199 assert(SI1->isUnconditional() && SI2->isConditional());
200
201 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000202 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000203 // 1> We have a constant incoming value for the conditional branch;
204 // 2> We have "Cond" as the incoming value for the unconditional branch;
205 // 3> SI2->getCondition() and Cond have same operands.
206 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
207 if (!Ci2) return false;
208 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
209 Cond->getOperand(1) == Ci2->getOperand(1)) &&
210 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
211 Cond->getOperand(1) == Ci2->getOperand(0)))
212 return false;
213
214 BasicBlock *SI1BB = SI1->getParent();
215 BasicBlock *SI2BB = SI2->getParent();
216 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000217 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
218 if (SI1Succs.count(*I))
219 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000220 isa<PHINode>(BBI); ++BBI) {
221 PHINode *PN = cast<PHINode>(BBI);
222 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000223 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000224 return false;
225 PhiNodes.push_back(PN);
226 }
227 return true;
228}
229
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000230/// Update PHI nodes in Succ to indicate that there will now be entries in it
231/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
232/// will be the same as those coming in from ExistPred, an existing predecessor
233/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000234static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
235 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000236 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000237
Chris Lattner80b03a12008-07-13 22:23:11 +0000238 PHINode *PN;
239 for (BasicBlock::iterator I = Succ->begin();
240 (PN = dyn_cast<PHINode>(I)); ++I)
241 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000242}
243
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000244/// Compute an abstract "cost" of speculating the given instruction,
245/// which is assumed to be safe to speculate. TCC_Free means cheap,
246/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000247/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000248static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000249 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000250 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000251 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000252 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000253}
Sanjay Patelf9b77632015-09-15 15:24:42 +0000254
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000255/// If we have a merge point of an "if condition" as accepted above,
256/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000257/// don't handle the true generality of domination here, just a special case
258/// which works well enough for us.
259///
260/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000261/// see if V (which must be an instruction) and its recursive operands
262/// that do not dominate BB have a combined cost lower than CostRemaining and
263/// are non-trapping. If both are true, the instruction is inserted into the
264/// set and true is returned.
265///
266/// The cost for most non-trapping instructions is defined as 1 except for
267/// Select whose cost is 2.
268///
269/// After this function returns, CostRemaining is decreased by the cost of
270/// V plus its non-dominating operands. If that cost is greater than
271/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000272static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000273 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000274 unsigned &CostRemaining,
David Majnemerfccf5c62016-01-27 02:59:41 +0000275 const TargetTransformInfo &TTI,
276 unsigned Depth = 0) {
Sanjay Patel5264cc72016-01-27 19:22:45 +0000277 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
278 // so limit the recursion depth.
279 // TODO: While this recursion limit does prevent pathological behavior, it
280 // would be better to track visited instructions to avoid cycles.
281 if (Depth == MaxSpeculationDepth)
282 return false;
283
Chris Lattner0aa56562004-04-09 22:50:22 +0000284 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000285 if (!I) {
286 // Non-instructions all dominate instructions, but not all constantexprs
287 // can be executed unconditionally.
288 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
289 if (C->canTrap())
290 return false;
291 return true;
292 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000293 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000294
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000295 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000296 // the bottom of this block.
297 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000298
Chris Lattner0aa56562004-04-09 22:50:22 +0000299 // If this instruction is defined in a block that contains an unconditional
300 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000301 // statement". If not, it definitely dominates the region.
302 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000303 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000304 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000305
Chris Lattner9ac168d2010-12-14 07:41:39 +0000306 // If we aren't allowing aggressive promotion anymore, then don't consider
307 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000308 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000309
Peter Collingbournee3511e12011-04-29 18:47:31 +0000310 // If we have seen this instruction before, don't count it again.
311 if (AggressiveInsts->count(I)) return true;
312
Chris Lattner9ac168d2010-12-14 07:41:39 +0000313 // Okay, it looks like the instruction IS in the "condition". Check to
314 // see if it's a cheap instruction to unconditionally compute, and if it
315 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000316 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000317 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000318
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000319 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000320
David Majnemerfccf5c62016-01-27 02:59:41 +0000321 // Allow exactly one instruction to be speculated regardless of its cost
322 // (as long as it is safe to do so).
323 // This is intended to flatten the CFG even if the instruction is a division
324 // or other expensive operation. The speculation of an expensive instruction
325 // is expected to be undone in CodeGenPrepare if the speculation has not
326 // enabled further IR optimizations.
327 if (Cost > CostRemaining &&
328 (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0))
Peter Collingbournee3511e12011-04-29 18:47:31 +0000329 return false;
330
David Majnemerfccf5c62016-01-27 02:59:41 +0000331 // Avoid unsigned wrap.
332 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000333
334 // Okay, we can only really hoist these out if their operands do
335 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000336 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
David Majnemerfccf5c62016-01-27 02:59:41 +0000337 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
338 Depth + 1))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000339 return false;
340 // Okay, it's safe to do this! Remember this instruction.
341 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000342 return true;
343}
Chris Lattner466a0492002-05-21 20:50:24 +0000344
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000345/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000346/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000347static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000348 // Normal constant int.
349 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000350 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000351 return CI;
352
353 // This is some kind of pointer constant. Turn it into a pointer-sized
354 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000355 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000356
357 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
358 if (isa<ConstantPointerNull>(V))
359 return ConstantInt::get(PtrTy, 0);
360
361 // IntToPtr const int.
362 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
363 if (CE->getOpcode() == Instruction::IntToPtr)
364 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
365 // The constant is very likely to have the right type already.
366 if (CI->getType() == PtrTy)
367 return CI;
368 else
369 return cast<ConstantInt>
370 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
371 }
Craig Topperf40110f2014-04-25 05:29:35 +0000372 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000373}
374
Mehdi Aminiffd01002014-11-20 22:40:25 +0000375namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000376
Mehdi Aminiffd01002014-11-20 22:40:25 +0000377/// Given a chain of or (||) or and (&&) comparison of a value against a
378/// constant, this will try to recover the information required for a switch
379/// structure.
380/// It will depth-first traverse the chain of comparison, seeking for patterns
381/// like %a == 12 or %a < 4 and combine them to produce a set of integer
382/// representing the different cases for the switch.
383/// Note that if the chain is composed of '||' it will build the set of elements
384/// that matches the comparisons (i.e. any of this value validate the chain)
385/// while for a chain of '&&' it will build the set elements that make the test
386/// fail.
387struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000388 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000389 Value *CompValue; /// Value found for the switch comparison
390 Value *Extra; /// Extra clause to be checked before the switch
391 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
392 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000393
Mehdi Aminiffd01002014-11-20 22:40:25 +0000394 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000395 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
396 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
397 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000398 }
399
Mehdi Aminiffd01002014-11-20 22:40:25 +0000400 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000401 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000402 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000403 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000404
Mehdi Aminiffd01002014-11-20 22:40:25 +0000405private:
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000406
Mehdi Aminiffd01002014-11-20 22:40:25 +0000407 /// Try to set the current value used for the comparison, it succeeds only if
408 /// it wasn't set before or if the new value is the same as the old one
409 bool setValueOnce(Value *NewVal) {
410 if(CompValue && CompValue != NewVal) return false;
411 CompValue = NewVal;
412 return (CompValue != nullptr);
413 }
414
415 /// Try to match Instruction "I" as a comparison against a constant and
416 /// populates the array Vals with the set of values that match (or do not
417 /// match depending on isEQ).
418 /// Return false on failure. On success, the Value the comparison matched
419 /// against is placed in CompValue.
420 /// If CompValue is already set, the function is expected to fail if a match
421 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000422 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000423 // If this is an icmp against a constant, handle this as one of the cases.
424 ICmpInst *ICI;
425 ConstantInt *C;
426 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
427 (C = GetConstantInt(I->getOperand(1), DL)))) {
428 return false;
429 }
430
431 Value *RHSVal;
432 ConstantInt *RHSC;
433
434 // Pattern match a special case
David Majnemerc761afd2016-01-27 02:43:28 +0000435 // (x & ~2^z) == y --> x == y || x == y|2^z
Mehdi Aminiffd01002014-11-20 22:40:25 +0000436 // This undoes a transformation done by instcombine to fuse 2 compares.
437 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
438 if (match(ICI->getOperand(0),
439 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
440 APInt Not = ~RHSC->getValue();
David Majnemerc761afd2016-01-27 02:43:28 +0000441 if (Not.isPowerOf2() && C->getValue().isPowerOf2() &&
442 Not != C->getValue()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000443 // If we already have a value for the switch, it has to match!
444 if(!setValueOnce(RHSVal))
445 return false;
446
447 Vals.push_back(C);
448 Vals.push_back(ConstantInt::get(C->getContext(),
449 C->getValue() | Not));
450 UsedICmps++;
451 return true;
452 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000453 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000454
455 // If we already have a value for the switch, it has to match!
456 if(!setValueOnce(ICI->getOperand(0)))
457 return false;
458
459 UsedICmps++;
460 Vals.push_back(C);
461 return ICI->getOperand(0);
462 }
463
464 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
Sanjoy Das7182d362015-03-18 00:41:24 +0000465 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
466 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000467
468 // Shift the range if the compare is fed by an add. This is the range
469 // compare idiom as emitted by instcombine.
470 Value *CandidateVal = I->getOperand(0);
471 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
472 Span = Span.subtract(RHSC->getValue());
473 CandidateVal = RHSVal;
474 }
475
476 // If this is an and/!= check, then we are looking to build the set of
477 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
478 // x != 0 && x != 1.
479 if (!isEQ)
480 Span = Span.inverse();
481
482 // If there are a ton of values, we don't want to make a ginormous switch.
483 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
484 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000485 }
486
487 // If we already have a value for the switch, it has to match!
Mehdi Aminiffd01002014-11-20 22:40:25 +0000488 if(!setValueOnce(CandidateVal))
489 return false;
490
491 // Add all values from the range to the set
492 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
493 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000494
495 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000496 return true;
497
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000498 }
499
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000500 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000501 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
502 /// the value being compared, and stick the list constants into the Vals
503 /// vector.
504 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000505 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000506 Instruction *I = dyn_cast<Instruction>(V);
507 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000508
Mehdi Aminiffd01002014-11-20 22:40:25 +0000509 // Keep a stack (SmallVector for efficiency) for depth-first traversal
510 SmallVector<Value *, 8> DFT;
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000511 SmallPtrSet<Value *, 8> Visited;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000512
Mehdi Aminiffd01002014-11-20 22:40:25 +0000513 // Initialize
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000514 Visited.insert(V);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000515 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000516
Mehdi Aminiffd01002014-11-20 22:40:25 +0000517 while(!DFT.empty()) {
518 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000519
Mehdi Aminiffd01002014-11-20 22:40:25 +0000520 if (Instruction *I = dyn_cast<Instruction>(V)) {
521 // If it is a || (or && depending on isEQ), process the operands.
522 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000523 if (Visited.insert(I->getOperand(1)).second)
524 DFT.push_back(I->getOperand(1));
525 if (Visited.insert(I->getOperand(0)).second)
526 DFT.push_back(I->getOperand(0));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000527 continue;
528 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000529
Mehdi Aminiffd01002014-11-20 22:40:25 +0000530 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000531 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000532 // Match succeed, continue the loop
533 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000534 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000535
Mehdi Aminiffd01002014-11-20 22:40:25 +0000536 // One element of the sequence of || (or &&) could not be match as a
537 // comparison against the same value as the others.
538 // We allow only one "Extra" case to be checked before the switch
539 if (!Extra) {
540 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000541 continue;
542 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000543 // Failed to parse a proper sequence, abort now
544 CompValue = nullptr;
545 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000546 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000547 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000548};
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000549
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000550}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000551
Eli Friedmancb61afb2008-12-16 20:54:32 +0000552static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000553 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000554 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
555 Cond = dyn_cast<Instruction>(SI->getCondition());
556 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
557 if (BI->isConditional())
558 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000559 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
560 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000561 }
562
563 TI->eraseFromParent();
564 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
565}
566
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000567/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000568/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000569Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000570 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000571 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
572 // Do not permit merging of large switch instructions into their
573 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000574 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
575 pred_end(SI->getParent())) <= 128)
576 CV = SI->getCondition();
577 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000578 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000579 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000580 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000581 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000582 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000583
584 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000585 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000586 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
587 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000588 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000589 CV = Ptr;
590 }
591 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000592 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000593}
594
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000595/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000596/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000597BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000598GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000599 std::vector<ValueEqualityComparisonCase>
600 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000601 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000602 Cases.reserve(SI->getNumCases());
603 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
604 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
605 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000606 return SI->getDefaultDest();
607 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000608
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000609 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000610 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000611 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
612 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000613 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000614 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000615 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000616}
617
Eric Christopherb65acc62012-07-02 23:22:21 +0000618
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000619/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000620/// in the list that match the specified block.
621static void EliminateBlockCases(BasicBlock *BB,
622 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000623 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000624}
625
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000626/// Return true if there are any keys in C1 that exist in C2 as well.
Eric Christopherb65acc62012-07-02 23:22:21 +0000627static bool
628ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
629 std::vector<ValueEqualityComparisonCase > &C2) {
630 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
631
632 // Make V1 be smaller than V2.
633 if (V1->size() > V2->size())
634 std::swap(V1, V2);
635
636 if (V1->size() == 0) return false;
637 if (V1->size() == 1) {
638 // Just scan V2.
639 ConstantInt *TheVal = (*V1)[0].Value;
640 for (unsigned i = 0, e = V2->size(); i != e; ++i)
641 if (TheVal == (*V2)[i].Value)
642 return true;
643 }
644
645 // Otherwise, just sort both lists and compare element by element.
646 array_pod_sort(V1->begin(), V1->end());
647 array_pod_sort(V2->begin(), V2->end());
648 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
649 while (i1 != e1 && i2 != e2) {
650 if ((*V1)[i1].Value == (*V2)[i2].Value)
651 return true;
652 if ((*V1)[i1].Value < (*V2)[i2].Value)
653 ++i1;
654 else
655 ++i2;
656 }
657 return false;
658}
659
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000660/// If TI is known to be a terminator instruction and its block is known to
661/// only have a single predecessor block, check to see if that predecessor is
662/// also a value comparison with the same value, and if that comparison
663/// determines the outcome of this comparison. If so, simplify TI. This does a
664/// very limited form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000665bool SimplifyCFGOpt::
666SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000667 BasicBlock *Pred,
668 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000669 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
670 if (!PredVal) return false; // Not a value comparison in predecessor.
671
672 Value *ThisVal = isValueEqualityComparison(TI);
673 assert(ThisVal && "This isn't a value comparison!!");
674 if (ThisVal != PredVal) return false; // Different predicates.
675
Andrew Trick3051aa12012-08-29 21:46:38 +0000676 // TODO: Preserve branch weight metadata, similarly to how
677 // FoldValueComparisonIntoPredecessors preserves it.
678
Chris Lattner1cca9592005-02-24 06:17:52 +0000679 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000680 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000681 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
682 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000683 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000684
Chris Lattner1cca9592005-02-24 06:17:52 +0000685 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000686 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000687 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000688 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000689
690 // If TI's block is the default block from Pred's comparison, potentially
691 // simplify TI based on this knowledge.
692 if (PredDef == TI->getParent()) {
693 // If we are here, we know that the value is none of those cases listed in
694 // PredCases. If there are any cases in ThisCases that are in PredCases, we
695 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000696 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000697 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000698
Chris Lattner4088e2b2010-12-13 01:47:07 +0000699 if (isa<BranchInst>(TI)) {
700 // Okay, one of the successors of this condbr is dead. Convert it to a
701 // uncond br.
702 assert(ThisCases.size() == 1 && "Branch can only have one case!");
703 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000704 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000705 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000706
Chris Lattner4088e2b2010-12-13 01:47:07 +0000707 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000708 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000709
Chris Lattner4088e2b2010-12-13 01:47:07 +0000710 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
711 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000712
Chris Lattner4088e2b2010-12-13 01:47:07 +0000713 EraseTerminatorInstAndDCECond(TI);
714 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000715 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000716
Chris Lattner4088e2b2010-12-13 01:47:07 +0000717 SwitchInst *SI = cast<SwitchInst>(TI);
718 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000719 SmallPtrSet<Constant*, 16> DeadCases;
720 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
721 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000722
David Greene725c7c32010-01-05 01:26:52 +0000723 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000724 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000725
Manman Ren8691e522012-09-14 21:53:06 +0000726 // Collect branch weights into a vector.
727 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000728 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000729 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
730 if (HasWeight)
731 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
732 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000733 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000734 Weights.push_back(CI->getValue().getZExtValue());
735 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000736 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
737 --i;
738 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000739 if (HasWeight) {
740 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
741 Weights.pop_back();
742 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000743 i.getCaseSuccessor()->removePredecessor(TI->getParent());
744 SI->removeCase(i);
745 }
746 }
Manman Ren97c18762012-10-11 22:28:34 +0000747 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000748 SI->setMetadata(LLVMContext::MD_prof,
749 MDBuilder(SI->getParent()->getContext()).
750 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000751
752 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000753 return true;
754 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000755
Chris Lattner4088e2b2010-12-13 01:47:07 +0000756 // Otherwise, TI's block must correspond to some matched value. Find out
757 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000758 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000759 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000760 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
761 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000762 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000763 return false; // Cannot handle multiple values coming to this block.
764 TIV = PredCases[i].Value;
765 }
766 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000767
768 // Okay, we found the one constant that our value can be if we get into TI's
769 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000770 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000771 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
772 if (ThisCases[i].Value == TIV) {
773 TheRealDest = ThisCases[i].Dest;
774 break;
775 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000776
777 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000778 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000779
780 // Remove PHI node entries for dead edges.
781 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000782 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
783 if (*SI != CheckEdge)
784 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000785 else
Craig Topperf40110f2014-04-25 05:29:35 +0000786 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000787
788 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000789 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000790 (void) NI;
791
792 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
793 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
794
795 EraseTerminatorInstAndDCECond(TI);
796 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000797}
798
Dale Johannesen7f99d222009-03-12 21:01:11 +0000799namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000800 /// This class implements a stable ordering of constant
Dale Johannesen7f99d222009-03-12 21:01:11 +0000801 /// integers that does not depend on their address. This is important for
802 /// applications that sort ConstantInt's to ensure uniqueness.
803 struct ConstantIntOrdering {
804 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
805 return LHS->getValue().ult(RHS->getValue());
806 }
807 };
808}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000809
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000810static int ConstantIntSortPredicate(ConstantInt *const *P1,
811 ConstantInt *const *P2) {
812 const ConstantInt *LHS = *P1;
813 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000814 if (LHS->getValue().ult(RHS->getValue()))
815 return 1;
816 if (LHS->getValue() == RHS->getValue())
817 return 0;
818 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000819}
820
Andrew Trick3051aa12012-08-29 21:46:38 +0000821static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000822 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000823 if (ProfMD && ProfMD->getOperand(0))
824 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
825 return MDS->getString().equals("branch_weights");
826
827 return false;
828}
829
Manman Ren571d9e42012-09-11 17:43:35 +0000830/// Get Weights of a given TerminatorInst, the default weight is at the front
831/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
832/// metadata.
833static void GetBranchWeights(TerminatorInst *TI,
834 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000835 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000836 assert(MD);
837 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000838 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000839 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000840 }
841
Manman Ren571d9e42012-09-11 17:43:35 +0000842 // If TI is a conditional eq, the default case is the false case,
843 // and the corresponding branch-weight data is at index 2. We swap the
844 // default weight to be the first entry.
845 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
846 assert(Weights.size() == 2);
847 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
848 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
849 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000850 }
851}
852
Manman Renf1cb16e2014-01-27 23:39:03 +0000853/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000854static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000855 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
856 if (Max > UINT_MAX) {
857 unsigned Offset = 32 - countLeadingZeros(Max);
858 for (uint64_t &I : Weights)
859 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000860 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000861}
862
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000863/// The specified terminator is a value equality comparison instruction
864/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000865/// See if any of the predecessors of the terminator block are value comparisons
866/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000867bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
868 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000869 BasicBlock *BB = TI->getParent();
870 Value *CV = isValueEqualityComparison(TI); // CondVal
871 assert(CV && "Not a comparison?");
872 bool Changed = false;
873
Chris Lattner6b39cb92008-02-18 07:42:56 +0000874 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000875 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000876 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000877
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000878 // See if the predecessor is a comparison with the same value.
879 TerminatorInst *PTI = Pred->getTerminator();
880 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
881
882 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
883 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000884 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000885 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
886
Eric Christopherb65acc62012-07-02 23:22:21 +0000887 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000888 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
889
890 // Based on whether the default edge from PTI goes to BB or not, fill in
891 // PredCases and PredDefault with the new switch cases we would like to
892 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000893 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000894
Andrew Trick3051aa12012-08-29 21:46:38 +0000895 // Update the branch weight metadata along the way
896 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000897 bool PredHasWeights = HasBranchWeights(PTI);
898 bool SuccHasWeights = HasBranchWeights(TI);
899
Manman Ren5e5049d2012-09-14 19:05:19 +0000900 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000901 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000902 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000903 if (Weights.size() != 1 + PredCases.size())
904 PredHasWeights = SuccHasWeights = false;
905 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000906 // If there are no predecessor weights but there are successor weights,
907 // populate Weights with 1, which will later be scaled to the sum of
908 // successor's weights
909 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000910
Manman Ren571d9e42012-09-11 17:43:35 +0000911 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000912 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000913 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000914 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000915 if (SuccWeights.size() != 1 + BBCases.size())
916 PredHasWeights = SuccHasWeights = false;
917 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000918 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000919
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000920 if (PredDefault == BB) {
921 // If this is the default destination from PTI, only the edges in TI
922 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000923 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
924 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
925 if (PredCases[i].Dest != BB)
926 PTIHandled.insert(PredCases[i].Value);
927 else {
928 // The default destination is BB, we don't need explicit targets.
929 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000930
Manman Ren571d9e42012-09-11 17:43:35 +0000931 if (PredHasWeights || SuccHasWeights) {
932 // Increase weight for the default case.
933 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000934 std::swap(Weights[i+1], Weights.back());
935 Weights.pop_back();
936 }
937
Eric Christopherb65acc62012-07-02 23:22:21 +0000938 PredCases.pop_back();
939 --i; --e;
940 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000941
Eric Christopherb65acc62012-07-02 23:22:21 +0000942 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000943 if (PredDefault != BBDefault) {
944 PredDefault->removePredecessor(Pred);
945 PredDefault = BBDefault;
946 NewSuccessors.push_back(BBDefault);
947 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000948
Manman Ren571d9e42012-09-11 17:43:35 +0000949 unsigned CasesFromPred = Weights.size();
950 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000951 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
952 if (!PTIHandled.count(BBCases[i].Value) &&
953 BBCases[i].Dest != BBDefault) {
954 PredCases.push_back(BBCases[i]);
955 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000956 if (SuccHasWeights || PredHasWeights) {
957 // The default weight is at index 0, so weight for the ith case
958 // should be at index i+1. Scale the cases from successor by
959 // PredDefaultWeight (Weights[0]).
960 Weights.push_back(Weights[0] * SuccWeights[i+1]);
961 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000962 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000963 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000964
Manman Ren571d9e42012-09-11 17:43:35 +0000965 if (SuccHasWeights || PredHasWeights) {
966 ValidTotalSuccWeight += SuccWeights[0];
967 // Scale the cases from predecessor by ValidTotalSuccWeight.
968 for (unsigned i = 1; i < CasesFromPred; ++i)
969 Weights[i] *= ValidTotalSuccWeight;
970 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
971 Weights[0] *= SuccWeights[0];
972 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000973 } else {
974 // If this is not the default destination from PSI, only the edges
975 // in SI that occur in PSI with a destination of BB will be
976 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000977 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000978 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000979 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
980 if (PredCases[i].Dest == BB) {
981 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000982
983 if (PredHasWeights || SuccHasWeights) {
984 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
985 std::swap(Weights[i+1], Weights.back());
986 Weights.pop_back();
987 }
988
Eric Christopherb65acc62012-07-02 23:22:21 +0000989 std::swap(PredCases[i], PredCases.back());
990 PredCases.pop_back();
991 --i; --e;
992 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000993
994 // Okay, now we know which constants were sent to BB from the
995 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000996 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
997 if (PTIHandled.count(BBCases[i].Value)) {
998 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000999 if (PredHasWeights || SuccHasWeights)
1000 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +00001001 PredCases.push_back(BBCases[i]);
1002 NewSuccessors.push_back(BBCases[i].Dest);
1003 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
1004 }
1005
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001006 // If there are any constants vectored to BB that TI doesn't handle,
1007 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001008 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +00001009 PTIHandled.begin(),
1010 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +00001011 if (PredHasWeights || SuccHasWeights)
1012 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +00001013 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001014 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +00001015 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001016 }
1017
1018 // Okay, at this point, we know which new successor Pred will get. Make
1019 // sure we update the number of entries in the PHI nodes for these
1020 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +00001021 for (BasicBlock *NewSuccessor : NewSuccessors)
1022 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001023
Devang Patel58380552011-05-18 20:53:17 +00001024 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001025 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +00001026 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001027 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +00001028 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001029 }
1030
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001031 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +00001032 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
1033 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001034 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +00001035 for (ValueEqualityComparisonCase &V : PredCases)
1036 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001037
Andrew Trick3051aa12012-08-29 21:46:38 +00001038 if (PredHasWeights || SuccHasWeights) {
1039 // Halve the weights if any of them cannot fit in an uint32_t
1040 FitWeights(Weights);
1041
1042 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1043
1044 NewSI->setMetadata(LLVMContext::MD_prof,
1045 MDBuilder(BB->getContext()).
1046 createBranchWeights(MDWeights));
1047 }
1048
Eli Friedmancb61afb2008-12-16 20:54:32 +00001049 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001050
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001051 // Okay, last check. If BB is still a successor of PSI, then we must
1052 // have an infinite loop case. If so, add an infinitely looping block
1053 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001054 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001055 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1056 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001057 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001058 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001059 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001060 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1061 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001062 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001063 }
1064 NewSI->setSuccessor(i, InfLoopBlock);
1065 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001066
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001067 Changed = true;
1068 }
1069 }
1070 return Changed;
1071}
1072
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001073// If we would need to insert a select that uses the value of this invoke
1074// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1075// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001076static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1077 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001078 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001079 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001080 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001081 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1082 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1083 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1084 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1085 return false;
1086 }
1087 }
1088 }
1089 return true;
1090}
1091
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001092static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1093
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001094/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1095/// in the two blocks up into the branch block. The caller of this function
1096/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001097static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001098 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001099 // This does very trivial matching, with limited scanning, to find identical
1100 // instructions in the two blocks. In particular, we don't want to get into
1101 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1102 // such, we currently just scan for obviously identical instructions in an
1103 // identical order.
1104 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1105 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1106
Devang Patelf10e2872009-02-04 00:03:08 +00001107 BasicBlock::iterator BB1_Itr = BB1->begin();
1108 BasicBlock::iterator BB2_Itr = BB2->begin();
1109
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001110 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001111 // Skip debug info if it is not identical.
1112 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1113 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1114 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1115 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001116 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001117 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001118 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001119 }
Devang Patele48ddf82011-04-07 00:30:15 +00001120 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001121 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001122 return false;
1123
Chris Lattner389cfac2004-11-30 00:29:14 +00001124 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001125
David Majnemerc82f27a2013-06-03 20:43:12 +00001126 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001127 do {
1128 // If we are hoisting the terminator instruction, don't move one (making a
1129 // broken BB), instead clone it, and remove BI.
1130 if (isa<TerminatorInst>(I1))
1131 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001132
Chad Rosier54390052015-02-23 19:15:16 +00001133 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1134 return Changed;
1135
Chris Lattner389cfac2004-11-30 00:29:14 +00001136 // For a normal instruction, we just move one to right before the branch,
1137 // then replace all uses of the other with the first. Finally, we remove
1138 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001139 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001140 if (!I2->use_empty())
1141 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001142 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001143 unsigned KnownIDs[] = {
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001144 LLVMContext::MD_tbaa, LLVMContext::MD_range,
1145 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001146 LLVMContext::MD_nonnull, LLVMContext::MD_invariant_group,
1147 LLVMContext::MD_align, LLVMContext::MD_dereferenceable,
1148 LLVMContext::MD_dereferenceable_or_null};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001149 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001150 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001151 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001152
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001153 I1 = &*BB1_Itr++;
1154 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001155 // Skip debug info if it is not identical.
1156 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1157 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1158 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1159 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001160 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001161 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001162 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001163 }
Devang Patele48ddf82011-04-07 00:30:15 +00001164 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001165
1166 return true;
1167
1168HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001169 // It may not be possible to hoist an invoke.
1170 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001171 return Changed;
1172
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001173 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001174 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001175 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001176 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1177 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1178 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1179 if (BB1V == BB2V)
1180 continue;
1181
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001182 // Check for passingValueIsAlwaysUndefined here because we would rather
1183 // eliminate undefined control flow then converting it to a select.
1184 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1185 passingValueIsAlwaysUndefined(BB2V, PN))
1186 return Changed;
1187
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001188 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001189 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001190 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001191 return Changed;
1192 }
1193 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001194
Chris Lattner389cfac2004-11-30 00:29:14 +00001195 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001196 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001197 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001198 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001199 I1->replaceAllUsesWith(NT);
1200 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001201 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001202 }
1203
Devang Patel1407fb42011-05-19 20:52:46 +00001204 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001205 // Hoisting one of the terminators from our successor is a great thing.
1206 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1207 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1208 // nodes, so we insert select instruction to compute the final result.
1209 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001210 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001211 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001212 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001213 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001214 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1215 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001216 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001217
Chris Lattner4088e2b2010-12-13 01:47:07 +00001218 // These values do not agree. Insert a select instruction before NT
1219 // that determines the right value.
1220 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001221 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001222 SI = cast<SelectInst>
1223 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1224 BB1V->getName()+"."+BB2V->getName()));
1225
Chris Lattner4088e2b2010-12-13 01:47:07 +00001226 // Make the PHI node use the select for all incoming values for BB1/BB2
1227 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1228 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1229 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001230 }
1231 }
1232
1233 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001234 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1235 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001236
Eli Friedmancb61afb2008-12-16 20:54:32 +00001237 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001238 return true;
1239}
1240
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001241/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001242/// check whether BBEnd has only two predecessors and the other predecessor
1243/// ends with an unconditional branch. If it is true, sink any common code
1244/// in the two predecessors to BBEnd.
1245static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1246 assert(BI1->isUnconditional());
1247 BasicBlock *BB1 = BI1->getParent();
1248 BasicBlock *BBEnd = BI1->getSuccessor(0);
1249
1250 // Check that BBEnd has two predecessors and the other predecessor ends with
1251 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001252 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1253 BasicBlock *Pred0 = *PI++;
1254 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001255 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001256 BasicBlock *Pred1 = *PI++;
1257 if (PI != PE) // More than two predecessors.
1258 return false;
1259 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001260 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1261 if (!BI2 || !BI2->isUnconditional())
1262 return false;
1263
1264 // Gather the PHI nodes in BBEnd.
Michael Liao5313da32014-12-23 08:26:55 +00001265 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
Craig Topperf40110f2014-04-25 05:29:35 +00001266 Instruction *FirstNonPhiInBBEnd = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001267 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
Manman Ren93ab6492012-09-20 22:37:36 +00001268 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1269 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001270 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Michael Liao5313da32014-12-23 08:26:55 +00001271 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
Manman Ren93ab6492012-09-20 22:37:36 +00001272 } else {
1273 FirstNonPhiInBBEnd = &*I;
1274 break;
1275 }
1276 }
1277 if (!FirstNonPhiInBBEnd)
1278 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001279
Manman Ren93ab6492012-09-20 22:37:36 +00001280 // This does very trivial matching, with limited scanning, to find identical
1281 // instructions in the two blocks. We scan backward for obviously identical
1282 // instructions in an identical order.
1283 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
Michael Liao5313da32014-12-23 08:26:55 +00001284 RE1 = BB1->getInstList().rend(),
1285 RI2 = BB2->getInstList().rbegin(),
1286 RE2 = BB2->getInstList().rend();
Manman Ren93ab6492012-09-20 22:37:36 +00001287 // Skip debug info.
1288 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1289 if (RI1 == RE1)
1290 return false;
1291 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1292 if (RI2 == RE2)
1293 return false;
1294 // Skip the unconditional branches.
1295 ++RI1;
1296 ++RI2;
1297
1298 bool Changed = false;
1299 while (RI1 != RE1 && RI2 != RE2) {
1300 // Skip debug info.
1301 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1302 if (RI1 == RE1)
1303 return Changed;
1304 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1305 if (RI2 == RE2)
1306 return Changed;
1307
1308 Instruction *I1 = &*RI1, *I2 = &*RI2;
Michael Liao5313da32014-12-23 08:26:55 +00001309 auto InstPair = std::make_pair(I1, I2);
Manman Ren93ab6492012-09-20 22:37:36 +00001310 // I1 and I2 should have a single use in the same PHI node, and they
1311 // perform the same operation.
1312 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1313 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1314 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
David Majnemerba275f92015-08-19 19:54:02 +00001315 I1->isEHPad() || I2->isEHPad() ||
Manman Ren93ab6492012-09-20 22:37:36 +00001316 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1317 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1318 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1319 !I1->hasOneUse() || !I2->hasOneUse() ||
Michael Liao5313da32014-12-23 08:26:55 +00001320 !JointValueMap.count(InstPair))
Manman Ren93ab6492012-09-20 22:37:36 +00001321 return Changed;
1322
1323 // Check whether we should swap the operands of ICmpInst.
Michael Liao5313da32014-12-23 08:26:55 +00001324 // TODO: Add support of communativity.
Manman Ren93ab6492012-09-20 22:37:36 +00001325 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1326 bool SwapOpnds = false;
1327 if (ICmp1 && ICmp2 &&
1328 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1329 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1330 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1331 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1332 ICmp2->swapOperands();
1333 SwapOpnds = true;
1334 }
1335 if (!I1->isSameOperationAs(I2)) {
1336 if (SwapOpnds)
1337 ICmp2->swapOperands();
1338 return Changed;
1339 }
1340
1341 // The operands should be either the same or they need to be generated
1342 // with a PHI node after sinking. We only handle the case where there is
1343 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001344 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001345 unsigned Op1Idx = ~0U;
Manman Ren93ab6492012-09-20 22:37:36 +00001346 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1347 if (I1->getOperand(I) == I2->getOperand(I))
1348 continue;
Michael Liao5313da32014-12-23 08:26:55 +00001349 // Early exit if we have more-than one pair of different operands or if
1350 // we need a PHI node to replace a constant.
1351 if (Op1Idx != ~0U ||
Manman Ren93ab6492012-09-20 22:37:36 +00001352 isa<Constant>(I1->getOperand(I)) ||
1353 isa<Constant>(I2->getOperand(I))) {
1354 // If we can't sink the instructions, undo the swapping.
1355 if (SwapOpnds)
1356 ICmp2->swapOperands();
1357 return Changed;
1358 }
1359 DifferentOp1 = I1->getOperand(I);
1360 Op1Idx = I;
1361 DifferentOp2 = I2->getOperand(I);
1362 }
1363
Michael Liao5313da32014-12-23 08:26:55 +00001364 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1365 DEBUG(dbgs() << " " << *I2 << "\n");
1366
1367 // We insert the pair of different operands to JointValueMap and
1368 // remove (I1, I2) from JointValueMap.
1369 if (Op1Idx != ~0U) {
1370 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1371 if (!NewPN) {
1372 NewPN =
1373 PHINode::Create(DifferentOp1->getType(), 2,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001374 DifferentOp1->getName() + ".sink", &BBEnd->front());
Michael Liao5313da32014-12-23 08:26:55 +00001375 NewPN->addIncoming(DifferentOp1, BB1);
1376 NewPN->addIncoming(DifferentOp2, BB2);
1377 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1378 }
Manman Ren93ab6492012-09-20 22:37:36 +00001379 // I1 should use NewPN instead of DifferentOp1.
1380 I1->setOperand(Op1Idx, NewPN);
Manman Ren93ab6492012-09-20 22:37:36 +00001381 }
Michael Liao5313da32014-12-23 08:26:55 +00001382 PHINode *OldPN = JointValueMap[InstPair];
1383 JointValueMap.erase(InstPair);
Manman Ren93ab6492012-09-20 22:37:36 +00001384
Manman Ren93ab6492012-09-20 22:37:36 +00001385 // We need to update RE1 and RE2 if we are going to sink the first
1386 // instruction in the basic block down.
1387 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1388 // Sink the instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001389 BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(),
1390 BB1->getInstList(), I1);
Manman Ren93ab6492012-09-20 22:37:36 +00001391 if (!OldPN->use_empty())
1392 OldPN->replaceAllUsesWith(I1);
1393 OldPN->eraseFromParent();
1394
1395 if (!I2->use_empty())
1396 I2->replaceAllUsesWith(I1);
1397 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001398 // TODO: Use combineMetadata here to preserve what metadata we can
1399 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001400 I2->eraseFromParent();
1401
1402 if (UpdateRE1)
1403 RE1 = BB1->getInstList().rend();
1404 if (UpdateRE2)
1405 RE2 = BB2->getInstList().rend();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001406 FirstNonPhiInBBEnd = &*I1;
Manman Ren93ab6492012-09-20 22:37:36 +00001407 NumSinkCommons++;
1408 Changed = true;
1409 }
1410 return Changed;
1411}
1412
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001413/// \brief Determine if we can hoist sink a sole store instruction out of a
1414/// conditional block.
1415///
1416/// We are looking for code like the following:
1417/// BrBB:
1418/// store i32 %add, i32* %arrayidx2
1419/// ... // No other stores or function calls (we could be calling a memory
1420/// ... // function).
1421/// %cmp = icmp ult %x, %y
1422/// br i1 %cmp, label %EndBB, label %ThenBB
1423/// ThenBB:
1424/// store i32 %add5, i32* %arrayidx2
1425/// br label EndBB
1426/// EndBB:
1427/// ...
1428/// We are going to transform this into:
1429/// BrBB:
1430/// store i32 %add, i32* %arrayidx2
1431/// ... //
1432/// %cmp = icmp ult %x, %y
1433/// %add.add5 = select i1 %cmp, i32 %add, %add5
1434/// store i32 %add.add5, i32* %arrayidx2
1435/// ...
1436///
1437/// \return The pointer to the value of the previous store if the store can be
1438/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001439static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1440 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001441 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1442 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001443 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001444
1445 // Volatile or atomic.
1446 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001447 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001448
1449 Value *StorePtr = StoreToHoist->getPointerOperand();
1450
1451 // Look for a store to the same pointer in BrBB.
1452 unsigned MaxNumInstToLookAt = 10;
1453 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1454 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1455 Instruction *CurI = &*RI;
1456
1457 // Could be calling an instruction that effects memory like free().
1458 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001459 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001460
1461 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1462 // Found the previous store make sure it stores to the same location.
1463 if (SI && SI->getPointerOperand() == StorePtr)
1464 // Found the previous store, return its value operand.
1465 return SI->getValueOperand();
1466 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001467 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001468 }
1469
Craig Topperf40110f2014-04-25 05:29:35 +00001470 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001471}
1472
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001473/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001474///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001475/// Note that this is a very risky transform currently. Speculating
1476/// instructions like this is most often not desirable. Instead, there is an MI
1477/// pass which can do it with full awareness of the resource constraints.
1478/// However, some cases are "obvious" and we should do directly. An example of
1479/// this is speculating a single, reasonably cheap instruction.
1480///
1481/// There is only one distinct advantage to flattening the CFG at the IR level:
1482/// it makes very common but simplistic optimizations such as are common in
1483/// instcombine and the DAG combiner more powerful by removing CFG edges and
1484/// modeling their effects with easier to reason about SSA value graphs.
1485///
1486///
1487/// An illustration of this transform is turning this IR:
1488/// \code
1489/// BB:
1490/// %cmp = icmp ult %x, %y
1491/// br i1 %cmp, label %EndBB, label %ThenBB
1492/// ThenBB:
1493/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001494/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001495/// EndBB:
1496/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1497/// ...
1498/// \endcode
1499///
1500/// Into this IR:
1501/// \code
1502/// BB:
1503/// %cmp = icmp ult %x, %y
1504/// %sub = sub %x, %y
1505/// %cond = select i1 %cmp, 0, %sub
1506/// ...
1507/// \endcode
1508///
1509/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001510static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001511 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001512 // Be conservative for now. FP select instruction can often be expensive.
1513 Value *BrCond = BI->getCondition();
1514 if (isa<FCmpInst>(BrCond))
1515 return false;
1516
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001517 BasicBlock *BB = BI->getParent();
1518 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1519
1520 // If ThenBB is actually on the false edge of the conditional branch, remember
1521 // to swap the select operands later.
1522 bool Invert = false;
1523 if (ThenBB != BI->getSuccessor(0)) {
1524 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1525 Invert = true;
1526 }
1527 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1528
Chandler Carruthceff2222013-01-25 05:40:09 +00001529 // Keep a count of how many times instructions are used within CondBB when
1530 // they are candidates for sinking into CondBB. Specifically:
1531 // - They are defined in BB, and
1532 // - They have no side effects, and
1533 // - All of their uses are in CondBB.
1534 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1535
Chandler Carruth7481ca82013-01-24 11:52:58 +00001536 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001537 Value *SpeculatedStoreValue = nullptr;
1538 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001539 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001540 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001541 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001542 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001543 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001544 if (isa<DbgInfoIntrinsic>(I))
1545 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001546
Mark Lacey274f48b2015-04-12 18:18:51 +00001547 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001548 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001549 ++SpeculationCost;
1550 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001551 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001552
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001553 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001554 if (!isSafeToSpeculativelyExecute(I) &&
1555 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1556 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001557 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001558 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001559 ComputeSpeculationCost(I, TTI) >
1560 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001561 return false;
1562
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001563 // Store the store speculation candidate.
1564 if (SpeculatedStoreValue)
1565 SpeculatedStore = cast<StoreInst>(I);
1566
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001567 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001568 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001569 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001570 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001571 i != e; ++i) {
1572 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001573 if (!OpI || OpI->getParent() != BB ||
1574 OpI->mayHaveSideEffects())
1575 continue; // Not a candidate for sinking.
1576
1577 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001578 }
1579 }
Evan Cheng89200c92008-06-07 08:52:29 +00001580
Chandler Carruthceff2222013-01-25 05:40:09 +00001581 // Consider any sink candidates which are only used in CondBB as costs for
1582 // speculation. Note, while we iterate over a DenseMap here, we are summing
1583 // and so iteration order isn't significant.
1584 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1585 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1586 I != E; ++I)
1587 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001588 ++SpeculationCost;
1589 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001590 return false;
1591 }
1592
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001593 // Check that the PHI nodes can be converted to selects.
1594 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001595 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001596 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001597 Value *OrigV = PN->getIncomingValueForBlock(BB);
1598 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001599
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001600 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001601 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001602 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001603 continue;
1604
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001605 // Don't convert to selects if we could remove undefined behavior instead.
1606 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1607 passingValueIsAlwaysUndefined(ThenV, PN))
1608 return false;
1609
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001610 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001611 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1612 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1613 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001614 continue; // Known safe and cheap.
1615
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001616 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1617 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001618 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001619 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1620 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
James Molloy7c336572015-02-11 12:15:41 +00001621 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1622 TargetTransformInfo::TCC_Basic;
1623 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00001624 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001625
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001626 // Account for the cost of an unfolded ConstantExpr which could end up
1627 // getting expanded into Instructions.
1628 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001629 // constant expression.
1630 ++SpeculationCost;
1631 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001632 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001633 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001634
1635 // If there are no PHIs to process, bail early. This helps ensure idempotence
1636 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001637 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001638 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001639
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001640 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001641 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001642
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001643 // Insert a select of the value of the speculated store.
1644 if (SpeculatedStoreValue) {
1645 IRBuilder<true, NoFolder> Builder(BI);
1646 Value *TrueV = SpeculatedStore->getValueOperand();
1647 Value *FalseV = SpeculatedStoreValue;
1648 if (Invert)
1649 std::swap(TrueV, FalseV);
1650 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1651 "." + FalseV->getName());
1652 SpeculatedStore->setOperand(0, S);
1653 }
1654
Igor Laevsky7310c682015-11-18 14:50:18 +00001655 // Metadata can be dependent on the condition we are hoisting above.
1656 // Conservatively strip all metadata on the instruction.
1657 for (auto &I: *ThenBB)
1658 I.dropUnknownNonDebugMetadata();
1659
Chandler Carruth7481ca82013-01-24 11:52:58 +00001660 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001661 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
1662 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001663
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001664 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001665 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001666 for (BasicBlock::iterator I = EndBB->begin();
1667 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1668 unsigned OrigI = PN->getBasicBlockIndex(BB);
1669 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1670 Value *OrigV = PN->getIncomingValue(OrigI);
1671 Value *ThenV = PN->getIncomingValue(ThenI);
1672
1673 // Skip PHIs which are trivial.
1674 if (OrigV == ThenV)
1675 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001676
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001677 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001678 // false value is the preexisting value. Swap them if the branch
1679 // destinations were inverted.
1680 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001681 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001682 std::swap(TrueV, FalseV);
1683 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1684 TrueV->getName() + "." + FalseV->getName());
1685 PN->setIncomingValue(OrigI, V);
1686 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001687 }
1688
Evan Cheng89553cc2008-06-12 21:15:59 +00001689 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001690 return true;
1691}
1692
Tom Stellarde1631dd2013-10-21 20:07:30 +00001693/// \returns True if this block contains a CallInst with the NoDuplicate
1694/// attribute.
1695static bool HasNoDuplicateCall(const BasicBlock *BB) {
1696 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1697 const CallInst *CI = dyn_cast<CallInst>(I);
1698 if (!CI)
1699 continue;
1700 if (CI->cannotDuplicate())
1701 return true;
1702 }
1703 return false;
1704}
1705
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001706/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001707static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1708 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001709 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001710
Devang Patel84fceff2009-03-10 18:00:05 +00001711 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001712 if (isa<DbgInfoIntrinsic>(BBI))
1713 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001714 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001715 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001716
Dale Johannesened6f5a82009-03-12 23:18:09 +00001717 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001718 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001719 for (User *U : BBI->users()) {
1720 Instruction *UI = cast<Instruction>(U);
1721 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001722 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001723
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001724 // Looks ok, continue checking.
1725 }
Chris Lattner6c701062005-09-20 01:48:40 +00001726
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001727 return true;
1728}
1729
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001730/// If we have a conditional branch on a PHI node value that is defined in the
1731/// same block as the branch and if any PHI entries are constants, thread edges
1732/// corresponding to that entry to be branches to their ultimate destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001733static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001734 BasicBlock *BB = BI->getParent();
1735 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001736 // NOTE: we currently cannot transform this case if the PHI node is used
1737 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001738 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1739 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001740
Chris Lattner748f9032005-09-19 23:49:37 +00001741 // Degenerate case of a single entry PHI.
1742 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001743 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001744 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001745 }
1746
1747 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001748 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001749
Tom Stellarde1631dd2013-10-21 20:07:30 +00001750 if (HasNoDuplicateCall(BB)) return false;
1751
Chris Lattner748f9032005-09-19 23:49:37 +00001752 // Okay, this is a simple enough basic block. See if any phi values are
1753 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001754 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001755 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001756 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001757
Chris Lattner4088e2b2010-12-13 01:47:07 +00001758 // Okay, we now know that all edges from PredBB should be revectored to
1759 // branch to RealDest.
1760 BasicBlock *PredBB = PN->getIncomingBlock(i);
1761 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001762
Chris Lattner4088e2b2010-12-13 01:47:07 +00001763 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001764 // Skip if the predecessor's terminator is an indirect branch.
1765 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001766
Chris Lattner4088e2b2010-12-13 01:47:07 +00001767 // The dest block might have PHI nodes, other predecessors and other
1768 // difficult cases. Instead of being smart about this, just insert a new
1769 // block that jumps to the destination block, effectively splitting
1770 // the edge we are about to create.
1771 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1772 RealDest->getName()+".critedge",
1773 RealDest->getParent(), RealDest);
1774 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001775
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001776 // Update PHI nodes.
1777 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001778
1779 // BB may have instructions that are being threaded over. Clone these
1780 // instructions into EdgeBB. We know that there will be no uses of the
1781 // cloned instructions outside of EdgeBB.
1782 BasicBlock::iterator InsertPt = EdgeBB->begin();
1783 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1784 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1785 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1786 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1787 continue;
1788 }
1789 // Clone the instruction.
1790 Instruction *N = BBI->clone();
1791 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001792
Chris Lattner4088e2b2010-12-13 01:47:07 +00001793 // Update operands due to translation.
1794 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1795 i != e; ++i) {
1796 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1797 if (PI != TranslateMap.end())
1798 *i = PI->second;
1799 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001800
Chris Lattner4088e2b2010-12-13 01:47:07 +00001801 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001802 if (Value *V = SimplifyInstruction(N, DL)) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001803 TranslateMap[&*BBI] = V;
Chris Lattnerd7beca32010-12-14 06:17:25 +00001804 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001805 } else {
1806 // Insert the new instruction into its new home.
1807 EdgeBB->getInstList().insert(InsertPt, N);
1808 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001809 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001810 }
1811 }
1812
1813 // Loop over all of the edges from PredBB to BB, changing them to branch
1814 // to EdgeBB instead.
1815 TerminatorInst *PredBBTI = PredBB->getTerminator();
1816 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1817 if (PredBBTI->getSuccessor(i) == BB) {
1818 BB->removePredecessor(PredBB);
1819 PredBBTI->setSuccessor(i, EdgeBB);
1820 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001821
Chris Lattner4088e2b2010-12-13 01:47:07 +00001822 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001823 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001824 }
Chris Lattner748f9032005-09-19 23:49:37 +00001825
1826 return false;
1827}
1828
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001829/// Given a BB that starts with the specified two-entry PHI node,
1830/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001831static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1832 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001833 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1834 // statement", which has a very simple dominance structure. Basically, we
1835 // are trying to find the condition that is being branched on, which
1836 // subsequently causes this merge to happen. We really want control
1837 // dependence information for this check, but simplifycfg can't keep it up
1838 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001839 BasicBlock *BB = PN->getParent();
1840 BasicBlock *IfTrue, *IfFalse;
1841 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001842 if (!IfCond ||
1843 // Don't bother if the branch will be constant folded trivially.
1844 isa<ConstantInt>(IfCond))
1845 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001846
Chris Lattner95adf8f12006-11-18 19:19:36 +00001847 // Okay, we found that we can merge this two-entry phi node into a select.
1848 // Doing so would require us to fold *all* two entry phi nodes in this block.
1849 // At some point this becomes non-profitable (particularly if the target
1850 // doesn't support cmov's). Only do this transformation if there are two or
1851 // fewer PHI nodes in this block.
1852 unsigned NumPhis = 0;
1853 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1854 if (NumPhis > 2)
1855 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001856
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001857 // Loop over the PHI's seeing if we can promote them all to select
1858 // instructions. While we are at it, keep track of the instructions
1859 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001860 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001861 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1862 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00001863 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1864 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001865
Chris Lattner7499b452010-12-14 08:46:09 +00001866 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1867 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001868 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001869 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001870 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001871 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001872 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001873
Peter Collingbournee3511e12011-04-29 18:47:31 +00001874 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001875 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001876 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001877 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001878 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001879 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001880
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001881 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001882 // we ran out of PHIs then we simplified them all.
1883 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001884 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001885
Chris Lattner7499b452010-12-14 08:46:09 +00001886 // Don't fold i1 branches on PHIs which contain binary operators. These can
1887 // often be turned into switches and other things.
1888 if (PN->getType()->isIntegerTy(1) &&
1889 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1890 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1891 isa<BinaryOperator>(IfCond)))
1892 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001893
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001894 // If we all PHI nodes are promotable, check to make sure that all
1895 // instructions in the predecessor blocks can be promoted as well. If
1896 // not, we won't be able to get rid of the control flow, so it's not
1897 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001898 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001899 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1900 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1901 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001902 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001903 } else {
1904 DomBlock = *pred_begin(IfBlock1);
1905 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001906 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001907 // This is not an aggressive instruction that we can promote.
1908 // Because of this, we won't be able to get rid of the control
1909 // flow, so the xform is not worth it.
1910 return false;
1911 }
1912 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001913
Chris Lattner9ac168d2010-12-14 07:41:39 +00001914 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001915 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001916 } else {
1917 DomBlock = *pred_begin(IfBlock2);
1918 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001919 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001920 // This is not an aggressive instruction that we can promote.
1921 // Because of this, we won't be able to get rid of the control
1922 // flow, so the xform is not worth it.
1923 return false;
1924 }
1925 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001926
Chris Lattner9fd838d2010-12-14 07:23:10 +00001927 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001928 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001929
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001930 // If we can still promote the PHI nodes after this gauntlet of tests,
1931 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001932 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001933 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001934
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001935 // Move all 'aggressive' instructions, which are defined in the
1936 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001937 if (IfBlock1)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001938 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001939 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001940 IfBlock1->getTerminator()->getIterator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001941 if (IfBlock2)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001942 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001943 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001944 IfBlock2->getTerminator()->getIterator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001945
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001946 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1947 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001948 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1949 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001950
1951 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001952 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001953 PN->replaceAllUsesWith(NV);
1954 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001955 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001956 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001957
Chris Lattner335f0e42010-12-14 08:01:53 +00001958 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1959 // has been flattened. Change DomBlock to jump directly to our new block to
1960 // avoid other simplifycfg's kicking in on the diamond.
1961 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001962 Builder.SetInsertPoint(OldTI);
1963 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001964 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001965 return true;
1966}
Chris Lattner748f9032005-09-19 23:49:37 +00001967
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001968/// If we found a conditional branch that goes to two returning blocks,
1969/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00001970/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001971static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001972 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001973 assert(BI->isConditional() && "Must be a conditional branch");
1974 BasicBlock *TrueSucc = BI->getSuccessor(0);
1975 BasicBlock *FalseSucc = BI->getSuccessor(1);
1976 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1977 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001978
Chris Lattner86bbf332008-04-24 00:01:19 +00001979 // Check to ensure both blocks are empty (just a return) or optionally empty
1980 // with PHI nodes. If there are other instructions, merging would cause extra
1981 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001982 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001983 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001984 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001985 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001986
Devang Pateldd14e0f2011-05-18 21:33:11 +00001987 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001988 // Okay, we found a branch that is going to two return nodes. If
1989 // there is no return value for this function, just change the
1990 // branch into a return.
1991 if (FalseRet->getNumOperands() == 0) {
1992 TrueSucc->removePredecessor(BI->getParent());
1993 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001994 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001995 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001996 return true;
1997 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001998
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001999 // Otherwise, figure out what the true and false return values are
2000 // so we can insert a new select instruction.
2001 Value *TrueValue = TrueRet->getReturnValue();
2002 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002003
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002004 // Unwrap any PHI nodes in the return blocks.
2005 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2006 if (TVPN->getParent() == TrueSucc)
2007 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
2008 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2009 if (FVPN->getParent() == FalseSucc)
2010 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002011
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002012 // In order for this transformation to be safe, we must be able to
2013 // unconditionally execute both operands to the return. This is
2014 // normally the case, but we could have a potentially-trapping
2015 // constant expression that prevents this transformation from being
2016 // safe.
2017 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2018 if (TCV->canTrap())
2019 return false;
2020 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2021 if (FCV->canTrap())
2022 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002023
Chris Lattner86bbf332008-04-24 00:01:19 +00002024 // Okay, we collected all the mapped values and checked them for sanity, and
2025 // defined to really do this transformation. First, update the CFG.
2026 TrueSucc->removePredecessor(BI->getParent());
2027 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002028
Chris Lattner86bbf332008-04-24 00:01:19 +00002029 // Insert select instructions where needed.
2030 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002031 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002032 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002033 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2034 } else if (isa<UndefValue>(TrueValue)) {
2035 TrueValue = FalseValue;
2036 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00002037 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
2038 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00002039 }
Chris Lattner86bbf332008-04-24 00:01:19 +00002040 }
2041
Andrew Trickf3cf1932012-08-29 21:46:36 +00002042 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00002043 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2044
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00002045 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002046
David Greene725c7c32010-01-05 01:26:52 +00002047 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002048 << "\n " << *BI << "NewRet = " << *RI
2049 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002050
Eli Friedmancb61afb2008-12-16 20:54:32 +00002051 EraseTerminatorInstAndDCECond(BI);
2052
Chris Lattner86bbf332008-04-24 00:01:19 +00002053 return true;
2054}
2055
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002056/// Given a conditional BranchInstruction, retrieve the probabilities of the
2057/// branch taking each edge. Fills in the two APInt parameters and returns true,
2058/// or returns false if no or invalid metadata was found.
Juergen Ributzka194350a2014-12-09 17:32:12 +00002059static bool ExtractBranchMetadata(BranchInst *BI,
2060 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2061 assert(BI->isConditional() &&
2062 "Looking for probabilities on unconditional branch?");
2063 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2064 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002065 ConstantInt *CITrue =
2066 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2067 ConstantInt *CIFalse =
2068 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00002069 if (!CITrue || !CIFalse) return false;
2070 ProbTrue = CITrue->getValue().getZExtValue();
2071 ProbFalse = CIFalse->getValue().getZExtValue();
2072 return true;
2073}
2074
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002075/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002076/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002077static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002078 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2079 return false;
2080 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2081 Instruction *PBI = &*I;
2082 // Check whether Inst and PBI generate the same value.
2083 if (Inst->isIdenticalTo(PBI)) {
2084 Inst->replaceAllUsesWith(PBI);
2085 Inst->eraseFromParent();
2086 return true;
2087 }
2088 }
2089 return false;
2090}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002091
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002092/// If this basic block is simple enough, and if a predecessor branches to us
2093/// and one of our successors, fold the block into the predecessor and use
2094/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002095bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002096 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002097
Craig Topperf40110f2014-04-25 05:29:35 +00002098 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002099 if (BI->isConditional())
2100 Cond = dyn_cast<Instruction>(BI->getCondition());
2101 else {
2102 // For unconditional branch, check for a simple CFG pattern, where
2103 // BB has a single predecessor and BB's successor is also its predecessor's
2104 // successor. If such pattern exisits, check for CSE between BB and its
2105 // predecessor.
2106 if (BasicBlock *PB = BB->getSinglePredecessor())
2107 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2108 if (PBI->isConditional() &&
2109 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2110 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2111 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2112 I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002113 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002114 if (isa<CmpInst>(Curr)) {
2115 Cond = Curr;
2116 break;
2117 }
2118 // Quit if we can't remove this instruction.
2119 if (!checkCSEInPredecessor(Curr, PB))
2120 return false;
2121 }
2122 }
2123
Craig Topperf40110f2014-04-25 05:29:35 +00002124 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002125 return false;
2126 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002127
Craig Topperf40110f2014-04-25 05:29:35 +00002128 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2129 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002130 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002131
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002132 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002133 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002134
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002135 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002136 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002137
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002138 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002139 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002140
Jingyue Wufc029672014-09-30 22:23:38 +00002141 // Only allow this transformation if computing the condition doesn't involve
2142 // too many instructions and these involved instructions can be executed
2143 // unconditionally. We denote all involved instructions except the condition
2144 // as "bonus instructions", and only allow this transformation when the
2145 // number of the bonus instructions does not exceed a certain threshold.
2146 unsigned NumBonusInsts = 0;
2147 for (auto I = BB->begin(); Cond != I; ++I) {
2148 // Ignore dbg intrinsics.
2149 if (isa<DbgInfoIntrinsic>(I))
2150 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002151 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002152 return false;
2153 // I has only one use and can be executed unconditionally.
2154 Instruction *User = dyn_cast<Instruction>(I->user_back());
2155 if (User == nullptr || User->getParent() != BB)
2156 return false;
2157 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2158 // to use any other instruction, User must be an instruction between next(I)
2159 // and Cond.
2160 ++NumBonusInsts;
2161 // Early exits once we reach the limit.
2162 if (NumBonusInsts > BonusInstThreshold)
2163 return false;
2164 }
2165
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002166 // Cond is known to be a compare or binary operator. Check to make sure that
2167 // neither operand is a potentially-trapping constant expression.
2168 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2169 if (CE->canTrap())
2170 return false;
2171 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2172 if (CE->canTrap())
2173 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002174
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002175 // Finally, don't infinitely unroll conditional loops.
2176 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002177 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002178 if (TrueDest == BB || FalseDest == BB)
2179 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002180
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002181 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2182 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002183 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002184
Chris Lattner80b03a12008-07-13 22:23:11 +00002185 // Check that we have two conditional branches. If there is a PHI node in
2186 // the common successor, verify that the same value flows in from both
2187 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002188 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002189 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002190 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002191 !SafeToMergeTerminators(BI, PBI)) ||
2192 (!BI->isConditional() &&
2193 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002194 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002195
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002196 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002197 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002198 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002199
Manman Rend33f4ef2012-06-13 05:43:29 +00002200 if (BI->isConditional()) {
2201 if (PBI->getSuccessor(0) == TrueDest)
2202 Opc = Instruction::Or;
2203 else if (PBI->getSuccessor(1) == FalseDest)
2204 Opc = Instruction::And;
2205 else if (PBI->getSuccessor(0) == FalseDest)
2206 Opc = Instruction::And, InvertPredCond = true;
2207 else if (PBI->getSuccessor(1) == TrueDest)
2208 Opc = Instruction::Or, InvertPredCond = true;
2209 else
2210 continue;
2211 } else {
2212 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2213 continue;
2214 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002215
David Greene725c7c32010-01-05 01:26:52 +00002216 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002217 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002218
Chris Lattner55eaae12008-07-13 21:20:19 +00002219 // If we need to invert the condition in the pred block to match, do so now.
2220 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002221 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002222
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002223 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2224 CmpInst *CI = cast<CmpInst>(NewCond);
2225 CI->setPredicate(CI->getInversePredicate());
2226 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002227 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002228 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002229 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002230
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002231 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002232 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002233 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002234
Jingyue Wufc029672014-09-30 22:23:38 +00002235 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002236 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002237 // bonus instructions to a predecessor block.
2238 ValueToValueMapTy VMap; // maps original values to cloned values
2239 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002240 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002241 // instructions.
2242 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2243 if (isa<DbgInfoIntrinsic>(BonusInst))
2244 continue;
2245 Instruction *NewBonusInst = BonusInst->clone();
2246 RemapInstruction(NewBonusInst, VMap,
2247 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002248 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002249
2250 // If we moved a load, we cannot any longer claim any knowledge about
2251 // its potential value. The previous information might have been valid
2252 // only given the branch precondition.
2253 // For an analogous reason, we must also drop all the metadata whose
2254 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002255 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002256
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002257 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2258 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002259 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002260 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002261
Chris Lattner55eaae12008-07-13 21:20:19 +00002262 // Clone Cond into the predecessor basic block, and or/and the
2263 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002264 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002265 RemapInstruction(New, VMap,
2266 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002267 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002268 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002269 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002270
Manman Rend33f4ef2012-06-13 05:43:29 +00002271 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002272 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002273 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002274 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002275 PBI->setCondition(NewCond);
2276
Manman Renbfb9d432012-09-15 00:39:57 +00002277 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002278 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2279 PredFalseWeight);
2280 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2281 SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002282 SmallVector<uint64_t, 8> NewWeights;
2283
Manman Rend33f4ef2012-06-13 05:43:29 +00002284 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002285 if (PredHasWeights && SuccHasWeights) {
2286 // PBI: br i1 %x, BB, FalseDest
2287 // BI: br i1 %y, TrueDest, FalseDest
2288 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2289 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2290 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2291 // TrueWeight for PBI * FalseWeight for BI.
2292 // We assume that total weights of a BranchInst can fit into 32 bits.
2293 // Therefore, we will not have overflow using 64-bit arithmetic.
2294 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2295 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2296 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002297 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2298 PBI->setSuccessor(0, TrueDest);
2299 }
2300 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002301 if (PredHasWeights && SuccHasWeights) {
2302 // PBI: br i1 %x, TrueDest, BB
2303 // BI: br i1 %y, TrueDest, FalseDest
2304 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2305 // FalseWeight for PBI * TrueWeight for BI.
2306 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2307 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2308 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2309 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2310 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002311 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2312 PBI->setSuccessor(1, FalseDest);
2313 }
Manman Renbfb9d432012-09-15 00:39:57 +00002314 if (NewWeights.size() == 2) {
2315 // Halve the weights if any of them cannot fit in an uint32_t
2316 FitWeights(NewWeights);
2317
2318 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2319 PBI->setMetadata(LLVMContext::MD_prof,
2320 MDBuilder(BI->getContext()).
2321 createBranchWeights(MDWeights));
2322 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002323 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002324 } else {
2325 // Update PHI nodes in the common successors.
2326 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002327 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002328 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2329 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002330 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002331 if (PBI->getSuccessor(0) == TrueDest) {
2332 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2333 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2334 // is false: !PBI_Cond and BI_Value
2335 Instruction *NotCond =
2336 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2337 "not.cond"));
2338 MergedCond =
2339 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2340 NotCond, New,
2341 "and.cond"));
2342 if (PBI_C->isOne())
2343 MergedCond =
2344 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2345 PBI->getCondition(), MergedCond,
2346 "or.cond"));
2347 } else {
2348 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2349 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2350 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002351 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002352 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2353 PBI->getCondition(), New,
2354 "and.cond"));
2355 if (PBI_C->isOne()) {
2356 Instruction *NotCond =
2357 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2358 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002359 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002360 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2361 NotCond, MergedCond,
2362 "or.cond"));
2363 }
2364 }
2365 // Update PHI Node.
2366 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2367 MergedCond);
2368 }
2369 // Change PBI from Conditional to Unconditional.
2370 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2371 EraseTerminatorInstAndDCECond(PBI);
2372 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002373 }
Devang Pateld715ec82011-04-06 22:37:20 +00002374
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002375 // TODO: If BB is reachable from all paths through PredBlock, then we
2376 // could replace PBI's branch probabilities with BI's.
2377
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002378 // Copy any debug value intrinsics into the end of PredBlock.
2379 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2380 if (isa<DbgInfoIntrinsic>(*I))
2381 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002382
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002383 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002384 }
2385 return false;
2386}
2387
James Molloy4de84dd2015-11-04 15:28:04 +00002388// If there is only one store in BB1 and BB2, return it, otherwise return
2389// nullptr.
2390static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2391 StoreInst *S = nullptr;
2392 for (auto *BB : {BB1, BB2}) {
2393 if (!BB)
2394 continue;
2395 for (auto &I : *BB)
2396 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2397 if (S)
2398 // Multiple stores seen.
2399 return nullptr;
2400 else
2401 S = SI;
2402 }
2403 }
2404 return S;
2405}
2406
2407static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2408 Value *AlternativeV = nullptr) {
2409 // PHI is going to be a PHI node that allows the value V that is defined in
2410 // BB to be referenced in BB's only successor.
2411 //
2412 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2413 // doesn't matter to us what the other operand is (it'll never get used). We
2414 // could just create a new PHI with an undef incoming value, but that could
2415 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2416 // other PHI. So here we directly look for some PHI in BB's successor with V
2417 // as an incoming operand. If we find one, we use it, else we create a new
2418 // one.
2419 //
2420 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2421 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2422 // where OtherBB is the single other predecessor of BB's only successor.
2423 PHINode *PHI = nullptr;
2424 BasicBlock *Succ = BB->getSingleSuccessor();
2425
2426 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2427 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2428 PHI = cast<PHINode>(I);
2429 if (!AlternativeV)
2430 break;
2431
2432 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2433 auto PredI = pred_begin(Succ);
2434 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2435 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2436 break;
2437 PHI = nullptr;
2438 }
2439 if (PHI)
2440 return PHI;
2441
James Molloy3d21dcf2015-12-16 14:12:44 +00002442 // If V is not an instruction defined in BB, just return it.
2443 if (!AlternativeV &&
2444 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2445 return V;
2446
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002447 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
James Molloy4de84dd2015-11-04 15:28:04 +00002448 PHI->addIncoming(V, BB);
2449 for (BasicBlock *PredBB : predecessors(Succ))
2450 if (PredBB != BB)
2451 PHI->addIncoming(AlternativeV ? AlternativeV : UndefValue::get(V->getType()),
2452 PredBB);
2453 return PHI;
2454}
2455
2456static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2457 BasicBlock *QTB, BasicBlock *QFB,
2458 BasicBlock *PostBB, Value *Address,
2459 bool InvertPCond, bool InvertQCond) {
2460 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2461 return Operator::getOpcode(&I) == Instruction::BitCast &&
2462 I.getType()->isPointerTy();
2463 };
2464
2465 // If we're not in aggressive mode, we only optimize if we have some
2466 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2467 auto IsWorthwhile = [&](BasicBlock *BB) {
2468 if (!BB)
2469 return true;
2470 // Heuristic: if the block can be if-converted/phi-folded and the
2471 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2472 // thread this store.
James Molloy9e959ac2015-11-05 08:40:19 +00002473 unsigned N = 0;
2474 for (auto &I : *BB) {
2475 // Cheap instructions viable for folding.
2476 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2477 isa<StoreInst>(I))
2478 ++N;
2479 // Free instructions.
2480 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2481 IsaBitcastOfPointerType(I))
2482 continue;
2483 else
James Molloy4de84dd2015-11-04 15:28:04 +00002484 return false;
James Molloy9e959ac2015-11-05 08:40:19 +00002485 }
2486 return N <= PHINodeFoldingThreshold;
James Molloy4de84dd2015-11-04 15:28:04 +00002487 };
2488
2489 if (!MergeCondStoresAggressively && (!IsWorthwhile(PTB) ||
2490 !IsWorthwhile(PFB) ||
2491 !IsWorthwhile(QTB) ||
2492 !IsWorthwhile(QFB)))
2493 return false;
2494
2495 // For every pointer, there must be exactly two stores, one coming from
2496 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2497 // store (to any address) in PTB,PFB or QTB,QFB.
2498 // FIXME: We could relax this restriction with a bit more work and performance
2499 // testing.
2500 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2501 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2502 if (!PStore || !QStore)
2503 return false;
2504
2505 // Now check the stores are compatible.
2506 if (!QStore->isUnordered() || !PStore->isUnordered())
2507 return false;
2508
2509 // Check that sinking the store won't cause program behavior changes. Sinking
2510 // the store out of the Q blocks won't change any behavior as we're sinking
2511 // from a block to its unconditional successor. But we're moving a store from
2512 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2513 // So we need to check that there are no aliasing loads or stores in
2514 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2515 // operations between PStore and the end of its parent block.
2516 //
2517 // The ideal way to do this is to query AliasAnalysis, but we don't
2518 // preserve AA currently so that is dangerous. Be super safe and just
2519 // check there are no other memory operations at all.
2520 for (auto &I : *QFB->getSinglePredecessor())
2521 if (I.mayReadOrWriteMemory())
2522 return false;
2523 for (auto &I : *QFB)
2524 if (&I != QStore && I.mayReadOrWriteMemory())
2525 return false;
2526 if (QTB)
2527 for (auto &I : *QTB)
2528 if (&I != QStore && I.mayReadOrWriteMemory())
2529 return false;
2530 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2531 I != E; ++I)
2532 if (&*I != PStore && I->mayReadOrWriteMemory())
2533 return false;
2534
2535 // OK, we're going to sink the stores to PostBB. The store has to be
2536 // conditional though, so first create the predicate.
2537 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2538 ->getCondition();
2539 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2540 ->getCondition();
2541
2542 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2543 PStore->getParent());
2544 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2545 QStore->getParent(), PPHI);
2546
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002547 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2548
James Molloy4de84dd2015-11-04 15:28:04 +00002549 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2550 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2551
2552 if (InvertPCond)
2553 PPred = QB.CreateNot(PPred);
2554 if (InvertQCond)
2555 QPred = QB.CreateNot(QPred);
2556 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2557
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002558 auto *T =
2559 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
James Molloy4de84dd2015-11-04 15:28:04 +00002560 QB.SetInsertPoint(T);
2561 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2562 AAMDNodes AAMD;
2563 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2564 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2565 SI->setAAMetadata(AAMD);
2566
2567 QStore->eraseFromParent();
2568 PStore->eraseFromParent();
2569
2570 return true;
2571}
2572
2573static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) {
2574 // The intention here is to find diamonds or triangles (see below) where each
2575 // conditional block contains a store to the same address. Both of these
2576 // stores are conditional, so they can't be unconditionally sunk. But it may
2577 // be profitable to speculatively sink the stores into one merged store at the
2578 // end, and predicate the merged store on the union of the two conditions of
2579 // PBI and QBI.
2580 //
2581 // This can reduce the number of stores executed if both of the conditions are
2582 // true, and can allow the blocks to become small enough to be if-converted.
2583 // This optimization will also chain, so that ladders of test-and-set
2584 // sequences can be if-converted away.
2585 //
2586 // We only deal with simple diamonds or triangles:
2587 //
2588 // PBI or PBI or a combination of the two
2589 // / \ | \
2590 // PTB PFB | PFB
2591 // \ / | /
2592 // QBI QBI
2593 // / \ | \
2594 // QTB QFB | QFB
2595 // \ / | /
2596 // PostBB PostBB
2597 //
2598 // We model triangles as a type of diamond with a nullptr "true" block.
2599 // Triangles are canonicalized so that the fallthrough edge is represented by
2600 // a true condition, as in the diagram above.
2601 //
2602 BasicBlock *PTB = PBI->getSuccessor(0);
2603 BasicBlock *PFB = PBI->getSuccessor(1);
2604 BasicBlock *QTB = QBI->getSuccessor(0);
2605 BasicBlock *QFB = QBI->getSuccessor(1);
2606 BasicBlock *PostBB = QFB->getSingleSuccessor();
2607
2608 bool InvertPCond = false, InvertQCond = false;
2609 // Canonicalize fallthroughs to the true branches.
2610 if (PFB == QBI->getParent()) {
2611 std::swap(PFB, PTB);
2612 InvertPCond = true;
2613 }
2614 if (QFB == PostBB) {
2615 std::swap(QFB, QTB);
2616 InvertQCond = true;
2617 }
2618
2619 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
2620 // and QFB may not. Model fallthroughs as a nullptr block.
2621 if (PTB == QBI->getParent())
2622 PTB = nullptr;
2623 if (QTB == PostBB)
2624 QTB = nullptr;
2625
2626 // Legality bailouts. We must have at least the non-fallthrough blocks and
2627 // the post-dominating block, and the non-fallthroughs must only have one
2628 // predecessor.
2629 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
2630 return BB->getSinglePredecessor() == P &&
2631 BB->getSingleSuccessor() == S;
2632 };
2633 if (!PostBB ||
2634 !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
2635 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
2636 return false;
2637 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
2638 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
2639 return false;
2640 if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2)
2641 return false;
2642
2643 // OK, this is a sequence of two diamonds or triangles.
2644 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
2645 SmallPtrSet<Value *,4> PStoreAddresses, QStoreAddresses;
2646 for (auto *BB : {PTB, PFB}) {
2647 if (!BB)
2648 continue;
2649 for (auto &I : *BB)
2650 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2651 PStoreAddresses.insert(SI->getPointerOperand());
2652 }
2653 for (auto *BB : {QTB, QFB}) {
2654 if (!BB)
2655 continue;
2656 for (auto &I : *BB)
2657 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2658 QStoreAddresses.insert(SI->getPointerOperand());
2659 }
2660
2661 set_intersect(PStoreAddresses, QStoreAddresses);
2662 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
2663 // clear what it contains.
2664 auto &CommonAddresses = PStoreAddresses;
2665
2666 bool Changed = false;
2667 for (auto *Address : CommonAddresses)
2668 Changed |= mergeConditionalStoreToAddress(
2669 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond);
2670 return Changed;
2671}
2672
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002673/// If we have a conditional branch as a predecessor of another block,
2674/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00002675/// that PBI and BI are both conditional branches, and BI is in one of the
2676/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00002677static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
2678 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00002679 assert(PBI->isConditional() && BI->isConditional());
2680 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002681
Chris Lattner9aada1d2008-07-13 21:53:26 +00002682 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002683 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002684 // this conditional branch redundant.
2685 if (PBI->getCondition() == BI->getCondition() &&
2686 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2687 // Okay, the outcome of this conditional branch is statically
2688 // knowable. If this block had a single pred, handle specially.
2689 if (BB->getSinglePredecessor()) {
2690 // Turn this into a branch on constant.
2691 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002692 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002693 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002694 return true; // Nuke the branch on constant.
2695 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002696
Chris Lattner9aada1d2008-07-13 21:53:26 +00002697 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2698 // in the constant and simplify the block result. Subsequent passes of
2699 // simplifycfg will thread the block.
2700 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002701 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002702 PHINode *NewPN = PHINode::Create(
2703 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
2704 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00002705 // Okay, we're going to insert the PHI node. Since PBI is not the only
2706 // predecessor, compute the PHI'd conditional value for all of the preds.
2707 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002708 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002709 BasicBlock *P = *PI;
2710 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002711 PBI != BI && PBI->isConditional() &&
2712 PBI->getCondition() == BI->getCondition() &&
2713 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2714 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002715 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002716 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002717 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002718 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002719 }
Gabor Greif8629f122010-07-12 10:59:23 +00002720 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002721
Chris Lattner9aada1d2008-07-13 21:53:26 +00002722 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002723 return true;
2724 }
2725 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002726
Philip Reamesb42db212015-10-14 22:46:19 +00002727 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2728 if (CE->canTrap())
2729 return false;
2730
Philip Reames846e3e42015-10-29 03:11:49 +00002731 // If BI is reached from the true path of PBI and PBI's condition implies
2732 // BI's condition, we know the direction of the BI branch.
2733 if (PBI->getSuccessor(0) == BI->getParent() &&
Sanjoy Das55ea67c2015-11-06 19:01:08 +00002734 isImpliedCondition(PBI->getCondition(), BI->getCondition(), DL) &&
Philip Reames846e3e42015-10-29 03:11:49 +00002735 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
2736 BB->getSinglePredecessor()) {
2737 // Turn this into a branch on constant.
2738 auto *OldCond = BI->getCondition();
2739 BI->setCondition(ConstantInt::getTrue(BB->getContext()));
2740 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
2741 return true; // Nuke the branch on constant.
2742 }
2743
James Molloy4de84dd2015-11-04 15:28:04 +00002744 // If both branches are conditional and both contain stores to the same
2745 // address, remove the stores from the conditionals and create a conditional
2746 // merged store at the end.
2747 if (MergeCondStores && mergeConditionalStores(PBI, BI))
2748 return true;
2749
Chris Lattner9aada1d2008-07-13 21:53:26 +00002750 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002751 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002752 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002753 BasicBlock::iterator BBI = BB->begin();
2754 // Ignore dbg intrinsics.
2755 while (isa<DbgInfoIntrinsic>(BBI))
2756 ++BBI;
2757 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002758 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002759
Chris Lattner834ab4e2008-07-13 22:04:41 +00002760 int PBIOp, BIOp;
2761 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2762 PBIOp = BIOp = 0;
2763 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2764 PBIOp = 0, BIOp = 1;
2765 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2766 PBIOp = 1, BIOp = 0;
2767 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2768 PBIOp = BIOp = 1;
2769 else
2770 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002771
Chris Lattner834ab4e2008-07-13 22:04:41 +00002772 // Check to make sure that the other destination of this branch
2773 // isn't BB itself. If so, this is an infinite loop that will
2774 // keep getting unwound.
2775 if (PBI->getSuccessor(PBIOp) == BB)
2776 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002777
2778 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002779 // insertion of a large number of select instructions. For targets
2780 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002781
Sanjay Patela932da82014-07-07 21:19:00 +00002782 // Also do not perform this transformation if any phi node in the common
2783 // destination block can trap when reached by BB or PBB (PR17073). In that
2784 // case, it would be unsafe to hoist the operation into a select instruction.
2785
2786 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002787 unsigned NumPhis = 0;
2788 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002789 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002790 if (NumPhis > 2) // Disable this xform.
2791 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002792
Sanjay Patela932da82014-07-07 21:19:00 +00002793 PHINode *PN = cast<PHINode>(II);
2794 Value *BIV = PN->getIncomingValueForBlock(BB);
2795 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2796 if (CE->canTrap())
2797 return false;
2798
2799 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2800 Value *PBIV = PN->getIncomingValue(PBBIdx);
2801 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2802 if (CE->canTrap())
2803 return false;
2804 }
2805
Chris Lattner834ab4e2008-07-13 22:04:41 +00002806 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002807 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002808
David Greene725c7c32010-01-05 01:26:52 +00002809 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002810 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002811
2812
Chris Lattner80b03a12008-07-13 22:23:11 +00002813 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2814 // branch in it, where one edge (OtherDest) goes back to itself but the other
2815 // exits. We don't *know* that the program avoids the infinite loop
2816 // (even though that seems likely). If we do this xform naively, we'll end up
2817 // recursively unpeeling the loop. Since we know that (after the xform is
2818 // done) that the block *is* infinite if reached, we just make it an obviously
2819 // infinite loop with no cond branch.
2820 if (OtherDest == BB) {
2821 // Insert it at the end of the function, because it's either code,
2822 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002823 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2824 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002825 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2826 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002827 }
2828
David Greene725c7c32010-01-05 01:26:52 +00002829 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002830
Chris Lattner834ab4e2008-07-13 22:04:41 +00002831 // BI may have other predecessors. Because of this, we leave
2832 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002833
Chris Lattner834ab4e2008-07-13 22:04:41 +00002834 // Make sure we get to CommonDest on True&True directions.
2835 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002836 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002837 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002838 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2839
Chris Lattner834ab4e2008-07-13 22:04:41 +00002840 Value *BICond = BI->getCondition();
2841 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002842 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2843
Chris Lattner834ab4e2008-07-13 22:04:41 +00002844 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002845 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002846
Chris Lattner834ab4e2008-07-13 22:04:41 +00002847 // Modify PBI to branch on the new condition to the new dests.
2848 PBI->setCondition(Cond);
2849 PBI->setSuccessor(0, CommonDest);
2850 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002851
Manman Ren2d4c10f2012-09-17 21:30:40 +00002852 // Update branch weight for PBI.
2853 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002854 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2855 PredFalseWeight);
2856 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2857 SuccFalseWeight);
Manman Ren2d4c10f2012-09-17 21:30:40 +00002858 if (PredHasWeights && SuccHasWeights) {
2859 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2860 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2861 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2862 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2863 // The weight to CommonDest should be PredCommon * SuccTotal +
2864 // PredOther * SuccCommon.
2865 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00002866 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2867 PredOther * SuccCommon,
2868 PredOther * SuccOther};
Manman Ren2d4c10f2012-09-17 21:30:40 +00002869 // Halve the weights if any of them cannot fit in an uint32_t
2870 FitWeights(NewWeights);
2871
Manman Ren2d4c10f2012-09-17 21:30:40 +00002872 PBI->setMetadata(LLVMContext::MD_prof,
Benjamin Kramerea68a942015-02-19 15:26:17 +00002873 MDBuilder(BI->getContext())
2874 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00002875 }
2876
Chris Lattner834ab4e2008-07-13 22:04:41 +00002877 // OtherDest may have phi nodes. If so, add an entry from PBI's
2878 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002879 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002880
Chris Lattner834ab4e2008-07-13 22:04:41 +00002881 // We know that the CommonDest already had an edge from PBI to
2882 // it. If it has PHIs though, the PHIs may have different
2883 // entries for BB and PBI's BB. If so, insert a select to make
2884 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002885 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002886 for (BasicBlock::iterator II = CommonDest->begin();
2887 (PN = dyn_cast<PHINode>(II)); ++II) {
2888 Value *BIV = PN->getIncomingValueForBlock(BB);
2889 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2890 Value *PBIV = PN->getIncomingValue(PBBIdx);
2891 if (BIV != PBIV) {
2892 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002893 Value *NV = cast<SelectInst>
2894 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002895 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002896 }
2897 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002898
David Greene725c7c32010-01-05 01:26:52 +00002899 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2900 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002901
Chris Lattner834ab4e2008-07-13 22:04:41 +00002902 // This basic block is probably dead. We know it has at least
2903 // one fewer predecessor.
2904 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002905}
2906
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002907// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2908// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00002909// Takes care of updating the successors and removing the old terminator.
2910// Also makes sure not to introduce new successors by assuming that edges to
2911// non-successor TrueBBs and FalseBBs aren't reachable.
2912static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002913 BasicBlock *TrueBB, BasicBlock *FalseBB,
2914 uint32_t TrueWeight,
2915 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002916 // Remove any superfluous successor edges from the CFG.
2917 // First, figure out which successors to preserve.
2918 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2919 // successor.
2920 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002921 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002922
2923 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00002924 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002925 // Make sure only to keep exactly one copy of each edge.
2926 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002927 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002928 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002929 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002930 else
David Majnemerdc3b67b2015-10-21 18:22:24 +00002931 Succ->removePredecessor(OldTerm->getParent(),
2932 /*DontDeleteUselessPHIs=*/true);
Frits van Bommel8e158492011-01-11 12:52:11 +00002933 }
2934
Devang Patel2c2ea222011-05-18 18:43:31 +00002935 IRBuilder<> Builder(OldTerm);
2936 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2937
Frits van Bommel8e158492011-01-11 12:52:11 +00002938 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002939 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002940 if (TrueBB == FalseBB)
2941 // We were only looking for one successor, and it was present.
2942 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002943 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002944 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002945 // We found both of the successors we were looking for.
2946 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002947 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2948 if (TrueWeight != FalseWeight)
2949 NewBI->setMetadata(LLVMContext::MD_prof,
2950 MDBuilder(OldTerm->getContext()).
2951 createBranchWeights(TrueWeight, FalseWeight));
2952 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002953 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2954 // Neither of the selected blocks were successors, so this
2955 // terminator must be unreachable.
2956 new UnreachableInst(OldTerm->getContext(), OldTerm);
2957 } else {
2958 // One of the selected values was a successor, but the other wasn't.
2959 // Insert an unconditional branch to the one that was found;
2960 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002961 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002962 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002963 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002964 else
2965 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002966 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002967 }
2968
2969 EraseTerminatorInstAndDCECond(OldTerm);
2970 return true;
2971}
2972
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002973// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00002974// (switch (select cond, X, Y)) on constant X, Y
2975// with a branch - conditional if X and Y lead to distinct BBs,
2976// unconditional otherwise.
2977static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2978 // Check for constant integer values in the select.
2979 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2980 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2981 if (!TrueVal || !FalseVal)
2982 return false;
2983
2984 // Find the relevant condition and destinations.
2985 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002986 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2987 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002988
Manman Ren774246a2012-09-17 22:28:55 +00002989 // Get weight for TrueBB and FalseBB.
2990 uint32_t TrueWeight = 0, FalseWeight = 0;
2991 SmallVector<uint64_t, 8> Weights;
2992 bool HasWeights = HasBranchWeights(SI);
2993 if (HasWeights) {
2994 GetBranchWeights(SI, Weights);
2995 if (Weights.size() == 1 + SI->getNumCases()) {
2996 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2997 getSuccessorIndex()];
2998 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2999 getSuccessorIndex()];
3000 }
3001 }
3002
Frits van Bommel8ae07992011-02-28 09:44:07 +00003003 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00003004 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
3005 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00003006}
3007
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003008// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003009// (indirectbr (select cond, blockaddress(@fn, BlockA),
3010// blockaddress(@fn, BlockB)))
3011// with
3012// (br cond, BlockA, BlockB).
3013static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
3014 // Check that both operands of the select are block addresses.
3015 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3016 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3017 if (!TBA || !FBA)
3018 return false;
3019
3020 // Extract the actual blocks.
3021 BasicBlock *TrueBB = TBA->getBasicBlock();
3022 BasicBlock *FalseBB = FBA->getBasicBlock();
3023
Frits van Bommel8e158492011-01-11 12:52:11 +00003024 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00003025 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
3026 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003027}
3028
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003029/// This is called when we find an icmp instruction
3030/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003031/// block that ends with an uncond branch. We are looking for a very specific
3032/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3033/// this case, we merge the first two "or's of icmp" into a switch, but then the
3034/// default value goes to an uncond block with a seteq in it, we get something
3035/// like:
3036///
3037/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3038/// DEFAULT:
3039/// %tmp = icmp eq i8 %A, 92
3040/// br label %end
3041/// end:
3042/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00003043///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003044/// We prefer to split the edge to 'end' so that there is a true/false entry to
3045/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003046static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003047 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
3048 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
3049 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003050 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00003051
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003052 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3053 // complex.
3054 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
3055
3056 Value *V = ICI->getOperand(0);
3057 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00003058
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003059 // The pattern we're looking for is where our only predecessor is a switch on
3060 // 'V' and this block is the default case for the switch. In this case we can
3061 // fold the compared value into the switch to simplify things.
3062 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00003063 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003064
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003065 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3066 if (SI->getCondition() != V)
3067 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003068
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003069 // If BB is reachable on a non-default case, then we simply know the value of
3070 // V in this block. Substitute it and constant fold the icmp instruction
3071 // away.
3072 if (SI->getDefaultDest() != BB) {
3073 ConstantInt *VVal = SI->findCaseDest(BB);
3074 assert(VVal && "Should have a unique destination value");
3075 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003076
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003077 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00003078 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003079 ICI->eraseFromParent();
3080 }
3081 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003082 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003083 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003084
Chris Lattner62cc76e2010-12-13 03:43:57 +00003085 // Ok, the block is reachable from the default dest. If the constant we're
3086 // comparing exists in one of the other edges, then we can constant fold ICI
3087 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003088 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00003089 Value *V;
3090 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3091 V = ConstantInt::getFalse(BB->getContext());
3092 else
3093 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003094
Chris Lattner62cc76e2010-12-13 03:43:57 +00003095 ICI->replaceAllUsesWith(V);
3096 ICI->eraseFromParent();
3097 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003098 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00003099 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003100
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003101 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3102 // the block.
3103 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003104 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00003105 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003106 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3107 return false;
3108
3109 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3110 // true in the PHI.
3111 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3112 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3113
3114 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3115 std::swap(DefaultCst, NewCst);
3116
3117 // Replace ICI (which is used by the PHI for the default value) with true or
3118 // false depending on if it is EQ or NE.
3119 ICI->replaceAllUsesWith(DefaultCst);
3120 ICI->eraseFromParent();
3121
3122 // Okay, the switch goes to this block on a default value. Add an edge from
3123 // the switch to the merge point on the compared value.
3124 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
3125 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00003126 SmallVector<uint64_t, 8> Weights;
3127 bool HasWeights = HasBranchWeights(SI);
3128 if (HasWeights) {
3129 GetBranchWeights(SI, Weights);
3130 if (Weights.size() == 1 + SI->getNumCases()) {
3131 // Split weight for default case to case for "Cst".
3132 Weights[0] = (Weights[0]+1) >> 1;
3133 Weights.push_back(Weights[0]);
3134
3135 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3136 SI->setMetadata(LLVMContext::MD_prof,
3137 MDBuilder(SI->getContext()).
3138 createBranchWeights(MDWeights));
3139 }
3140 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003141 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003142
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003143 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00003144 Builder.SetInsertPoint(NewBB);
3145 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3146 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003147 PHIUse->addIncoming(NewCst, NewBB);
3148 return true;
3149}
3150
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003151/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003152/// Check to see if it is branching on an or/and chain of icmp instructions, and
3153/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003154static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3155 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003156 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00003157 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003158
Chris Lattnera69c4432010-12-13 05:03:41 +00003159 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3160 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3161 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003162
Mehdi Amini9a25cb82014-11-19 20:09:11 +00003163 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00003164 ConstantComparesGatherer ConstantCompare(Cond, DL);
3165 // Unpack the result
3166 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
3167 Value *CompVal = ConstantCompare.CompValue;
3168 unsigned UsedICmps = ConstantCompare.UsedICmps;
3169 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003170
Chris Lattnera69c4432010-12-13 05:03:41 +00003171 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00003172 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00003173
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003174 // Avoid turning single icmps into a switch.
3175 if (UsedICmps <= 1)
3176 return false;
3177
Mehdi Aminiffd01002014-11-20 22:40:25 +00003178 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3179
Chris Lattnera69c4432010-12-13 05:03:41 +00003180 // There might be duplicate constants in the list, which the switch
3181 // instruction can't handle, remove them now.
3182 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3183 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003184
Chris Lattnera69c4432010-12-13 05:03:41 +00003185 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00003186 // transformation. A switch with one value is just a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003187 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003188
Andrew Trick3051aa12012-08-29 21:46:38 +00003189 // TODO: Preserve branch weight metadata, similarly to how
3190 // FoldValueComparisonIntoPredecessors preserves it.
3191
Chris Lattnera69c4432010-12-13 05:03:41 +00003192 // Figure out which block is which destination.
3193 BasicBlock *DefaultBB = BI->getSuccessor(1);
3194 BasicBlock *EdgeBB = BI->getSuccessor(0);
3195 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003196
Chris Lattnera69c4432010-12-13 05:03:41 +00003197 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003198
Chris Lattnerd7beca32010-12-14 06:17:25 +00003199 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003200 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003201
Chris Lattnera69c4432010-12-13 05:03:41 +00003202 // If there are any extra values that couldn't be folded into the switch
3203 // then we evaluate them with an explicit branch first. Split the block
3204 // right before the condbr to handle it.
3205 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003206 BasicBlock *NewBB =
3207 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00003208 // Remove the uncond branch added to the old block.
3209 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00003210 Builder.SetInsertPoint(OldTI);
3211
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003212 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00003213 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003214 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00003215 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003216
Chris Lattnera69c4432010-12-13 05:03:41 +00003217 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003218
Chris Lattnercb570f82010-12-13 05:34:18 +00003219 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3220 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003221 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003222
Chris Lattnerd7beca32010-12-14 06:17:25 +00003223 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
3224 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00003225 BB = NewBB;
3226 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00003227
3228 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00003229 // Convert pointer to int before we switch.
3230 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003231 CompVal = Builder.CreatePtrToInt(
3232 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00003233 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003234
Chris Lattnera69c4432010-12-13 05:03:41 +00003235 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00003236 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00003237
Chris Lattnera69c4432010-12-13 05:03:41 +00003238 // Add all of the 'cases' to the switch instruction.
3239 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3240 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003241
Chris Lattnera69c4432010-12-13 05:03:41 +00003242 // We added edges from PI to the EdgeBB. As such, if there were any
3243 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3244 // the number of edges added.
3245 for (BasicBlock::iterator BBI = EdgeBB->begin();
3246 isa<PHINode>(BBI); ++BBI) {
3247 PHINode *PN = cast<PHINode>(BBI);
3248 Value *InVal = PN->getIncomingValueForBlock(BB);
3249 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
3250 PN->addIncoming(InVal, BB);
3251 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003252
Chris Lattnera69c4432010-12-13 05:03:41 +00003253 // Erase the old branch instruction.
3254 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003255
Chris Lattnerd7beca32010-12-14 06:17:25 +00003256 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00003257 return true;
3258}
3259
Duncan Sands29192d02011-09-05 12:57:57 +00003260bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
Chen Li1689c2f2016-01-10 05:48:01 +00003261 if (isa<PHINode>(RI->getValue()))
3262 return SimplifyCommonResume(RI);
3263 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3264 RI->getValue() == RI->getParent()->getFirstNonPHI())
3265 // The resume must unwind the exception that caused control to branch here.
3266 return SimplifySingleResume(RI);
Chen Li509ff212016-01-11 19:20:53 +00003267
3268 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003269}
3270
3271// Simplify resume that is shared by several landing pads (phi of landing pad).
3272bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3273 BasicBlock *BB = RI->getParent();
3274
3275 // Check that there are no other instructions except for debug intrinsics
3276 // between the phi of landing pads (RI->getValue()) and resume instruction.
3277 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
3278 E = RI->getIterator();
3279 while (++I != E)
3280 if (!isa<DbgInfoIntrinsic>(I))
3281 return false;
3282
3283 SmallSet<BasicBlock *, 4> TrivialUnwindBlocks;
3284 auto *PhiLPInst = cast<PHINode>(RI->getValue());
3285
3286 // Check incoming blocks to see if any of them are trivial.
3287 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues();
3288 Idx != End; Idx++) {
3289 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3290 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3291
3292 // If the block has other successors, we can not delete it because
3293 // it has other dependents.
3294 if (IncomingBB->getUniqueSuccessor() != BB)
3295 continue;
3296
3297 auto *LandingPad =
3298 dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
3299 // Not the landing pad that caused the control to branch here.
3300 if (IncomingValue != LandingPad)
3301 continue;
3302
3303 bool isTrivial = true;
3304
3305 I = IncomingBB->getFirstNonPHI()->getIterator();
3306 E = IncomingBB->getTerminator()->getIterator();
3307 while (++I != E)
3308 if (!isa<DbgInfoIntrinsic>(I)) {
3309 isTrivial = false;
3310 break;
3311 }
3312
3313 if (isTrivial)
3314 TrivialUnwindBlocks.insert(IncomingBB);
3315 }
3316
3317 // If no trivial unwind blocks, don't do any simplifications.
3318 if (TrivialUnwindBlocks.empty()) return false;
3319
3320 // Turn all invokes that unwind here into calls.
3321 for (auto *TrivialBB : TrivialUnwindBlocks) {
3322 // Blocks that will be simplified should be removed from the phi node.
3323 // Note there could be multiple edges to the resume block, and we need
3324 // to remove them all.
3325 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3326 BB->removePredecessor(TrivialBB, true);
3327
3328 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3329 PI != PE;) {
3330 BasicBlock *Pred = *PI++;
3331 removeUnwindEdge(Pred);
3332 }
3333
3334 // In each SimplifyCFG run, only the current processed block can be erased.
3335 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3336 // of erasing TrivialBB, we only remove the branch to the common resume
3337 // block so that we can later erase the resume block since it has no
3338 // predecessors.
3339 TrivialBB->getTerminator()->eraseFromParent();
3340 new UnreachableInst(RI->getContext(), TrivialBB);
3341 }
3342
3343 // Delete the resume block if all its predecessors have been removed.
3344 if (pred_empty(BB))
3345 BB->eraseFromParent();
3346
3347 return !TrivialUnwindBlocks.empty();
3348}
3349
3350// Simplify resume that is only used by a single (non-phi) landing pad.
3351bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
Duncan Sands29192d02011-09-05 12:57:57 +00003352 BasicBlock *BB = RI->getParent();
3353 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
Chen Li1689c2f2016-01-10 05:48:01 +00003354 assert (RI->getValue() == LPInst &&
3355 "Resume must unwind the exception that caused control to here");
Duncan Sands29192d02011-09-05 12:57:57 +00003356
Chen Li7009cd32015-10-23 21:13:01 +00003357 // Check that there are no other instructions except for debug intrinsics.
3358 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
Duncan Sands29192d02011-09-05 12:57:57 +00003359 while (++I != E)
3360 if (!isa<DbgInfoIntrinsic>(I))
3361 return false;
3362
Chen Lic6e28782015-10-22 20:48:38 +00003363 // Turn all invokes that unwind here into calls and delete the basic block.
Chen Li7009cd32015-10-23 21:13:01 +00003364 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3365 BasicBlock *Pred = *PI++;
3366 removeUnwindEdge(Pred);
Chen Lic6e28782015-10-22 20:48:38 +00003367 }
3368
Chen Li7009cd32015-10-23 21:13:01 +00003369 // The landingpad is now unreachable. Zap it.
3370 BB->eraseFromParent();
3371 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00003372}
3373
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003374bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
3375 // If this is a trivial cleanup pad that executes no instructions, it can be
3376 // eliminated. If the cleanup pad continues to the caller, any predecessor
3377 // that is an EH pad will be updated to continue to the caller and any
3378 // predecessor that terminates with an invoke instruction will have its invoke
3379 // instruction converted to a call instruction. If the cleanup pad being
3380 // simplified does not continue to the caller, each predecessor will be
3381 // updated to continue to the unwind destination of the cleanup pad being
3382 // simplified.
3383 BasicBlock *BB = RI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003384 CleanupPadInst *CPInst = RI->getCleanupPad();
3385 if (CPInst->getParent() != BB)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003386 // This isn't an empty cleanup.
3387 return false;
3388
3389 // Check that there are no other instructions except for debug intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003390 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003391 while (++I != E)
3392 if (!isa<DbgInfoIntrinsic>(I))
3393 return false;
3394
David Majnemer8a1c45d2015-12-12 05:38:55 +00003395 // If the cleanup return we are simplifying unwinds to the caller, this will
3396 // set UnwindDest to nullptr.
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003397 BasicBlock *UnwindDest = RI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003398 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003399
3400 // We're about to remove BB from the control flow. Before we do, sink any
3401 // PHINodes into the unwind destination. Doing this before changing the
3402 // control flow avoids some potentially slow checks, since we can currently
3403 // be certain that UnwindDest and BB have no common predecessors (since they
3404 // are both EH pads).
3405 if (UnwindDest) {
3406 // First, go through the PHI nodes in UnwindDest and update any nodes that
3407 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003408 for (BasicBlock::iterator I = UnwindDest->begin(),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003409 IE = DestEHPad->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003410 I != IE; ++I) {
3411 PHINode *DestPN = cast<PHINode>(I);
James Molloy4de84dd2015-11-04 15:28:04 +00003412
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003413 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003414 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003415 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003416 // This PHI node has an incoming value that corresponds to a control
3417 // path through the cleanup pad we are removing. If the incoming
3418 // value is in the cleanup pad, it must be a PHINode (because we
3419 // verified above that the block is otherwise empty). Otherwise, the
3420 // value is either a constant or a value that dominates the cleanup
3421 // pad being removed.
3422 //
3423 // Because BB and UnwindDest are both EH pads, all of their
3424 // predecessors must unwind to these blocks, and since no instruction
3425 // can have multiple unwind destinations, there will be no overlap in
3426 // incoming blocks between SrcPN and DestPN.
3427 Value *SrcVal = DestPN->getIncomingValue(Idx);
3428 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3429
3430 // Remove the entry for the block we are deleting.
3431 DestPN->removeIncomingValue(Idx, false);
3432
3433 if (SrcPN && SrcPN->getParent() == BB) {
3434 // If the incoming value was a PHI node in the cleanup pad we are
3435 // removing, we need to merge that PHI node's incoming values into
3436 // DestPN.
James Molloy4de84dd2015-11-04 15:28:04 +00003437 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003438 SrcIdx != SrcE; ++SrcIdx) {
3439 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3440 SrcPN->getIncomingBlock(SrcIdx));
3441 }
3442 } else {
3443 // Otherwise, the incoming value came from above BB and
3444 // so we can just reuse it. We must associate all of BB's
3445 // predecessors with this value.
3446 for (auto *pred : predecessors(BB)) {
3447 DestPN->addIncoming(SrcVal, pred);
3448 }
3449 }
3450 }
3451
3452 // Sink any remaining PHI nodes directly into UnwindDest.
David Majnemer8a1c45d2015-12-12 05:38:55 +00003453 Instruction *InsertPt = DestEHPad;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003454 for (BasicBlock::iterator I = BB->begin(),
3455 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003456 I != IE;) {
3457 // The iterator must be incremented here because the instructions are
3458 // being moved to another block.
3459 PHINode *PN = cast<PHINode>(I++);
3460 if (PN->use_empty())
3461 // If the PHI node has no uses, just leave it. It will be erased
3462 // when we erase BB below.
3463 continue;
3464
3465 // Otherwise, sink this PHI node into UnwindDest.
3466 // Any predecessors to UnwindDest which are not already represented
3467 // must be back edges which inherit the value from the path through
3468 // BB. In this case, the PHI value must reference itself.
3469 for (auto *pred : predecessors(UnwindDest))
3470 if (pred != BB)
3471 PN->addIncoming(PN, pred);
3472 PN->moveBefore(InsertPt);
3473 }
3474 }
3475
3476 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3477 // The iterator must be updated here because we are removing this pred.
3478 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003479 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003480 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003481 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003482 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003483 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003484 }
3485 }
3486
3487 // The cleanup pad is now unreachable. Zap it.
3488 BB->eraseFromParent();
3489 return true;
3490}
3491
Devang Pateldd14e0f2011-05-18 21:33:11 +00003492bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003493 BasicBlock *BB = RI->getParent();
3494 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003495
Chris Lattner25c3af32010-12-13 06:25:44 +00003496 // Find predecessors that end with branches.
3497 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3498 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003499 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3500 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003501 TerminatorInst *PTI = P->getTerminator();
3502 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3503 if (BI->isUnconditional())
3504 UncondBranchPreds.push_back(P);
3505 else
3506 CondBranchPreds.push_back(BI);
3507 }
3508 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003509
Chris Lattner25c3af32010-12-13 06:25:44 +00003510 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00003511 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003512 while (!UncondBranchPreds.empty()) {
3513 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3514 DEBUG(dbgs() << "FOLDING: " << *BB
3515 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00003516 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00003517 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003518
Chris Lattner25c3af32010-12-13 06:25:44 +00003519 // If we eliminated all predecessors of the block, delete the block now.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003520 if (pred_empty(BB))
Chris Lattner25c3af32010-12-13 06:25:44 +00003521 // We know there are no successors, so just nuke the block.
3522 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003523
Chris Lattner25c3af32010-12-13 06:25:44 +00003524 return true;
3525 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003526
Chris Lattner25c3af32010-12-13 06:25:44 +00003527 // Check out all of the conditional branches going to this return
3528 // instruction. If any of them just select between returns, change the
3529 // branch itself into a select/return pair.
3530 while (!CondBranchPreds.empty()) {
3531 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003532
Chris Lattner25c3af32010-12-13 06:25:44 +00003533 // Check to see if the non-BB successor is also a return block.
3534 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3535 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003536 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003537 return true;
3538 }
3539 return false;
3540}
3541
Chris Lattner25c3af32010-12-13 06:25:44 +00003542bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3543 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003544
Chris Lattner25c3af32010-12-13 06:25:44 +00003545 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003546
Chris Lattner25c3af32010-12-13 06:25:44 +00003547 // If there are any instructions immediately before the unreachable that can
3548 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003549 while (UI->getIterator() != BB->begin()) {
3550 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00003551 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003552 // Do not delete instructions that can have side effects which might cause
3553 // the unreachable to not be reachable; specifically, calls and volatile
3554 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003555 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003556
3557 if (BBI->mayHaveSideEffects()) {
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003558 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003559 if (SI->isVolatile())
3560 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003561 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003562 if (LI->isVolatile())
3563 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003564 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003565 if (RMWI->isVolatile())
3566 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003567 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003568 if (CXI->isVolatile())
3569 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003570 } else if (isa<CatchPadInst>(BBI)) {
3571 // A catchpad may invoke exception object constructors and such, which
3572 // in some languages can be arbitrary code, so be conservative by
3573 // default.
3574 // For CoreCLR, it just involves a type test, so can be removed.
3575 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
3576 EHPersonality::CoreCLR)
3577 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003578 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3579 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003580 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003581 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003582 // Note that deleting LandingPad's here is in fact okay, although it
3583 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3584 // all the predecessors of this block will be the unwind edges of Invokes,
3585 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003586 }
3587
Eli Friedmanaac35b32011-03-09 00:48:33 +00003588 // Delete this instruction (any uses are guaranteed to be dead)
3589 if (!BBI->use_empty())
3590 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003591 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003592 Changed = true;
3593 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003594
Chris Lattner25c3af32010-12-13 06:25:44 +00003595 // If the unreachable instruction is the first in the block, take a gander
3596 // at all of the predecessors of this instruction, and simplify them.
3597 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003598
Chris Lattner25c3af32010-12-13 06:25:44 +00003599 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3600 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3601 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003602 IRBuilder<> Builder(TI);
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003603 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003604 if (BI->isUnconditional()) {
3605 if (BI->getSuccessor(0) == BB) {
3606 new UnreachableInst(TI->getContext(), TI);
3607 TI->eraseFromParent();
3608 Changed = true;
3609 }
3610 } else {
3611 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003612 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003613 EraseTerminatorInstAndDCECond(BI);
3614 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003615 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003616 EraseTerminatorInstAndDCECond(BI);
3617 Changed = true;
3618 }
3619 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003620 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003621 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003622 i != e; ++i)
3623 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003624 BB->removePredecessor(SI->getParent());
3625 SI->removeCase(i);
3626 --i; --e;
3627 Changed = true;
3628 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003629 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
3630 if (II->getUnwindDest() == BB) {
3631 removeUnwindEdge(TI->getParent());
3632 Changed = true;
3633 }
3634 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3635 if (CSI->getUnwindDest() == BB) {
3636 removeUnwindEdge(TI->getParent());
3637 Changed = true;
3638 continue;
3639 }
3640
3641 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
3642 E = CSI->handler_end();
3643 I != E; ++I) {
3644 if (*I == BB) {
3645 CSI->removeHandler(I);
3646 --I;
3647 --E;
3648 Changed = true;
3649 }
3650 }
3651 if (CSI->getNumHandlers() == 0) {
3652 BasicBlock *CatchSwitchBB = CSI->getParent();
3653 if (CSI->hasUnwindDest()) {
3654 // Redirect preds to the unwind dest
3655 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
3656 } else {
3657 // Rewrite all preds to unwind to caller (or from invoke to call).
3658 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
3659 for (BasicBlock *EHPred : EHPreds)
3660 removeUnwindEdge(EHPred);
3661 }
3662 // The catchswitch is no longer reachable.
3663 new UnreachableInst(CSI->getContext(), CSI);
3664 CSI->eraseFromParent();
3665 Changed = true;
3666 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003667 } else if (isa<CleanupReturnInst>(TI)) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003668 new UnreachableInst(TI->getContext(), TI);
3669 TI->eraseFromParent();
3670 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00003671 }
3672 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003673
Chris Lattner25c3af32010-12-13 06:25:44 +00003674 // If this block is now dead, remove it.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003675 if (pred_empty(BB) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00003676 BB != &BB->getParent()->getEntryBlock()) {
3677 // We know there are no successors, so just nuke the block.
3678 BB->eraseFromParent();
3679 return true;
3680 }
3681
3682 return Changed;
3683}
3684
Hans Wennborg68000082015-01-26 19:52:32 +00003685static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3686 assert(Cases.size() >= 1);
3687
3688 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3689 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3690 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3691 return false;
3692 }
3693 return true;
3694}
3695
3696/// Turn a switch with two reachable destinations into an integer range
3697/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003698static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003699 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003700
Hans Wennborg68000082015-01-26 19:52:32 +00003701 bool HasDefault =
3702 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003703
Hans Wennborg68000082015-01-26 19:52:32 +00003704 // Partition the cases into two sets with different destinations.
3705 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3706 BasicBlock *DestB = nullptr;
3707 SmallVector <ConstantInt *, 16> CasesA;
3708 SmallVector <ConstantInt *, 16> CasesB;
3709
3710 for (SwitchInst::CaseIt I : SI->cases()) {
3711 BasicBlock *Dest = I.getCaseSuccessor();
3712 if (!DestA) DestA = Dest;
3713 if (Dest == DestA) {
3714 CasesA.push_back(I.getCaseValue());
3715 continue;
3716 }
3717 if (!DestB) DestB = Dest;
3718 if (Dest == DestB) {
3719 CasesB.push_back(I.getCaseValue());
3720 continue;
3721 }
3722 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003723 }
3724
Hans Wennborg68000082015-01-26 19:52:32 +00003725 assert(DestA && DestB && "Single-destination switch should have been folded.");
3726 assert(DestA != DestB);
3727 assert(DestB != SI->getDefaultDest());
3728 assert(!CasesB.empty() && "There must be non-default cases.");
3729 assert(!CasesA.empty() || HasDefault);
3730
3731 // Figure out if one of the sets of cases form a contiguous range.
3732 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3733 BasicBlock *ContiguousDest = nullptr;
3734 BasicBlock *OtherDest = nullptr;
3735 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3736 ContiguousCases = &CasesA;
3737 ContiguousDest = DestA;
3738 OtherDest = DestB;
3739 } else if (CasesAreContiguous(CasesB)) {
3740 ContiguousCases = &CasesB;
3741 ContiguousDest = DestB;
3742 OtherDest = DestA;
3743 } else
3744 return false;
3745
3746 // Start building the compare and branch.
3747
3748 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3749 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003750
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003751 Value *Sub = SI->getCondition();
3752 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00003753 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3754
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003755 Value *Cmp;
3756 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00003757 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003758 Cmp = ConstantInt::getTrue(SI->getContext());
3759 else
3760 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00003761 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003762
Manman Ren56575552012-09-18 00:47:33 +00003763 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00003764 if (HasBranchWeights(SI)) {
3765 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00003766 GetBranchWeights(SI, Weights);
3767 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00003768 uint64_t TrueWeight = 0;
3769 uint64_t FalseWeight = 0;
3770 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3771 if (SI->getSuccessor(I) == ContiguousDest)
3772 TrueWeight += Weights[I];
3773 else
3774 FalseWeight += Weights[I];
3775 }
3776 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3777 TrueWeight /= 2;
3778 FalseWeight /= 2;
3779 }
Manman Ren56575552012-09-18 00:47:33 +00003780 NewBI->setMetadata(LLVMContext::MD_prof,
Hans Wennborg68000082015-01-26 19:52:32 +00003781 MDBuilder(SI->getContext()).createBranchWeights(
3782 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00003783 }
3784 }
3785
Hans Wennborg68000082015-01-26 19:52:32 +00003786 // Prune obsolete incoming values off the successors' PHI nodes.
3787 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3788 unsigned PreviousEdges = ContiguousCases->size();
3789 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3790 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003791 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3792 }
Hans Wennborg68000082015-01-26 19:52:32 +00003793 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3794 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3795 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3796 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3797 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3798 }
3799
3800 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003801 SI->eraseFromParent();
3802
3803 return true;
3804}
Chris Lattner25c3af32010-12-13 06:25:44 +00003805
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003806/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003807/// and use it to remove dead cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003808static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3809 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003810 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003811 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003812 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003813 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003814
3815 // Gather dead cases.
3816 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003817 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003818 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3819 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3820 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003821 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003822 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003823 }
3824 }
3825
Philip Reames98a2dab2015-08-26 23:56:46 +00003826 // If we can prove that the cases must cover all possible values, the
Philip Reames05370132015-09-10 17:44:47 +00003827 // default destination becomes dead and we can remove it. If we know some
3828 // of the bits in the value, we can use that to more precisely compute the
3829 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00003830 bool HasDefault =
3831 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Philip Reames05370132015-09-10 17:44:47 +00003832 const unsigned NumUnknownBits = Bits -
3833 (KnownZero.Or(KnownOne)).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00003834 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00003835 if (HasDefault && DeadCases.empty() &&
3836 NumUnknownBits < 64 /* avoid overflow */ &&
3837 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00003838 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
3839 BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(),
3840 SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003841 SI->setDefaultDest(&*NewDefault);
3842 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00003843 auto *OldTI = NewDefault->getTerminator();
3844 new UnreachableInst(SI->getContext(), OldTI);
3845 EraseTerminatorInstAndDCECond(OldTI);
3846 return true;
3847 }
3848
Manman Ren56575552012-09-18 00:47:33 +00003849 SmallVector<uint64_t, 8> Weights;
3850 bool HasWeight = HasBranchWeights(SI);
3851 if (HasWeight) {
3852 GetBranchWeights(SI, Weights);
3853 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3854 }
3855
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003856 // Remove dead cases from the switch.
3857 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003858 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003859 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003860 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003861 if (HasWeight) {
3862 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3863 Weights.pop_back();
3864 }
3865
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003866 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003867 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003868 SI->removeCase(Case);
3869 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003870 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003871 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3872 SI->setMetadata(LLVMContext::MD_prof,
3873 MDBuilder(SI->getParent()->getContext()).
3874 createBranchWeights(MDWeights));
3875 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003876
3877 return !DeadCases.empty();
3878}
3879
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003880/// If BB would be eligible for simplification by
3881/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003882/// by an unconditional branch), look at the phi node for BB in the successor
3883/// block and see if the incoming value is equal to CaseValue. If so, return
3884/// the phi node, and set PhiIndex to BB's index in the phi node.
3885static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3886 BasicBlock *BB,
3887 int *PhiIndex) {
3888 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003889 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003890 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003891 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003892
3893 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3894 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003895 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003896
3897 BasicBlock *Succ = Branch->getSuccessor(0);
3898
3899 BasicBlock::iterator I = Succ->begin();
3900 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3901 int Idx = PHI->getBasicBlockIndex(BB);
3902 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3903
3904 Value *InValue = PHI->getIncomingValue(Idx);
3905 if (InValue != CaseValue) continue;
3906
3907 *PhiIndex = Idx;
3908 return PHI;
3909 }
3910
Craig Topperf40110f2014-04-25 05:29:35 +00003911 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003912}
3913
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003914/// Try to forward the condition of a switch instruction to a phi node
3915/// dominated by the switch, if that would mean that some of the destination
3916/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003917/// Returns true if a change is made.
3918static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3919 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3920 ForwardingNodesMap ForwardingNodes;
3921
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003922 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003923 ConstantInt *CaseValue = I.getCaseValue();
3924 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003925
3926 int PhiIndex;
3927 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3928 &PhiIndex);
3929 if (!PHI) continue;
3930
3931 ForwardingNodes[PHI].push_back(PhiIndex);
3932 }
3933
3934 bool Changed = false;
3935
3936 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3937 E = ForwardingNodes.end(); I != E; ++I) {
3938 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003939 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003940
3941 if (Indexes.size() < 2) continue;
3942
3943 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3944 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3945 Changed = true;
3946 }
3947
3948 return Changed;
3949}
3950
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003951/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003952/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003953static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003954 if (C->isThreadDependent())
3955 return false;
3956 if (C->isDLLImportDependent())
3957 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003958
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003959 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3960 return CE->isGEPWithNoNotionalOverIndexing();
3961
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003962 return isa<ConstantFP>(C) ||
3963 isa<ConstantInt>(C) ||
3964 isa<ConstantPointerNull>(C) ||
3965 isa<GlobalValue>(C) ||
3966 isa<UndefValue>(C);
3967}
3968
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003969/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003970/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003971static Constant *LookupConstant(Value *V,
3972 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3973 if (Constant *C = dyn_cast<Constant>(V))
3974 return C;
3975 return ConstantPool.lookup(V);
3976}
3977
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003978/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003979/// simple instructions such as binary operations where both operands are
3980/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003981/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003982static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003983ConstantFold(Instruction *I, const DataLayout &DL,
3984 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003985 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003986 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3987 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003988 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003989 if (A->isAllOnesValue())
3990 return LookupConstant(Select->getTrueValue(), ConstantPool);
3991 if (A->isNullValue())
3992 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003993 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003994 }
3995
Benjamin Kramer7c302602013-11-12 12:24:36 +00003996 SmallVector<Constant *, 4> COps;
3997 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3998 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3999 COps.push_back(A);
4000 else
Craig Topperf40110f2014-04-25 05:29:35 +00004001 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004002 }
4003
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004004 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00004005 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4006 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004007 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00004008
Manuel Jacobe9024592016-01-21 06:33:22 +00004009 return ConstantFoldInstOperands(I, COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004010}
4011
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004012/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004013/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004014/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004015/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00004016static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004017GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00004018 BasicBlock **CommonDest,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004019 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
4020 const DataLayout &DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004021 // The block from which we enter the common destination.
4022 BasicBlock *Pred = SI->getParent();
4023
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004024 // If CaseDest is empty except for some side-effect free instructions through
4025 // which we can constant-propagate the CaseVal, continue to its successor.
4026 SmallDenseMap<Value*, Constant*> ConstantPool;
4027 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4028 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4029 ++I) {
4030 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4031 // If the terminator is a simple branch, continue to the next block.
4032 if (T->getNumSuccessors() != 1)
4033 return false;
4034 Pred = CaseDest;
4035 CaseDest = T->getSuccessor(0);
4036 } else if (isa<DbgInfoIntrinsic>(I)) {
4037 // Skip debug intrinsic.
4038 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004039 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004040 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00004041
4042 // If the instruction has uses outside this block or a phi node slot for
4043 // the block, it is not safe to bypass the instruction since it would then
4044 // no longer dominate all its uses.
4045 for (auto &Use : I->uses()) {
4046 User *User = Use.getUser();
4047 if (Instruction *I = dyn_cast<Instruction>(User))
4048 if (I->getParent() == CaseDest)
4049 continue;
4050 if (PHINode *Phi = dyn_cast<PHINode>(User))
4051 if (Phi->getIncomingBlock(Use) == CaseDest)
4052 continue;
4053 return false;
4054 }
4055
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004056 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004057 } else {
4058 break;
4059 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004060 }
4061
4062 // If we did not have a CommonDest before, use the current one.
4063 if (!*CommonDest)
4064 *CommonDest = CaseDest;
4065 // If the destination isn't the common one, abort.
4066 if (CaseDest != *CommonDest)
4067 return false;
4068
4069 // Get the values for this case from phi nodes in the destination block.
4070 BasicBlock::iterator I = (*CommonDest)->begin();
4071 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4072 int Idx = PHI->getBasicBlockIndex(Pred);
4073 if (Idx == -1)
4074 continue;
4075
Hans Wennborg09acdb92012-10-31 15:14:39 +00004076 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
4077 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004078 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004079 return false;
4080
4081 // Be conservative about which kinds of constants we support.
4082 if (!ValidLookupTableConstant(ConstVal))
4083 return false;
4084
4085 Res.push_back(std::make_pair(PHI, ConstVal));
4086 }
4087
Hans Wennborgac114a32014-01-12 00:44:41 +00004088 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004089}
4090
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004091// Helper function used to add CaseVal to the list of cases that generate
4092// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004093static void MapCaseToResult(ConstantInt *CaseVal,
4094 SwitchCaseResultVectorTy &UniqueResults,
4095 Constant *Result) {
4096 for (auto &I : UniqueResults) {
4097 if (I.first == Result) {
4098 I.second.push_back(CaseVal);
4099 return;
4100 }
4101 }
4102 UniqueResults.push_back(std::make_pair(Result,
4103 SmallVector<ConstantInt*, 4>(1, CaseVal)));
4104}
4105
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004106// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004107// results for the PHI node of the common destination block for a switch
4108// instruction. Returns false if multiple PHI nodes have been found or if
4109// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004110static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4111 BasicBlock *&CommonDest,
4112 SwitchCaseResultVectorTy &UniqueResults,
4113 Constant *&DefaultResult,
4114 const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004115 for (auto &I : SI->cases()) {
4116 ConstantInt *CaseVal = I.getCaseValue();
4117
4118 // Resulting value at phi nodes for this case value.
4119 SwitchCaseResultsTy Results;
4120 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4121 DL))
4122 return false;
4123
4124 // Only one value per case is permitted
4125 if (Results.size() > 1)
4126 return false;
4127 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4128
4129 // Check the PHI consistency.
4130 if (!PHI)
4131 PHI = Results[0].first;
4132 else if (PHI != Results[0].first)
4133 return false;
4134 }
4135 // Find the default result value.
4136 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4137 BasicBlock *DefaultDest = SI->getDefaultDest();
4138 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4139 DL);
4140 // If the default value is not found abort unless the default destination
4141 // is unreachable.
4142 DefaultResult =
4143 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4144 if ((!DefaultResult &&
4145 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
4146 return false;
4147
4148 return true;
4149}
4150
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004151// Helper function that checks if it is possible to transform a switch with only
4152// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004153// Example:
4154// switch (a) {
4155// case 10: %0 = icmp eq i32 %a, 10
4156// return 10; %1 = select i1 %0, i32 10, i32 4
4157// case 20: ----> %2 = icmp eq i32 %a, 20
4158// return 2; %3 = select i1 %2, i32 2, i32 %1
4159// default:
4160// return 4;
4161// }
4162static Value *
4163ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4164 Constant *DefaultResult, Value *Condition,
4165 IRBuilder<> &Builder) {
4166 assert(ResultVector.size() == 2 &&
4167 "We should have exactly two unique results at this point");
4168 // If we are selecting between only two cases transform into a simple
4169 // select or a two-way select if default is possible.
4170 if (ResultVector[0].second.size() == 1 &&
4171 ResultVector[1].second.size() == 1) {
4172 ConstantInt *const FirstCase = ResultVector[0].second[0];
4173 ConstantInt *const SecondCase = ResultVector[1].second[0];
4174
4175 bool DefaultCanTrigger = DefaultResult;
4176 Value *SelectValue = ResultVector[1].first;
4177 if (DefaultCanTrigger) {
4178 Value *const ValueCompare =
4179 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4180 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4181 DefaultResult, "switch.select");
4182 }
4183 Value *const ValueCompare =
4184 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
4185 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
4186 "switch.select");
4187 }
4188
4189 return nullptr;
4190}
4191
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004192// Helper function to cleanup a switch instruction that has been converted into
4193// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004194static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4195 Value *SelectValue,
4196 IRBuilder<> &Builder) {
4197 BasicBlock *SelectBB = SI->getParent();
4198 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4199 PHI->removeIncomingValue(SelectBB);
4200 PHI->addIncoming(SelectValue, SelectBB);
4201
4202 Builder.CreateBr(PHI->getParent());
4203
4204 // Remove the switch.
4205 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4206 BasicBlock *Succ = SI->getSuccessor(i);
4207
4208 if (Succ == PHI->getParent())
4209 continue;
4210 Succ->removePredecessor(SelectBB);
4211 }
4212 SI->eraseFromParent();
4213}
4214
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004215/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004216/// phi nodes in a common successor block with only two different
4217/// constant values, replace the switch with select.
4218static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004219 AssumptionCache *AC, const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004220 Value *const Cond = SI->getCondition();
4221 PHINode *PHI = nullptr;
4222 BasicBlock *CommonDest = nullptr;
4223 Constant *DefaultResult;
4224 SwitchCaseResultVectorTy UniqueResults;
4225 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004226 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4227 DL))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004228 return false;
4229 // Selects choose between maximum two values.
4230 if (UniqueResults.size() != 2)
4231 return false;
4232 assert(PHI != nullptr && "PHI for value select not found");
4233
4234 Builder.SetInsertPoint(SI);
4235 Value *SelectValue = ConvertTwoCaseSwitch(
4236 UniqueResults,
4237 DefaultResult, Cond, Builder);
4238 if (SelectValue) {
4239 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4240 return true;
4241 }
4242 // The switch couldn't be converted into a select.
4243 return false;
4244}
4245
Hans Wennborg776d7122012-09-26 09:34:53 +00004246namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004247 /// This class represents a lookup table that can be used to replace a switch.
Hans Wennborg776d7122012-09-26 09:34:53 +00004248 class SwitchLookupTable {
4249 public:
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004250 /// Create a lookup table to use as a switch replacement with the contents
4251 /// of Values, using DefaultValue to fill any holes in the table.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004252 SwitchLookupTable(
4253 Module &M, uint64_t TableSize, ConstantInt *Offset,
4254 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4255 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004256
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004257 /// Build instructions with Builder to retrieve the value at
Hans Wennborg776d7122012-09-26 09:34:53 +00004258 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00004259 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00004260
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004261 /// Return true if a table with TableSize elements of
Hans Wennborg39583b82012-09-26 09:44:49 +00004262 /// type ElementType would fit in a target-legal register.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004263 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004264 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004265
Hans Wennborg776d7122012-09-26 09:34:53 +00004266 private:
4267 // Depending on the contents of the table, it can be represented in
4268 // different ways.
4269 enum {
4270 // For tables where each element contains the same value, we just have to
4271 // store that single value and return it for each lookup.
4272 SingleValueKind,
4273
Erik Eckstein105374f2014-11-17 09:13:57 +00004274 // For tables where there is a linear relationship between table index
4275 // and values. We calculate the result with a simple multiplication
4276 // and addition instead of a table lookup.
4277 LinearMapKind,
4278
Hans Wennborg39583b82012-09-26 09:44:49 +00004279 // For small tables with integer elements, we can pack them into a bitmap
4280 // that fits into a target-legal register. Values are retrieved by
4281 // shift and mask operations.
4282 BitMapKind,
4283
Hans Wennborg776d7122012-09-26 09:34:53 +00004284 // The table is stored as an array of values. Values are retrieved by load
4285 // instructions from the table.
4286 ArrayKind
4287 } Kind;
4288
4289 // For SingleValueKind, this is the single value.
4290 Constant *SingleValue;
4291
Hans Wennborg39583b82012-09-26 09:44:49 +00004292 // For BitMapKind, this is the bitmap.
4293 ConstantInt *BitMap;
4294 IntegerType *BitMapElementTy;
4295
Erik Eckstein105374f2014-11-17 09:13:57 +00004296 // For LinearMapKind, these are the constants used to derive the value.
4297 ConstantInt *LinearOffset;
4298 ConstantInt *LinearMultiplier;
4299
Hans Wennborg776d7122012-09-26 09:34:53 +00004300 // For ArrayKind, this is the array.
4301 GlobalVariable *Array;
4302 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +00004303}
Hans Wennborg776d7122012-09-26 09:34:53 +00004304
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004305SwitchLookupTable::SwitchLookupTable(
4306 Module &M, uint64_t TableSize, ConstantInt *Offset,
4307 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4308 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00004309 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00004310 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004311 assert(Values.size() && "Can't build lookup table without values!");
4312 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004313
4314 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00004315 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004316
Hans Wennborgac114a32014-01-12 00:44:41 +00004317 Type *ValueType = Values.begin()->second->getType();
4318
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004319 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00004320 SmallVector<Constant*, 64> TableContents(TableSize);
4321 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4322 ConstantInt *CaseVal = Values[I].first;
4323 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00004324 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004325
Hans Wennborg776d7122012-09-26 09:34:53 +00004326 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
4327 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004328 TableContents[Idx] = CaseRes;
4329
Hans Wennborg776d7122012-09-26 09:34:53 +00004330 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004331 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004332 }
4333
4334 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00004335 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00004336 assert(DefaultValue &&
4337 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00004338 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00004339 for (uint64_t I = 0; I < TableSize; ++I) {
4340 if (!TableContents[I])
4341 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004342 }
4343
Hans Wennborg776d7122012-09-26 09:34:53 +00004344 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004345 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004346 }
4347
Hans Wennborg776d7122012-09-26 09:34:53 +00004348 // If each element in the table contains the same value, we only need to store
4349 // that single value.
4350 if (SingleValue) {
4351 Kind = SingleValueKind;
4352 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004353 }
4354
Erik Eckstein105374f2014-11-17 09:13:57 +00004355 // Check if we can derive the value with a linear transformation from the
4356 // table index.
4357 if (isa<IntegerType>(ValueType)) {
4358 bool LinearMappingPossible = true;
4359 APInt PrevVal;
4360 APInt DistToPrev;
4361 assert(TableSize >= 2 && "Should be a SingleValue table.");
4362 // Check if there is the same distance between two consecutive values.
4363 for (uint64_t I = 0; I < TableSize; ++I) {
4364 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4365 if (!ConstVal) {
4366 // This is an undef. We could deal with it, but undefs in lookup tables
4367 // are very seldom. It's probably not worth the additional complexity.
4368 LinearMappingPossible = false;
4369 break;
4370 }
4371 APInt Val = ConstVal->getValue();
4372 if (I != 0) {
4373 APInt Dist = Val - PrevVal;
4374 if (I == 1) {
4375 DistToPrev = Dist;
4376 } else if (Dist != DistToPrev) {
4377 LinearMappingPossible = false;
4378 break;
4379 }
4380 }
4381 PrevVal = Val;
4382 }
4383 if (LinearMappingPossible) {
4384 LinearOffset = cast<ConstantInt>(TableContents[0]);
4385 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4386 Kind = LinearMapKind;
4387 ++NumLinearMaps;
4388 return;
4389 }
4390 }
4391
Hans Wennborg39583b82012-09-26 09:44:49 +00004392 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004393 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004394 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004395 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4396 for (uint64_t I = TableSize; I > 0; --I) {
4397 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00004398 // Insert values into the bitmap. Undef values are set to zero.
4399 if (!isa<UndefValue>(TableContents[I - 1])) {
4400 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4401 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4402 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004403 }
4404 BitMap = ConstantInt::get(M.getContext(), TableInt);
4405 BitMapElementTy = IT;
4406 Kind = BitMapKind;
4407 ++NumBitMaps;
4408 return;
4409 }
4410
Hans Wennborg776d7122012-09-26 09:34:53 +00004411 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004412 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004413 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4414
Hans Wennborg776d7122012-09-26 09:34:53 +00004415 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
4416 GlobalVariable::PrivateLinkage,
4417 Initializer,
4418 "switch.table");
4419 Array->setUnnamedAddr(true);
4420 Kind = ArrayKind;
4421}
4422
Manman Ren4d189fb2014-07-24 21:13:20 +00004423Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004424 switch (Kind) {
4425 case SingleValueKind:
4426 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00004427 case LinearMapKind: {
4428 // Derive the result value from the input value.
4429 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4430 false, "switch.idx.cast");
4431 if (!LinearMultiplier->isOne())
4432 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4433 if (!LinearOffset->isZero())
4434 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4435 return Result;
4436 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004437 case BitMapKind: {
4438 // Type of the bitmap (e.g. i59).
4439 IntegerType *MapTy = BitMap->getType();
4440
4441 // Cast Index to the same type as the bitmap.
4442 // Note: The Index is <= the number of elements in the table, so
4443 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00004444 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004445
4446 // Multiply the shift amount by the element width.
4447 ShiftAmt = Builder.CreateMul(ShiftAmt,
4448 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4449 "switch.shiftamt");
4450
4451 // Shift down.
4452 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
4453 "switch.downshift");
4454 // Mask off.
4455 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
4456 "switch.masked");
4457 }
Hans Wennborg776d7122012-09-26 09:34:53 +00004458 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00004459 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00004460 IntegerType *IT = cast<IntegerType>(Index->getType());
4461 uint64_t TableSize = Array->getInitializer()->getType()
4462 ->getArrayNumElements();
4463 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4464 Index = Builder.CreateZExt(Index,
4465 IntegerType::get(IT->getContext(),
4466 IT->getBitWidth() + 1),
4467 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00004468
Hans Wennborg776d7122012-09-26 09:34:53 +00004469 Value *GEPIndices[] = { Builder.getInt32(0), Index };
David Blaikieaa41cd52015-04-03 21:33:42 +00004470 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4471 GEPIndices, "switch.gep");
Hans Wennborg776d7122012-09-26 09:34:53 +00004472 return Builder.CreateLoad(GEP, "switch.load");
4473 }
4474 }
4475 llvm_unreachable("Unknown lookup table kind!");
4476}
4477
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004478bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00004479 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004480 Type *ElementType) {
4481 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004482 if (!IT)
4483 return false;
4484 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4485 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004486
4487 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4488 if (TableSize >= UINT_MAX/IT->getBitWidth())
4489 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004490 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00004491}
4492
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004493/// Determine whether a lookup table should be built for this switch, based on
4494/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004495static bool
4496ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4497 const TargetTransformInfo &TTI, const DataLayout &DL,
4498 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004499 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4500 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00004501
Chandler Carruth77d433d2012-11-30 09:26:25 +00004502 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00004503 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00004504 for (const auto &I : ResultTypes) {
4505 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004506
4507 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004508 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004509
4510 // Saturate this flag to false.
4511 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004512 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004513
4514 // If both flags saturate, we're done. NOTE: This *only* works with
4515 // saturating flags, and all flags have to saturate first due to the
4516 // non-deterministic behavior of iterating over a dense map.
4517 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00004518 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00004519 }
Evan Cheng65df8082012-11-30 02:02:42 +00004520
Chandler Carruth77d433d2012-11-30 09:26:25 +00004521 // If each table would fit in a register, we should build it anyway.
4522 if (AllTablesFitInRegister)
4523 return true;
4524
4525 // Don't build a table that doesn't fit in-register if it has illegal types.
4526 if (HasIllegalType)
4527 return false;
4528
4529 // The table density should be at least 40%. This is the same criterion as for
4530 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4531 // FIXME: Find the best cut-off.
4532 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004533}
4534
Erik Eckstein0d86c762014-11-27 15:13:14 +00004535/// Try to reuse the switch table index compare. Following pattern:
4536/// \code
4537/// if (idx < tablesize)
4538/// r = table[idx]; // table does not contain default_value
4539/// else
4540/// r = default_value;
4541/// if (r != default_value)
4542/// ...
4543/// \endcode
4544/// Is optimized to:
4545/// \code
4546/// cond = idx < tablesize;
4547/// if (cond)
4548/// r = table[idx];
4549/// else
4550/// r = default_value;
4551/// if (cond)
4552/// ...
4553/// \endcode
4554/// Jump threading will then eliminate the second if(cond).
4555static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4556 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4557 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4558
4559 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4560 if (!CmpInst)
4561 return;
4562
4563 // We require that the compare is in the same block as the phi so that jump
4564 // threading can do its work afterwards.
4565 if (CmpInst->getParent() != PhiBlock)
4566 return;
4567
4568 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4569 if (!CmpOp1)
4570 return;
4571
4572 Value *RangeCmp = RangeCheckBranch->getCondition();
4573 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4574 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4575
4576 // Check if the compare with the default value is constant true or false.
4577 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4578 DefaultValue, CmpOp1, true);
4579 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4580 return;
4581
4582 // Check if the compare with the case values is distinct from the default
4583 // compare result.
4584 for (auto ValuePair : Values) {
4585 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4586 ValuePair.second, CmpOp1, true);
4587 if (!CaseConst || CaseConst == DefaultConst)
4588 return;
4589 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4590 "Expect true or false as compare result.");
4591 }
James Molloy4de84dd2015-11-04 15:28:04 +00004592
Erik Eckstein0d86c762014-11-27 15:13:14 +00004593 // Check if the branch instruction dominates the phi node. It's a simple
4594 // dominance check, but sufficient for our needs.
4595 // Although this check is invariant in the calling loops, it's better to do it
4596 // at this late stage. Practically we do it at most once for a switch.
4597 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4598 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4599 BasicBlock *Pred = *PI;
4600 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4601 return;
4602 }
4603
4604 if (DefaultConst == FalseConst) {
4605 // The compare yields the same result. We can replace it.
4606 CmpInst->replaceAllUsesWith(RangeCmp);
4607 ++NumTableCmpReuses;
4608 } else {
4609 // The compare yields the same result, just inverted. We can replace it.
4610 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4611 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4612 RangeCheckBranch);
4613 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4614 ++NumTableCmpReuses;
4615 }
4616}
4617
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004618/// If the switch is only used to initialize one or more phi nodes in a common
4619/// successor block with different constant values, replace the switch with
4620/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004621static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4622 const DataLayout &DL,
4623 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004624 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004625
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004626 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004627 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004628 return false;
4629
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004630 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4631 // split off a dense part and build a lookup table for that.
4632
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004633 // FIXME: This creates arrays of GEPs to constant strings, which means each
4634 // GEP needs a runtime relocation in PIC code. We should just build one big
4635 // string and lookup indices into that.
4636
Hans Wennborg4744ac12014-01-15 05:00:27 +00004637 // Ignore switches with less than three cases. Lookup tables will not make them
4638 // faster, so we don't analyze them.
4639 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004640 return false;
4641
4642 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00004643 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004644 assert(SI->case_begin() != SI->case_end());
4645 SwitchInst::CaseIt CI = SI->case_begin();
4646 ConstantInt *MinCaseVal = CI.getCaseValue();
4647 ConstantInt *MaxCaseVal = CI.getCaseValue();
4648
Craig Topperf40110f2014-04-25 05:29:35 +00004649 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004650 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004651 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4652 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4653 SmallDenseMap<PHINode*, Type*> ResultTypes;
4654 SmallVector<PHINode*, 4> PHIs;
4655
4656 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4657 ConstantInt *CaseVal = CI.getCaseValue();
4658 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4659 MinCaseVal = CaseVal;
4660 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4661 MaxCaseVal = CaseVal;
4662
4663 // Resulting value at phi nodes for this case value.
4664 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4665 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004666 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004667 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004668 return false;
4669
4670 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004671 for (const auto &I : Results) {
4672 PHINode *PHI = I.first;
4673 Constant *Value = I.second;
4674 if (!ResultLists.count(PHI))
4675 PHIs.push_back(PHI);
4676 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004677 }
4678 }
4679
Hans Wennborgac114a32014-01-12 00:44:41 +00004680 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004681 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004682 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4683 }
4684
4685 uint64_t NumResults = ResultLists[PHIs[0]].size();
4686 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4687 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4688 bool TableHasHoles = (NumResults < TableSize);
4689
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004690 // If the table has holes, we need a constant result for the default case
4691 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004692 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00004693 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004694 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00004695
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004696 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4697 if (NeedMask) {
4698 // As an extra penalty for the validity test we require more cases.
4699 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4700 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004701 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004702 return false;
4703 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004704
Hans Wennborga6a11a92014-11-18 02:37:11 +00004705 for (const auto &I : DefaultResultsList) {
4706 PHINode *PHI = I.first;
4707 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004708 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004709 }
4710
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004711 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004712 return false;
4713
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004714 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004715 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004716 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4717 "switch.lookup",
4718 CommonDest->getParent(),
4719 CommonDest);
4720
Michael Gottesmanc024f322013-10-20 07:04:37 +00004721 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004722 Builder.SetInsertPoint(SI);
4723 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4724 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004725
4726 // Compute the maximum table size representable by the integer type we are
4727 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004728 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004729 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004730 assert(MaxTableSize >= TableSize &&
4731 "It is impossible for a switch to have more entries than the max "
4732 "representable value of its input integer type's size.");
4733
Hans Wennborgb64cb272015-01-26 19:52:34 +00004734 // If the default destination is unreachable, or if the lookup table covers
4735 // all values of the conditional variable, branch directly to the lookup table
4736 // BB. Otherwise, check that the condition is within the case range.
4737 const bool DefaultIsReachable =
4738 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4739 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004740 BranchInst *RangeCheckBranch = nullptr;
4741
Hans Wennborgb64cb272015-01-26 19:52:34 +00004742 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00004743 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00004744 // Note: We call removeProdecessor later since we need to be able to get the
4745 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00004746 } else {
4747 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004748 MinCaseVal->getType(), TableSize));
Erik Eckstein0d86c762014-11-27 15:13:14 +00004749 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00004750 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004751
4752 // Populate the BB that does the lookups.
4753 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004754
4755 if (NeedMask) {
4756 // Before doing the lookup we do the hole check.
4757 // The LookupBB is therefore re-purposed to do the hole check
4758 // and we create a new LookupBB.
4759 BasicBlock *MaskBB = LookupBB;
4760 MaskBB->setName("switch.hole_check");
4761 LookupBB = BasicBlock::Create(Mod.getContext(),
4762 "switch.lookup",
4763 CommonDest->getParent(),
4764 CommonDest);
4765
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004766 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4767 // unnecessary illegal types.
4768 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4769 APInt MaskInt(TableSizePowOf2, 0);
4770 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004771 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004772 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4773 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4774 uint64_t Idx = (ResultList[I].first->getValue() -
4775 MinCaseVal->getValue()).getLimitedValue();
4776 MaskInt |= One << Idx;
4777 }
4778 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4779
4780 // Get the TableIndex'th bit of the bitmask.
4781 // If this bit is 0 (meaning hole) jump to the default destination,
4782 // else continue with table lookup.
4783 IntegerType *MapTy = TableMask->getType();
4784 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4785 "switch.maskindex");
4786 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4787 "switch.shifted");
4788 Value *LoBit = Builder.CreateTrunc(Shifted,
4789 Type::getInt1Ty(Mod.getContext()),
4790 "switch.lobit");
4791 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4792
4793 Builder.SetInsertPoint(LookupBB);
4794 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4795 }
4796
Hans Wennborg86ac6302015-04-24 20:57:56 +00004797 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4798 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4799 // do not delete PHINodes here.
4800 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4801 /*DontDeleteUselessPHIs=*/true);
4802 }
4803
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004804 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004805 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4806 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004807 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004808
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004809 // If using a bitmask, use any value to fill the lookup table holes.
4810 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004811 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004812
Manman Ren4d189fb2014-07-24 21:13:20 +00004813 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004814
Hans Wennborgf744fa92012-09-19 14:24:21 +00004815 // If the result is used to return immediately from the function, we want to
4816 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004817 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4818 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004819 Builder.CreateRet(Result);
4820 ReturnedEarly = true;
4821 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004822 }
4823
Erik Eckstein0d86c762014-11-27 15:13:14 +00004824 // Do a small peephole optimization: re-use the switch table compare if
4825 // possible.
4826 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4827 BasicBlock *PhiBlock = PHI->getParent();
4828 // Search for compare instructions which use the phi.
4829 for (auto *User : PHI->users()) {
4830 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4831 }
4832 }
4833
Hans Wennborgf744fa92012-09-19 14:24:21 +00004834 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004835 }
4836
4837 if (!ReturnedEarly)
4838 Builder.CreateBr(CommonDest);
4839
4840 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004841 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004842 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004843
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004844 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004845 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004846 Succ->removePredecessor(SI->getParent());
4847 }
4848 SI->eraseFromParent();
4849
4850 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004851 if (NeedMask)
4852 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004853 return true;
4854}
4855
Devang Patela7ec47d2011-05-18 20:35:38 +00004856bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004857 BasicBlock *BB = SI->getParent();
4858
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004859 if (isValueEqualityComparison(SI)) {
4860 // If we only have one predecessor, and if it is a branch on this value,
4861 // see if that predecessor totally determines the outcome of this switch.
4862 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4863 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004864 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004865
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004866 Value *Cond = SI->getCondition();
4867 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4868 if (SimplifySwitchOnSelect(SI, Select))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004869 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004870
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004871 // If the block only contains the switch, see if we can fold the block
4872 // away into any preds.
4873 BasicBlock::iterator BBI = BB->begin();
4874 // Ignore dbg intrinsics.
4875 while (isa<DbgInfoIntrinsic>(BBI))
4876 ++BBI;
4877 if (SI == &*BBI)
4878 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004879 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004880 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004881
4882 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004883 if (TurnSwitchRangeIntoICmp(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004884 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004885
4886 // Remove unreachable cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004887 if (EliminateDeadSwitchCases(SI, AC, DL))
4888 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004889
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004890 if (SwitchToSelect(SI, Builder, AC, DL))
4891 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004892
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004893 if (ForwardSwitchConditionToPHI(SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004894 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004895
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004896 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4897 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004898
Chris Lattner25c3af32010-12-13 06:25:44 +00004899 return false;
4900}
4901
4902bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4903 BasicBlock *BB = IBI->getParent();
4904 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004905
Chris Lattner25c3af32010-12-13 06:25:44 +00004906 // Eliminate redundant destinations.
4907 SmallPtrSet<Value *, 8> Succs;
4908 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4909 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004910 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004911 Dest->removePredecessor(BB);
4912 IBI->removeDestination(i);
4913 --i; --e;
4914 Changed = true;
4915 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004916 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004917
4918 if (IBI->getNumDestinations() == 0) {
4919 // If the indirectbr has no successors, change it to unreachable.
4920 new UnreachableInst(IBI->getContext(), IBI);
4921 EraseTerminatorInstAndDCECond(IBI);
4922 return true;
4923 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004924
Chris Lattner25c3af32010-12-13 06:25:44 +00004925 if (IBI->getNumDestinations() == 1) {
4926 // If the indirectbr has one successor, change it to a direct branch.
4927 BranchInst::Create(IBI->getDestination(0), IBI);
4928 EraseTerminatorInstAndDCECond(IBI);
4929 return true;
4930 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004931
Chris Lattner25c3af32010-12-13 06:25:44 +00004932 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4933 if (SimplifyIndirectBrOnSelect(IBI, SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004934 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004935 }
4936 return Changed;
4937}
4938
Philip Reames2b969d72015-03-24 22:28:45 +00004939/// Given an block with only a single landing pad and a unconditional branch
4940/// try to find another basic block which this one can be merged with. This
4941/// handles cases where we have multiple invokes with unique landing pads, but
4942/// a shared handler.
4943///
4944/// We specifically choose to not worry about merging non-empty blocks
4945/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4946/// practice, the optimizer produces empty landing pad blocks quite frequently
4947/// when dealing with exception dense code. (see: instcombine, gvn, if-else
4948/// sinking in this file)
4949///
4950/// This is primarily a code size optimization. We need to avoid performing
4951/// any transform which might inhibit optimization (such as our ability to
4952/// specialize a particular handler via tail commoning). We do this by not
4953/// merging any blocks which require us to introduce a phi. Since the same
4954/// values are flowing through both blocks, we don't loose any ability to
4955/// specialize. If anything, we make such specialization more likely.
4956///
4957/// TODO - This transformation could remove entries from a phi in the target
4958/// block when the inputs in the phi are the same for the two blocks being
4959/// merged. In some cases, this could result in removal of the PHI entirely.
4960static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
4961 BasicBlock *BB) {
4962 auto Succ = BB->getUniqueSuccessor();
4963 assert(Succ);
4964 // If there's a phi in the successor block, we'd likely have to introduce
4965 // a phi into the merged landing pad block.
4966 if (isa<PHINode>(*Succ->begin()))
4967 return false;
4968
4969 for (BasicBlock *OtherPred : predecessors(Succ)) {
4970 if (BB == OtherPred)
4971 continue;
4972 BasicBlock::iterator I = OtherPred->begin();
4973 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
4974 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
4975 continue;
4976 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4977 BranchInst *BI2 = dyn_cast<BranchInst>(I);
4978 if (!BI2 || !BI2->isIdenticalTo(BI))
4979 continue;
4980
4981 // We've found an identical block. Update our predeccessors to take that
4982 // path instead and make ourselves dead.
4983 SmallSet<BasicBlock *, 16> Preds;
4984 Preds.insert(pred_begin(BB), pred_end(BB));
4985 for (BasicBlock *Pred : Preds) {
4986 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
4987 assert(II->getNormalDest() != BB &&
4988 II->getUnwindDest() == BB && "unexpected successor");
4989 II->setUnwindDest(OtherPred);
4990 }
4991
4992 // The debug info in OtherPred doesn't cover the merged control flow that
4993 // used to go through BB. We need to delete it or update it.
4994 for (auto I = OtherPred->begin(), E = OtherPred->end();
4995 I != E;) {
4996 Instruction &Inst = *I; I++;
4997 if (isa<DbgInfoIntrinsic>(Inst))
4998 Inst.eraseFromParent();
4999 }
5000
5001 SmallSet<BasicBlock *, 16> Succs;
5002 Succs.insert(succ_begin(BB), succ_end(BB));
5003 for (BasicBlock *Succ : Succs) {
5004 Succ->removePredecessor(BB);
5005 }
5006
5007 IRBuilder<> Builder(BI);
5008 Builder.CreateUnreachable();
5009 BI->eraseFromParent();
5010 return true;
5011 }
5012 return false;
5013}
5014
Devang Patel767f6932011-05-18 18:28:48 +00005015bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00005016 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005017
Manman Ren93ab6492012-09-20 22:37:36 +00005018 if (SinkCommon && SinkThenElseCodeToEnd(BI))
5019 return true;
5020
Chris Lattner25c3af32010-12-13 06:25:44 +00005021 // If the Terminator is the only non-phi instruction, simplify the block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00005022 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00005023 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
5024 TryToSimplifyUncondBranchFromEmptyBlock(BB))
5025 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005026
Chris Lattner25c3af32010-12-13 06:25:44 +00005027 // If the only instruction in the block is a seteq/setne comparison
5028 // against a constant, try to simplify the block.
5029 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5030 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5031 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5032 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005033 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005034 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
5035 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00005036 return true;
5037 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005038
Philip Reames2b969d72015-03-24 22:28:45 +00005039 // See if we can merge an empty landing pad block with another which is
5040 // equivalent.
5041 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
5042 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
5043 if (I->isTerminator() &&
5044 TryToMergeLandingPad(LPad, BI, BB))
5045 return true;
5046 }
5047
Manman Rend33f4ef2012-06-13 05:43:29 +00005048 // If this basic block is ONLY a compare and a branch, and if a predecessor
5049 // branches to us and our successor, fold the comparison into the
5050 // predecessor and use logical operations to update the incoming value
5051 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005052 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5053 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005054 return false;
5055}
5056
James Molloy4de84dd2015-11-04 15:28:04 +00005057static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5058 BasicBlock *PredPred = nullptr;
5059 for (auto *P : predecessors(BB)) {
5060 BasicBlock *PPred = P->getSinglePredecessor();
5061 if (!PPred || (PredPred && PredPred != PPred))
5062 return nullptr;
5063 PredPred = PPred;
5064 }
5065 return PredPred;
5066}
Chris Lattner25c3af32010-12-13 06:25:44 +00005067
Devang Patela7ec47d2011-05-18 20:35:38 +00005068bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005069 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005070
Chris Lattner25c3af32010-12-13 06:25:44 +00005071 // Conditional branch
5072 if (isValueEqualityComparison(BI)) {
5073 // If we only have one predecessor, and if it is a branch on this value,
5074 // see if that predecessor totally determines the outcome of this
5075 // switch.
5076 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00005077 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005078 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005079
Chris Lattner25c3af32010-12-13 06:25:44 +00005080 // This block must be empty, except for the setcond inst, if it exists.
5081 // Ignore dbg intrinsics.
5082 BasicBlock::iterator I = BB->begin();
5083 // Ignore dbg intrinsics.
5084 while (isa<DbgInfoIntrinsic>(I))
5085 ++I;
5086 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00005087 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005088 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005089 } else if (&*I == cast<Instruction>(BI->getCondition())){
5090 ++I;
5091 // Ignore dbg intrinsics.
5092 while (isa<DbgInfoIntrinsic>(I))
5093 ++I;
Devang Patel58380552011-05-18 20:53:17 +00005094 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005095 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005096 }
5097 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005098
Chris Lattner25c3af32010-12-13 06:25:44 +00005099 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005100 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00005101 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005102
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00005103 // If this basic block is ONLY a compare and a branch, and if a predecessor
5104 // branches to us and one of our successors, fold the comparison into the
5105 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005106 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5107 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005108
Chris Lattner25c3af32010-12-13 06:25:44 +00005109 // We have a conditional branch to two blocks that are only reachable
5110 // from BI. We know that the condbr dominates the two blocks, so see if
5111 // there is any identical code in the "then" and "else" blocks. If so, we
5112 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00005113 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5114 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005115 if (HoistThenElseCodeToIf(BI, TTI))
5116 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005117 } else {
5118 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005119 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00005120 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5121 if (Succ0TI->getNumSuccessors() == 1 &&
5122 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005123 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
5124 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005125 }
Craig Topperf40110f2014-04-25 05:29:35 +00005126 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005127 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005128 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00005129 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5130 if (Succ1TI->getNumSuccessors() == 1 &&
5131 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005132 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
5133 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005134 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005135
Chris Lattner25c3af32010-12-13 06:25:44 +00005136 // If this is a branch on a phi node in the current block, thread control
5137 // through this block if any PHI node entries are constants.
5138 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5139 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005140 if (FoldCondBranchOnPHI(BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005141 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005142
Chris Lattner25c3af32010-12-13 06:25:44 +00005143 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00005144 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5145 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00005146 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00005147 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005148 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005149
James Molloy4de84dd2015-11-04 15:28:04 +00005150 // Look for diamond patterns.
5151 if (MergeCondStores)
5152 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5153 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5154 if (PBI != BI && PBI->isConditional())
5155 if (mergeConditionalStores(PBI, BI))
5156 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5157
Chris Lattner25c3af32010-12-13 06:25:44 +00005158 return false;
5159}
5160
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005161/// Check if passing a value to an instruction will cause undefined behavior.
5162static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5163 Constant *C = dyn_cast<Constant>(V);
5164 if (!C)
5165 return false;
5166
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005167 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005168 return false;
5169
5170 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005171 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00005172 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005173
5174 // Now make sure that there are no instructions in between that can alter
5175 // control flow (eg. calls)
5176 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00005177 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005178 return false;
5179
5180 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5181 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5182 if (GEP->getPointerOperand() == I)
5183 return passingValueIsAlwaysUndefined(V, GEP);
5184
5185 // Look through bitcasts.
5186 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5187 return passingValueIsAlwaysUndefined(V, BC);
5188
Benjamin Kramer0655b782011-08-26 02:25:55 +00005189 // Load from null is undefined.
5190 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005191 if (!LI->isVolatile())
5192 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005193
Benjamin Kramer0655b782011-08-26 02:25:55 +00005194 // Store to null is undefined.
5195 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005196 if (!SI->isVolatile())
5197 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005198 }
5199 return false;
5200}
5201
5202/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005203/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005204static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5205 for (BasicBlock::iterator i = BB->begin();
5206 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5207 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5208 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5209 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5210 IRBuilder<> Builder(T);
5211 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5212 BB->removePredecessor(PHI->getIncomingBlock(i));
5213 // Turn uncoditional branches into unreachables and remove the dead
5214 // destination from conditional branches.
5215 if (BI->isUnconditional())
5216 Builder.CreateUnreachable();
5217 else
5218 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
5219 BI->getSuccessor(0));
5220 BI->eraseFromParent();
5221 return true;
5222 }
5223 // TODO: SwitchInst.
5224 }
5225
5226 return false;
5227}
5228
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005229bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00005230 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00005231
Chris Lattnerd7beca32010-12-14 06:17:25 +00005232 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00005233 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00005234
Dan Gohman4a63fad2010-08-14 00:29:42 +00005235 // Remove basic blocks that have no predecessors (except the entry block)...
5236 // or that just have themself as a predecessor. These are unreachable.
Ramkumar Ramachandra181233b2015-01-13 04:17:47 +00005237 if ((pred_empty(BB) &&
Chris Lattnerd7beca32010-12-14 06:17:25 +00005238 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00005239 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00005240 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00005241 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00005242 return true;
5243 }
5244
Chris Lattner031340a2003-08-17 19:41:53 +00005245 // Check to see if we can constant propagate this terminator instruction
5246 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00005247 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00005248
Dan Gohman1a951062009-10-30 22:39:04 +00005249 // Check for and eliminate duplicate PHI nodes in this block.
5250 Changed |= EliminateDuplicatePHINodes(BB);
5251
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005252 // Check for and remove branches that will always cause undefined behavior.
5253 Changed |= removeUndefIntroducingPredecessor(BB);
5254
Chris Lattner2e3832d2010-12-13 05:10:48 +00005255 // Merge basic blocks into their predecessor if there is only one distinct
5256 // pred, and if there is only one distinct successor of the predecessor, and
5257 // if there are no PHI nodes.
5258 //
5259 if (MergeBlockIntoPredecessor(BB))
5260 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005261
Devang Patel15ad6762011-05-18 18:01:27 +00005262 IRBuilder<> Builder(BB);
5263
Dan Gohman20af5a02008-03-11 21:53:06 +00005264 // If there is a trivial two-entry PHI node in this basic block, and we can
5265 // eliminate it, do so now.
5266 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5267 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005268 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00005269
Devang Patela7ec47d2011-05-18 20:35:38 +00005270 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00005271 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00005272 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00005273 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005274 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00005275 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005276 }
5277 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00005278 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00005279 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
5280 if (SimplifyResume(RI, Builder)) return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00005281 } else if (CleanupReturnInst *RI =
5282 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5283 if (SimplifyCleanupReturn(RI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005284 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00005285 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005286 } else if (UnreachableInst *UI =
5287 dyn_cast<UnreachableInst>(BB->getTerminator())) {
5288 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005289 } else if (IndirectBrInst *IBI =
5290 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
5291 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00005292 }
5293
Chris Lattner031340a2003-08-17 19:41:53 +00005294 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00005295}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005296
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005297/// This function is used to do simplification of a CFG.
5298/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005299/// eliminates unreachable basic blocks, and does other "peephole" optimization
5300/// of the CFG. It returns true if a modification was made.
5301///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005302bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005303 unsigned BonusInstThreshold, AssumptionCache *AC) {
5304 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
5305 BonusInstThreshold, AC).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005306}