blob: 3125a2c359b68b8114a01f3771b51e85292d8cc8 [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
Sanjay Patel38a02262015-12-15 17:38:29 +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
Hans Wennborg39583b82012-09-26 09:44:49 +000093STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000094STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000095STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +000096STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +000097STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Manman Ren93ab6492012-09-20 22:37:36 +000098STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000099STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +0000100
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000101namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000102 // The first field contains the value that the switch produces when a certain
Sanjay Patel9361d352015-09-10 16:31:19 +0000103 // case group is selected, and the second field is a vector containing the
104 // cases composing the case group.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000105 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
106 SwitchCaseResultVectorTy;
107 // The first field contains the phi node that generates a result of the switch
Sanjay Patel9361d352015-09-10 16:31:19 +0000108 // and the second field contains the value generated for a certain case in the
109 // switch for that PHI.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000110 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
111
Eric Christopherb65acc62012-07-02 23:22:21 +0000112 /// ValueEqualityComparisonCase - Represents a case of a switch.
113 struct ValueEqualityComparisonCase {
114 ConstantInt *Value;
115 BasicBlock *Dest;
116
117 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
118 : Value(Value), Dest(Dest) {}
119
120 bool operator<(ValueEqualityComparisonCase RHS) const {
121 // Comparing pointers is ok as we only rely on the order for uniquing.
122 return Value < RHS.Value;
123 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000124
125 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000126 };
127
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000128class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000129 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000130 const DataLayout &DL;
Jingyue Wufc029672014-09-30 22:23:38 +0000131 unsigned BonusInstThreshold;
Chandler Carruth66b31302015-01-04 12:03:27 +0000132 AssumptionCache *AC;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000133 Value *isValueEqualityComparison(TerminatorInst *TI);
134 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000135 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000136 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000137 BasicBlock *Pred,
138 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000139 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
140 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000141
Devang Pateldd14e0f2011-05-18 21:33:11 +0000142 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000143 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chen Li1689c2f2016-01-10 05:48:01 +0000144 bool SimplifySingleResume(ResumeInst *RI);
145 bool SimplifyCommonResume(ResumeInst *RI);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000146 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000147 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000148 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000149 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000150 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000151 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000152
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000153public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000154 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
155 unsigned BonusInstThreshold, AssumptionCache *AC)
156 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000157 bool run(BasicBlock *BB);
158};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000159}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000160
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000161/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000162/// terminator instructions together.
Chris Lattner76dc2042005-08-03 00:19:45 +0000163static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
164 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000165
Chris Lattner76dc2042005-08-03 00:19:45 +0000166 // It is not safe to merge these two switch instructions if they have a common
167 // successor, and if that successor has a PHI node, and if *that* PHI node has
168 // conflicting incoming values from the two switch blocks.
169 BasicBlock *SI1BB = SI1->getParent();
170 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000171 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000172
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000173 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
174 if (SI1Succs.count(*I))
175 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000176 isa<PHINode>(BBI); ++BBI) {
177 PHINode *PN = cast<PHINode>(BBI);
178 if (PN->getIncomingValueForBlock(SI1BB) !=
179 PN->getIncomingValueForBlock(SI2BB))
180 return false;
181 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000182
Chris Lattner76dc2042005-08-03 00:19:45 +0000183 return true;
184}
185
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000186/// Return true if it is safe and profitable to merge these two terminator
187/// instructions together, where SI1 is an unconditional branch. PhiNodes will
188/// store all PHI nodes in common successors.
Manman Rend33f4ef2012-06-13 05:43:29 +0000189static bool isProfitableToFoldUnconditional(BranchInst *SI1,
190 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000191 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000192 SmallVectorImpl<PHINode*> &PhiNodes) {
193 if (SI1 == SI2) return false; // Can't merge with self!
194 assert(SI1->isUnconditional() && SI2->isConditional());
195
196 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000197 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000198 // 1> We have a constant incoming value for the conditional branch;
199 // 2> We have "Cond" as the incoming value for the unconditional branch;
200 // 3> SI2->getCondition() and Cond have same operands.
201 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
202 if (!Ci2) return false;
203 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
204 Cond->getOperand(1) == Ci2->getOperand(1)) &&
205 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
206 Cond->getOperand(1) == Ci2->getOperand(0)))
207 return false;
208
209 BasicBlock *SI1BB = SI1->getParent();
210 BasicBlock *SI2BB = SI2->getParent();
211 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000212 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
213 if (SI1Succs.count(*I))
214 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000215 isa<PHINode>(BBI); ++BBI) {
216 PHINode *PN = cast<PHINode>(BBI);
217 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000218 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000219 return false;
220 PhiNodes.push_back(PN);
221 }
222 return true;
223}
224
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000225/// Update PHI nodes in Succ to indicate that there will now be entries in it
226/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
227/// will be the same as those coming in from ExistPred, an existing predecessor
228/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000229static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
230 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000231 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000232
Chris Lattner80b03a12008-07-13 22:23:11 +0000233 PHINode *PN;
234 for (BasicBlock::iterator I = Succ->begin();
235 (PN = dyn_cast<PHINode>(I)); ++I)
236 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000237}
238
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000239/// Compute an abstract "cost" of speculating the given instruction,
240/// which is assumed to be safe to speculate. TCC_Free means cheap,
241/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000242/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000243static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000244 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000245 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000246 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000247 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000248}
Sanjay Patelf9b77632015-09-15 15:24:42 +0000249
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000250/// If we have a merge point of an "if condition" as accepted above,
251/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000252/// don't handle the true generality of domination here, just a special case
253/// which works well enough for us.
254///
255/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000256/// see if V (which must be an instruction) and its recursive operands
257/// that do not dominate BB have a combined cost lower than CostRemaining and
258/// are non-trapping. If both are true, the instruction is inserted into the
259/// set and true is returned.
260///
261/// The cost for most non-trapping instructions is defined as 1 except for
262/// Select whose cost is 2.
263///
264/// After this function returns, CostRemaining is decreased by the cost of
265/// V plus its non-dominating operands. If that cost is greater than
266/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000267static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000268 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000269 unsigned &CostRemaining,
Sanjay Patel38a02262015-12-15 17:38:29 +0000270 const TargetTransformInfo &TTI,
271 unsigned Depth = 0) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000272 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000273 if (!I) {
274 // Non-instructions all dominate instructions, but not all constantexprs
275 // can be executed unconditionally.
276 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
277 if (C->canTrap())
278 return false;
279 return true;
280 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000281 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000282
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000283 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000284 // the bottom of this block.
285 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000286
Chris Lattner0aa56562004-04-09 22:50:22 +0000287 // If this instruction is defined in a block that contains an unconditional
288 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000289 // statement". If not, it definitely dominates the region.
290 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000291 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000292 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000293
Chris Lattner9ac168d2010-12-14 07:41:39 +0000294 // If we aren't allowing aggressive promotion anymore, then don't consider
295 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000296 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000297
Peter Collingbournee3511e12011-04-29 18:47:31 +0000298 // If we have seen this instruction before, don't count it again.
299 if (AggressiveInsts->count(I)) return true;
300
Chris Lattner9ac168d2010-12-14 07:41:39 +0000301 // Okay, it looks like the instruction IS in the "condition". Check to
302 // see if it's a cheap instruction to unconditionally compute, and if it
303 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000304 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000305 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000306
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000307 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000308
Sanjay Patel38a02262015-12-15 17:38:29 +0000309 // Allow exactly one instruction to be speculated regardless of its cost
310 // (as long as it is safe to do so).
311 // This is intended to flatten the CFG even if the instruction is a division
312 // or other expensive operation. The speculation of an expensive instruction
313 // is expected to be undone in CodeGenPrepare if the speculation has not
314 // enabled further IR optimizations.
315 if (Cost > CostRemaining &&
316 (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0))
Peter Collingbournee3511e12011-04-29 18:47:31 +0000317 return false;
318
Sanjay Patel38a02262015-12-15 17:38:29 +0000319 // Avoid unsigned wrap.
320 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000321
322 // Okay, we can only really hoist these out if their operands do
323 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000324 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Sanjay Patel38a02262015-12-15 17:38:29 +0000325 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
326 Depth + 1))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000327 return false;
328 // Okay, it's safe to do this! Remember this instruction.
329 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000330 return true;
331}
Chris Lattner466a0492002-05-21 20:50:24 +0000332
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000333/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000334/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000335static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000336 // Normal constant int.
337 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000338 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000339 return CI;
340
341 // This is some kind of pointer constant. Turn it into a pointer-sized
342 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000343 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000344
345 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
346 if (isa<ConstantPointerNull>(V))
347 return ConstantInt::get(PtrTy, 0);
348
349 // IntToPtr const int.
350 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
351 if (CE->getOpcode() == Instruction::IntToPtr)
352 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
353 // The constant is very likely to have the right type already.
354 if (CI->getType() == PtrTy)
355 return CI;
356 else
357 return cast<ConstantInt>
358 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
359 }
Craig Topperf40110f2014-04-25 05:29:35 +0000360 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000361}
362
Mehdi Aminiffd01002014-11-20 22:40:25 +0000363namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000364
Mehdi Aminiffd01002014-11-20 22:40:25 +0000365/// Given a chain of or (||) or and (&&) comparison of a value against a
366/// constant, this will try to recover the information required for a switch
367/// structure.
368/// It will depth-first traverse the chain of comparison, seeking for patterns
369/// like %a == 12 or %a < 4 and combine them to produce a set of integer
370/// representing the different cases for the switch.
371/// Note that if the chain is composed of '||' it will build the set of elements
372/// that matches the comparisons (i.e. any of this value validate the chain)
373/// while for a chain of '&&' it will build the set elements that make the test
374/// fail.
375struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000376 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000377 Value *CompValue; /// Value found for the switch comparison
378 Value *Extra; /// Extra clause to be checked before the switch
379 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
380 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000381
Mehdi Aminiffd01002014-11-20 22:40:25 +0000382 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000383 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
384 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
385 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000386 }
387
Mehdi Aminiffd01002014-11-20 22:40:25 +0000388 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000389 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000390 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000391 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000392
Mehdi Aminiffd01002014-11-20 22:40:25 +0000393private:
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000394
Mehdi Aminiffd01002014-11-20 22:40:25 +0000395 /// Try to set the current value used for the comparison, it succeeds only if
396 /// it wasn't set before or if the new value is the same as the old one
397 bool setValueOnce(Value *NewVal) {
398 if(CompValue && CompValue != NewVal) return false;
399 CompValue = NewVal;
400 return (CompValue != nullptr);
401 }
402
403 /// Try to match Instruction "I" as a comparison against a constant and
404 /// populates the array Vals with the set of values that match (or do not
405 /// match depending on isEQ).
406 /// Return false on failure. On success, the Value the comparison matched
407 /// against is placed in CompValue.
408 /// If CompValue is already set, the function is expected to fail if a match
409 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000410 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000411 // If this is an icmp against a constant, handle this as one of the cases.
412 ICmpInst *ICI;
413 ConstantInt *C;
414 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
415 (C = GetConstantInt(I->getOperand(1), DL)))) {
416 return false;
417 }
418
419 Value *RHSVal;
420 ConstantInt *RHSC;
421
422 // Pattern match a special case
423 // (x & ~2^x) == y --> x == y || x == y|2^x
424 // This undoes a transformation done by instcombine to fuse 2 compares.
425 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
426 if (match(ICI->getOperand(0),
427 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
428 APInt Not = ~RHSC->getValue();
429 if (Not.isPowerOf2()) {
430 // If we already have a value for the switch, it has to match!
431 if(!setValueOnce(RHSVal))
432 return false;
433
434 Vals.push_back(C);
435 Vals.push_back(ConstantInt::get(C->getContext(),
436 C->getValue() | Not));
437 UsedICmps++;
438 return true;
439 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000440 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000441
442 // If we already have a value for the switch, it has to match!
443 if(!setValueOnce(ICI->getOperand(0)))
444 return false;
445
446 UsedICmps++;
447 Vals.push_back(C);
448 return ICI->getOperand(0);
449 }
450
451 // 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 +0000452 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
453 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000454
455 // Shift the range if the compare is fed by an add. This is the range
456 // compare idiom as emitted by instcombine.
457 Value *CandidateVal = I->getOperand(0);
458 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
459 Span = Span.subtract(RHSC->getValue());
460 CandidateVal = RHSVal;
461 }
462
463 // If this is an and/!= check, then we are looking to build the set of
464 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
465 // x != 0 && x != 1.
466 if (!isEQ)
467 Span = Span.inverse();
468
469 // If there are a ton of values, we don't want to make a ginormous switch.
470 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
471 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000472 }
473
474 // If we already have a value for the switch, it has to match!
Mehdi Aminiffd01002014-11-20 22:40:25 +0000475 if(!setValueOnce(CandidateVal))
476 return false;
477
478 // Add all values from the range to the set
479 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
480 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000481
482 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000483 return true;
484
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000485 }
486
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000487 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000488 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
489 /// the value being compared, and stick the list constants into the Vals
490 /// vector.
491 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000492 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000493 Instruction *I = dyn_cast<Instruction>(V);
494 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000495
Mehdi Aminiffd01002014-11-20 22:40:25 +0000496 // Keep a stack (SmallVector for efficiency) for depth-first traversal
497 SmallVector<Value *, 8> DFT;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000498
Mehdi Aminiffd01002014-11-20 22:40:25 +0000499 // Initialize
500 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000501
Mehdi Aminiffd01002014-11-20 22:40:25 +0000502 while(!DFT.empty()) {
503 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000504
Mehdi Aminiffd01002014-11-20 22:40:25 +0000505 if (Instruction *I = dyn_cast<Instruction>(V)) {
506 // If it is a || (or && depending on isEQ), process the operands.
507 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
508 DFT.push_back(I->getOperand(1));
509 DFT.push_back(I->getOperand(0));
510 continue;
511 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000512
Mehdi Aminiffd01002014-11-20 22:40:25 +0000513 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000514 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000515 // Match succeed, continue the loop
516 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000517 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000518
Mehdi Aminiffd01002014-11-20 22:40:25 +0000519 // One element of the sequence of || (or &&) could not be match as a
520 // comparison against the same value as the others.
521 // We allow only one "Extra" case to be checked before the switch
522 if (!Extra) {
523 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000524 continue;
525 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000526 // Failed to parse a proper sequence, abort now
527 CompValue = nullptr;
528 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000529 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000530 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000531};
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000532
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000533}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000534
Eli Friedmancb61afb2008-12-16 20:54:32 +0000535static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000536 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000537 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
538 Cond = dyn_cast<Instruction>(SI->getCondition());
539 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
540 if (BI->isConditional())
541 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000542 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
543 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000544 }
545
546 TI->eraseFromParent();
547 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
548}
549
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000550/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000551/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000552Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000553 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000554 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
555 // Do not permit merging of large switch instructions into their
556 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000557 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
558 pred_end(SI->getParent())) <= 128)
559 CV = SI->getCondition();
560 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000561 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000562 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000563 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000564 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000565 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000566
567 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000568 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000569 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
570 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000571 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000572 CV = Ptr;
573 }
574 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000575 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000576}
577
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000578/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000579/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000580BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000581GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000582 std::vector<ValueEqualityComparisonCase>
583 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000584 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000585 Cases.reserve(SI->getNumCases());
586 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
587 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
588 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000589 return SI->getDefaultDest();
590 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000591
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000592 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000593 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000594 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
595 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000596 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000597 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000598 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000599}
600
Eric Christopherb65acc62012-07-02 23:22:21 +0000601
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000602/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000603/// in the list that match the specified block.
604static void EliminateBlockCases(BasicBlock *BB,
605 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000606 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000607}
608
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000609/// Return true if there are any keys in C1 that exist in C2 as well.
Eric Christopherb65acc62012-07-02 23:22:21 +0000610static bool
611ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
612 std::vector<ValueEqualityComparisonCase > &C2) {
613 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
614
615 // Make V1 be smaller than V2.
616 if (V1->size() > V2->size())
617 std::swap(V1, V2);
618
619 if (V1->size() == 0) return false;
620 if (V1->size() == 1) {
621 // Just scan V2.
622 ConstantInt *TheVal = (*V1)[0].Value;
623 for (unsigned i = 0, e = V2->size(); i != e; ++i)
624 if (TheVal == (*V2)[i].Value)
625 return true;
626 }
627
628 // Otherwise, just sort both lists and compare element by element.
629 array_pod_sort(V1->begin(), V1->end());
630 array_pod_sort(V2->begin(), V2->end());
631 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
632 while (i1 != e1 && i2 != e2) {
633 if ((*V1)[i1].Value == (*V2)[i2].Value)
634 return true;
635 if ((*V1)[i1].Value < (*V2)[i2].Value)
636 ++i1;
637 else
638 ++i2;
639 }
640 return false;
641}
642
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000643/// If TI is known to be a terminator instruction and its block is known to
644/// only have a single predecessor block, check to see if that predecessor is
645/// also a value comparison with the same value, and if that comparison
646/// determines the outcome of this comparison. If so, simplify TI. This does a
647/// very limited form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000648bool SimplifyCFGOpt::
649SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000650 BasicBlock *Pred,
651 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000652 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
653 if (!PredVal) return false; // Not a value comparison in predecessor.
654
655 Value *ThisVal = isValueEqualityComparison(TI);
656 assert(ThisVal && "This isn't a value comparison!!");
657 if (ThisVal != PredVal) return false; // Different predicates.
658
Andrew Trick3051aa12012-08-29 21:46:38 +0000659 // TODO: Preserve branch weight metadata, similarly to how
660 // FoldValueComparisonIntoPredecessors preserves it.
661
Chris Lattner1cca9592005-02-24 06:17:52 +0000662 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000663 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000664 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
665 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000666 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000667
Chris Lattner1cca9592005-02-24 06:17:52 +0000668 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000669 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000670 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000671 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000672
673 // If TI's block is the default block from Pred's comparison, potentially
674 // simplify TI based on this knowledge.
675 if (PredDef == TI->getParent()) {
676 // If we are here, we know that the value is none of those cases listed in
677 // PredCases. If there are any cases in ThisCases that are in PredCases, we
678 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000679 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000680 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000681
Chris Lattner4088e2b2010-12-13 01:47:07 +0000682 if (isa<BranchInst>(TI)) {
683 // Okay, one of the successors of this condbr is dead. Convert it to a
684 // uncond br.
685 assert(ThisCases.size() == 1 && "Branch can only have one case!");
686 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000687 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000688 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000689
Chris Lattner4088e2b2010-12-13 01:47:07 +0000690 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000691 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000692
Chris Lattner4088e2b2010-12-13 01:47:07 +0000693 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
694 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000695
Chris Lattner4088e2b2010-12-13 01:47:07 +0000696 EraseTerminatorInstAndDCECond(TI);
697 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000698 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000699
Chris Lattner4088e2b2010-12-13 01:47:07 +0000700 SwitchInst *SI = cast<SwitchInst>(TI);
701 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000702 SmallPtrSet<Constant*, 16> DeadCases;
703 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
704 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000705
David Greene725c7c32010-01-05 01:26:52 +0000706 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000707 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000708
Manman Ren8691e522012-09-14 21:53:06 +0000709 // Collect branch weights into a vector.
710 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000711 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000712 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
713 if (HasWeight)
714 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
715 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000716 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000717 Weights.push_back(CI->getValue().getZExtValue());
718 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000719 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
720 --i;
721 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000722 if (HasWeight) {
723 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
724 Weights.pop_back();
725 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000726 i.getCaseSuccessor()->removePredecessor(TI->getParent());
727 SI->removeCase(i);
728 }
729 }
Manman Ren97c18762012-10-11 22:28:34 +0000730 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000731 SI->setMetadata(LLVMContext::MD_prof,
732 MDBuilder(SI->getParent()->getContext()).
733 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000734
735 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000736 return true;
737 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000738
Chris Lattner4088e2b2010-12-13 01:47:07 +0000739 // Otherwise, TI's block must correspond to some matched value. Find out
740 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000741 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000742 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000743 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
744 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000745 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000746 return false; // Cannot handle multiple values coming to this block.
747 TIV = PredCases[i].Value;
748 }
749 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000750
751 // Okay, we found the one constant that our value can be if we get into TI's
752 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000753 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000754 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
755 if (ThisCases[i].Value == TIV) {
756 TheRealDest = ThisCases[i].Dest;
757 break;
758 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000759
760 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000761 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000762
763 // Remove PHI node entries for dead edges.
764 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000765 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
766 if (*SI != CheckEdge)
767 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000768 else
Craig Topperf40110f2014-04-25 05:29:35 +0000769 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000770
771 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000772 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000773 (void) NI;
774
775 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
776 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
777
778 EraseTerminatorInstAndDCECond(TI);
779 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000780}
781
Dale Johannesen7f99d222009-03-12 21:01:11 +0000782namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000783 /// This class implements a stable ordering of constant
Dale Johannesen7f99d222009-03-12 21:01:11 +0000784 /// integers that does not depend on their address. This is important for
785 /// applications that sort ConstantInt's to ensure uniqueness.
786 struct ConstantIntOrdering {
787 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
788 return LHS->getValue().ult(RHS->getValue());
789 }
790 };
791}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000792
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000793static int ConstantIntSortPredicate(ConstantInt *const *P1,
794 ConstantInt *const *P2) {
795 const ConstantInt *LHS = *P1;
796 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000797 if (LHS->getValue().ult(RHS->getValue()))
798 return 1;
799 if (LHS->getValue() == RHS->getValue())
800 return 0;
801 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000802}
803
Andrew Trick3051aa12012-08-29 21:46:38 +0000804static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000805 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000806 if (ProfMD && ProfMD->getOperand(0))
807 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
808 return MDS->getString().equals("branch_weights");
809
810 return false;
811}
812
Manman Ren571d9e42012-09-11 17:43:35 +0000813/// Get Weights of a given TerminatorInst, the default weight is at the front
814/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
815/// metadata.
816static void GetBranchWeights(TerminatorInst *TI,
817 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000818 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000819 assert(MD);
820 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000821 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000822 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000823 }
824
Manman Ren571d9e42012-09-11 17:43:35 +0000825 // If TI is a conditional eq, the default case is the false case,
826 // and the corresponding branch-weight data is at index 2. We swap the
827 // default weight to be the first entry.
828 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
829 assert(Weights.size() == 2);
830 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
831 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
832 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000833 }
834}
835
Manman Renf1cb16e2014-01-27 23:39:03 +0000836/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000837static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000838 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
839 if (Max > UINT_MAX) {
840 unsigned Offset = 32 - countLeadingZeros(Max);
841 for (uint64_t &I : Weights)
842 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000843 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000844}
845
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000846/// The specified terminator is a value equality comparison instruction
847/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000848/// See if any of the predecessors of the terminator block are value comparisons
849/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000850bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
851 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000852 BasicBlock *BB = TI->getParent();
853 Value *CV = isValueEqualityComparison(TI); // CondVal
854 assert(CV && "Not a comparison?");
855 bool Changed = false;
856
Chris Lattner6b39cb92008-02-18 07:42:56 +0000857 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000858 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000859 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000860
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000861 // See if the predecessor is a comparison with the same value.
862 TerminatorInst *PTI = Pred->getTerminator();
863 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
864
865 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
866 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000867 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000868 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
869
Eric Christopherb65acc62012-07-02 23:22:21 +0000870 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000871 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
872
873 // Based on whether the default edge from PTI goes to BB or not, fill in
874 // PredCases and PredDefault with the new switch cases we would like to
875 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000876 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000877
Andrew Trick3051aa12012-08-29 21:46:38 +0000878 // Update the branch weight metadata along the way
879 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000880 bool PredHasWeights = HasBranchWeights(PTI);
881 bool SuccHasWeights = HasBranchWeights(TI);
882
Manman Ren5e5049d2012-09-14 19:05:19 +0000883 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000884 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000885 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000886 if (Weights.size() != 1 + PredCases.size())
887 PredHasWeights = SuccHasWeights = false;
888 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000889 // If there are no predecessor weights but there are successor weights,
890 // populate Weights with 1, which will later be scaled to the sum of
891 // successor's weights
892 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000893
Manman Ren571d9e42012-09-11 17:43:35 +0000894 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000895 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000896 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000897 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000898 if (SuccWeights.size() != 1 + BBCases.size())
899 PredHasWeights = SuccHasWeights = false;
900 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000901 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000902
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000903 if (PredDefault == BB) {
904 // If this is the default destination from PTI, only the edges in TI
905 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000906 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
907 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
908 if (PredCases[i].Dest != BB)
909 PTIHandled.insert(PredCases[i].Value);
910 else {
911 // The default destination is BB, we don't need explicit targets.
912 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000913
Manman Ren571d9e42012-09-11 17:43:35 +0000914 if (PredHasWeights || SuccHasWeights) {
915 // Increase weight for the default case.
916 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000917 std::swap(Weights[i+1], Weights.back());
918 Weights.pop_back();
919 }
920
Eric Christopherb65acc62012-07-02 23:22:21 +0000921 PredCases.pop_back();
922 --i; --e;
923 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000924
Eric Christopherb65acc62012-07-02 23:22:21 +0000925 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000926 if (PredDefault != BBDefault) {
927 PredDefault->removePredecessor(Pred);
928 PredDefault = BBDefault;
929 NewSuccessors.push_back(BBDefault);
930 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000931
Manman Ren571d9e42012-09-11 17:43:35 +0000932 unsigned CasesFromPred = Weights.size();
933 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000934 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
935 if (!PTIHandled.count(BBCases[i].Value) &&
936 BBCases[i].Dest != BBDefault) {
937 PredCases.push_back(BBCases[i]);
938 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000939 if (SuccHasWeights || PredHasWeights) {
940 // The default weight is at index 0, so weight for the ith case
941 // should be at index i+1. Scale the cases from successor by
942 // PredDefaultWeight (Weights[0]).
943 Weights.push_back(Weights[0] * SuccWeights[i+1]);
944 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000945 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000946 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000947
Manman Ren571d9e42012-09-11 17:43:35 +0000948 if (SuccHasWeights || PredHasWeights) {
949 ValidTotalSuccWeight += SuccWeights[0];
950 // Scale the cases from predecessor by ValidTotalSuccWeight.
951 for (unsigned i = 1; i < CasesFromPred; ++i)
952 Weights[i] *= ValidTotalSuccWeight;
953 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
954 Weights[0] *= SuccWeights[0];
955 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000956 } else {
957 // If this is not the default destination from PSI, only the edges
958 // in SI that occur in PSI with a destination of BB will be
959 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000960 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000961 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000962 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
963 if (PredCases[i].Dest == BB) {
964 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000965
966 if (PredHasWeights || SuccHasWeights) {
967 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
968 std::swap(Weights[i+1], Weights.back());
969 Weights.pop_back();
970 }
971
Eric Christopherb65acc62012-07-02 23:22:21 +0000972 std::swap(PredCases[i], PredCases.back());
973 PredCases.pop_back();
974 --i; --e;
975 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000976
977 // Okay, now we know which constants were sent to BB from the
978 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000979 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
980 if (PTIHandled.count(BBCases[i].Value)) {
981 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000982 if (PredHasWeights || SuccHasWeights)
983 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000984 PredCases.push_back(BBCases[i]);
985 NewSuccessors.push_back(BBCases[i].Dest);
986 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
987 }
988
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000989 // If there are any constants vectored to BB that TI doesn't handle,
990 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000991 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000992 PTIHandled.begin(),
993 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000994 if (PredHasWeights || SuccHasWeights)
995 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000996 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000997 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000998 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000999 }
1000
1001 // Okay, at this point, we know which new successor Pred will get. Make
1002 // sure we update the number of entries in the PHI nodes for these
1003 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +00001004 for (BasicBlock *NewSuccessor : NewSuccessors)
1005 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001006
Devang Patel58380552011-05-18 20:53:17 +00001007 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001008 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +00001009 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001010 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +00001011 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001012 }
1013
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001014 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +00001015 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
1016 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001017 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +00001018 for (ValueEqualityComparisonCase &V : PredCases)
1019 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001020
Andrew Trick3051aa12012-08-29 21:46:38 +00001021 if (PredHasWeights || SuccHasWeights) {
1022 // Halve the weights if any of them cannot fit in an uint32_t
1023 FitWeights(Weights);
1024
1025 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1026
1027 NewSI->setMetadata(LLVMContext::MD_prof,
1028 MDBuilder(BB->getContext()).
1029 createBranchWeights(MDWeights));
1030 }
1031
Eli Friedmancb61afb2008-12-16 20:54:32 +00001032 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001033
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001034 // Okay, last check. If BB is still a successor of PSI, then we must
1035 // have an infinite loop case. If so, add an infinitely looping block
1036 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001037 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001038 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1039 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001040 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001041 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001042 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001043 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1044 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001045 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001046 }
1047 NewSI->setSuccessor(i, InfLoopBlock);
1048 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001049
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001050 Changed = true;
1051 }
1052 }
1053 return Changed;
1054}
1055
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001056// If we would need to insert a select that uses the value of this invoke
1057// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1058// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001059static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1060 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001061 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001062 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001063 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001064 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1065 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1066 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1067 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1068 return false;
1069 }
1070 }
1071 }
1072 return true;
1073}
1074
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001075static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1076
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001077/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1078/// in the two blocks up into the branch block. The caller of this function
1079/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001080static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001081 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001082 // This does very trivial matching, with limited scanning, to find identical
1083 // instructions in the two blocks. In particular, we don't want to get into
1084 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1085 // such, we currently just scan for obviously identical instructions in an
1086 // identical order.
1087 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1088 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1089
Devang Patelf10e2872009-02-04 00:03:08 +00001090 BasicBlock::iterator BB1_Itr = BB1->begin();
1091 BasicBlock::iterator BB2_Itr = BB2->begin();
1092
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001093 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001094 // Skip debug info if it is not identical.
1095 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1096 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1097 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1098 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001099 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001100 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001101 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001102 }
Devang Patele48ddf82011-04-07 00:30:15 +00001103 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001104 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001105 return false;
1106
Chris Lattner389cfac2004-11-30 00:29:14 +00001107 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001108
David Majnemerc82f27a2013-06-03 20:43:12 +00001109 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001110 do {
1111 // If we are hoisting the terminator instruction, don't move one (making a
1112 // broken BB), instead clone it, and remove BI.
1113 if (isa<TerminatorInst>(I1))
1114 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001115
Chad Rosier54390052015-02-23 19:15:16 +00001116 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1117 return Changed;
1118
Chris Lattner389cfac2004-11-30 00:29:14 +00001119 // For a normal instruction, we just move one to right before the branch,
1120 // then replace all uses of the other with the first. Finally, we remove
1121 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001122 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001123 if (!I2->use_empty())
1124 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001125 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001126 unsigned KnownIDs[] = {
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001127 LLVMContext::MD_tbaa, LLVMContext::MD_range,
1128 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001129 LLVMContext::MD_nonnull, LLVMContext::MD_invariant_group,
1130 LLVMContext::MD_align, LLVMContext::MD_dereferenceable,
1131 LLVMContext::MD_dereferenceable_or_null};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001132 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001133 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001134 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001135
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001136 I1 = &*BB1_Itr++;
1137 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001138 // Skip debug info if it is not identical.
1139 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1140 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1141 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1142 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001143 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001144 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001145 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001146 }
Devang Patele48ddf82011-04-07 00:30:15 +00001147 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001148
1149 return true;
1150
1151HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001152 // It may not be possible to hoist an invoke.
1153 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001154 return Changed;
1155
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001156 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001157 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001158 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001159 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1160 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1161 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1162 if (BB1V == BB2V)
1163 continue;
1164
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001165 // Check for passingValueIsAlwaysUndefined here because we would rather
1166 // eliminate undefined control flow then converting it to a select.
1167 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1168 passingValueIsAlwaysUndefined(BB2V, PN))
1169 return Changed;
1170
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001171 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001172 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001173 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001174 return Changed;
1175 }
1176 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001177
Chris Lattner389cfac2004-11-30 00:29:14 +00001178 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001179 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001180 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001181 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001182 I1->replaceAllUsesWith(NT);
1183 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001184 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001185 }
1186
Devang Patel1407fb42011-05-19 20:52:46 +00001187 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001188 // Hoisting one of the terminators from our successor is a great thing.
1189 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1190 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1191 // nodes, so we insert select instruction to compute the final result.
1192 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001193 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001194 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001195 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001196 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001197 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1198 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001199 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001200
Chris Lattner4088e2b2010-12-13 01:47:07 +00001201 // These values do not agree. Insert a select instruction before NT
1202 // that determines the right value.
1203 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001204 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001205 SI = cast<SelectInst>
1206 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1207 BB1V->getName()+"."+BB2V->getName()));
1208
Chris Lattner4088e2b2010-12-13 01:47:07 +00001209 // Make the PHI node use the select for all incoming values for BB1/BB2
1210 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1211 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1212 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001213 }
1214 }
1215
1216 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001217 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1218 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001219
Eli Friedmancb61afb2008-12-16 20:54:32 +00001220 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001221 return true;
1222}
1223
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001224/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001225/// check whether BBEnd has only two predecessors and the other predecessor
1226/// ends with an unconditional branch. If it is true, sink any common code
1227/// in the two predecessors to BBEnd.
1228static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1229 assert(BI1->isUnconditional());
1230 BasicBlock *BB1 = BI1->getParent();
1231 BasicBlock *BBEnd = BI1->getSuccessor(0);
1232
1233 // Check that BBEnd has two predecessors and the other predecessor ends with
1234 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001235 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1236 BasicBlock *Pred0 = *PI++;
1237 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001238 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001239 BasicBlock *Pred1 = *PI++;
1240 if (PI != PE) // More than two predecessors.
1241 return false;
1242 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001243 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1244 if (!BI2 || !BI2->isUnconditional())
1245 return false;
1246
1247 // Gather the PHI nodes in BBEnd.
Michael Liao5313da32014-12-23 08:26:55 +00001248 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
Craig Topperf40110f2014-04-25 05:29:35 +00001249 Instruction *FirstNonPhiInBBEnd = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001250 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
Manman Ren93ab6492012-09-20 22:37:36 +00001251 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1252 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001253 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Michael Liao5313da32014-12-23 08:26:55 +00001254 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
Manman Ren93ab6492012-09-20 22:37:36 +00001255 } else {
1256 FirstNonPhiInBBEnd = &*I;
1257 break;
1258 }
1259 }
1260 if (!FirstNonPhiInBBEnd)
1261 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001262
Manman Ren93ab6492012-09-20 22:37:36 +00001263 // This does very trivial matching, with limited scanning, to find identical
1264 // instructions in the two blocks. We scan backward for obviously identical
1265 // instructions in an identical order.
1266 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
Michael Liao5313da32014-12-23 08:26:55 +00001267 RE1 = BB1->getInstList().rend(),
1268 RI2 = BB2->getInstList().rbegin(),
1269 RE2 = BB2->getInstList().rend();
Manman Ren93ab6492012-09-20 22:37:36 +00001270 // Skip debug info.
1271 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1272 if (RI1 == RE1)
1273 return false;
1274 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1275 if (RI2 == RE2)
1276 return false;
1277 // Skip the unconditional branches.
1278 ++RI1;
1279 ++RI2;
1280
1281 bool Changed = false;
1282 while (RI1 != RE1 && RI2 != RE2) {
1283 // Skip debug info.
1284 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1285 if (RI1 == RE1)
1286 return Changed;
1287 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1288 if (RI2 == RE2)
1289 return Changed;
1290
1291 Instruction *I1 = &*RI1, *I2 = &*RI2;
Michael Liao5313da32014-12-23 08:26:55 +00001292 auto InstPair = std::make_pair(I1, I2);
Manman Ren93ab6492012-09-20 22:37:36 +00001293 // I1 and I2 should have a single use in the same PHI node, and they
1294 // perform the same operation.
1295 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1296 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1297 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
David Majnemerba275f92015-08-19 19:54:02 +00001298 I1->isEHPad() || I2->isEHPad() ||
Manman Ren93ab6492012-09-20 22:37:36 +00001299 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1300 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1301 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1302 !I1->hasOneUse() || !I2->hasOneUse() ||
Michael Liao5313da32014-12-23 08:26:55 +00001303 !JointValueMap.count(InstPair))
Manman Ren93ab6492012-09-20 22:37:36 +00001304 return Changed;
1305
1306 // Check whether we should swap the operands of ICmpInst.
Michael Liao5313da32014-12-23 08:26:55 +00001307 // TODO: Add support of communativity.
Manman Ren93ab6492012-09-20 22:37:36 +00001308 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1309 bool SwapOpnds = false;
1310 if (ICmp1 && ICmp2 &&
1311 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1312 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1313 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1314 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1315 ICmp2->swapOperands();
1316 SwapOpnds = true;
1317 }
1318 if (!I1->isSameOperationAs(I2)) {
1319 if (SwapOpnds)
1320 ICmp2->swapOperands();
1321 return Changed;
1322 }
1323
1324 // The operands should be either the same or they need to be generated
1325 // with a PHI node after sinking. We only handle the case where there is
1326 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001327 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001328 unsigned Op1Idx = ~0U;
Manman Ren93ab6492012-09-20 22:37:36 +00001329 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1330 if (I1->getOperand(I) == I2->getOperand(I))
1331 continue;
Michael Liao5313da32014-12-23 08:26:55 +00001332 // Early exit if we have more-than one pair of different operands or if
1333 // we need a PHI node to replace a constant.
1334 if (Op1Idx != ~0U ||
Manman Ren93ab6492012-09-20 22:37:36 +00001335 isa<Constant>(I1->getOperand(I)) ||
1336 isa<Constant>(I2->getOperand(I))) {
1337 // If we can't sink the instructions, undo the swapping.
1338 if (SwapOpnds)
1339 ICmp2->swapOperands();
1340 return Changed;
1341 }
1342 DifferentOp1 = I1->getOperand(I);
1343 Op1Idx = I;
1344 DifferentOp2 = I2->getOperand(I);
1345 }
1346
Michael Liao5313da32014-12-23 08:26:55 +00001347 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1348 DEBUG(dbgs() << " " << *I2 << "\n");
1349
1350 // We insert the pair of different operands to JointValueMap and
1351 // remove (I1, I2) from JointValueMap.
1352 if (Op1Idx != ~0U) {
1353 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1354 if (!NewPN) {
1355 NewPN =
1356 PHINode::Create(DifferentOp1->getType(), 2,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001357 DifferentOp1->getName() + ".sink", &BBEnd->front());
Michael Liao5313da32014-12-23 08:26:55 +00001358 NewPN->addIncoming(DifferentOp1, BB1);
1359 NewPN->addIncoming(DifferentOp2, BB2);
1360 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1361 }
Manman Ren93ab6492012-09-20 22:37:36 +00001362 // I1 should use NewPN instead of DifferentOp1.
1363 I1->setOperand(Op1Idx, NewPN);
Manman Ren93ab6492012-09-20 22:37:36 +00001364 }
Michael Liao5313da32014-12-23 08:26:55 +00001365 PHINode *OldPN = JointValueMap[InstPair];
1366 JointValueMap.erase(InstPair);
Manman Ren93ab6492012-09-20 22:37:36 +00001367
Manman Ren93ab6492012-09-20 22:37:36 +00001368 // We need to update RE1 and RE2 if we are going to sink the first
1369 // instruction in the basic block down.
1370 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1371 // Sink the instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001372 BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(),
1373 BB1->getInstList(), I1);
Manman Ren93ab6492012-09-20 22:37:36 +00001374 if (!OldPN->use_empty())
1375 OldPN->replaceAllUsesWith(I1);
1376 OldPN->eraseFromParent();
1377
1378 if (!I2->use_empty())
1379 I2->replaceAllUsesWith(I1);
1380 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001381 // TODO: Use combineMetadata here to preserve what metadata we can
1382 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001383 I2->eraseFromParent();
1384
1385 if (UpdateRE1)
1386 RE1 = BB1->getInstList().rend();
1387 if (UpdateRE2)
1388 RE2 = BB2->getInstList().rend();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001389 FirstNonPhiInBBEnd = &*I1;
Manman Ren93ab6492012-09-20 22:37:36 +00001390 NumSinkCommons++;
1391 Changed = true;
1392 }
1393 return Changed;
1394}
1395
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001396/// \brief Determine if we can hoist sink a sole store instruction out of a
1397/// conditional block.
1398///
1399/// We are looking for code like the following:
1400/// BrBB:
1401/// store i32 %add, i32* %arrayidx2
1402/// ... // No other stores or function calls (we could be calling a memory
1403/// ... // function).
1404/// %cmp = icmp ult %x, %y
1405/// br i1 %cmp, label %EndBB, label %ThenBB
1406/// ThenBB:
1407/// store i32 %add5, i32* %arrayidx2
1408/// br label EndBB
1409/// EndBB:
1410/// ...
1411/// We are going to transform this into:
1412/// BrBB:
1413/// store i32 %add, i32* %arrayidx2
1414/// ... //
1415/// %cmp = icmp ult %x, %y
1416/// %add.add5 = select i1 %cmp, i32 %add, %add5
1417/// store i32 %add.add5, i32* %arrayidx2
1418/// ...
1419///
1420/// \return The pointer to the value of the previous store if the store can be
1421/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001422static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1423 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001424 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1425 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001426 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001427
1428 // Volatile or atomic.
1429 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001430 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001431
1432 Value *StorePtr = StoreToHoist->getPointerOperand();
1433
1434 // Look for a store to the same pointer in BrBB.
1435 unsigned MaxNumInstToLookAt = 10;
1436 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1437 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1438 Instruction *CurI = &*RI;
1439
1440 // Could be calling an instruction that effects memory like free().
1441 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001442 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001443
1444 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1445 // Found the previous store make sure it stores to the same location.
1446 if (SI && SI->getPointerOperand() == StorePtr)
1447 // Found the previous store, return its value operand.
1448 return SI->getValueOperand();
1449 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001450 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001451 }
1452
Craig Topperf40110f2014-04-25 05:29:35 +00001453 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001454}
1455
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001456/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001457///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001458/// Note that this is a very risky transform currently. Speculating
1459/// instructions like this is most often not desirable. Instead, there is an MI
1460/// pass which can do it with full awareness of the resource constraints.
1461/// However, some cases are "obvious" and we should do directly. An example of
1462/// this is speculating a single, reasonably cheap instruction.
1463///
1464/// There is only one distinct advantage to flattening the CFG at the IR level:
1465/// it makes very common but simplistic optimizations such as are common in
1466/// instcombine and the DAG combiner more powerful by removing CFG edges and
1467/// modeling their effects with easier to reason about SSA value graphs.
1468///
1469///
1470/// An illustration of this transform is turning this IR:
1471/// \code
1472/// BB:
1473/// %cmp = icmp ult %x, %y
1474/// br i1 %cmp, label %EndBB, label %ThenBB
1475/// ThenBB:
1476/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001477/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001478/// EndBB:
1479/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1480/// ...
1481/// \endcode
1482///
1483/// Into this IR:
1484/// \code
1485/// BB:
1486/// %cmp = icmp ult %x, %y
1487/// %sub = sub %x, %y
1488/// %cond = select i1 %cmp, 0, %sub
1489/// ...
1490/// \endcode
1491///
1492/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001493static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001494 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001495 // Be conservative for now. FP select instruction can often be expensive.
1496 Value *BrCond = BI->getCondition();
1497 if (isa<FCmpInst>(BrCond))
1498 return false;
1499
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001500 BasicBlock *BB = BI->getParent();
1501 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1502
1503 // If ThenBB is actually on the false edge of the conditional branch, remember
1504 // to swap the select operands later.
1505 bool Invert = false;
1506 if (ThenBB != BI->getSuccessor(0)) {
1507 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1508 Invert = true;
1509 }
1510 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1511
Chandler Carruthceff2222013-01-25 05:40:09 +00001512 // Keep a count of how many times instructions are used within CondBB when
1513 // they are candidates for sinking into CondBB. Specifically:
1514 // - They are defined in BB, and
1515 // - They have no side effects, and
1516 // - All of their uses are in CondBB.
1517 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1518
Chandler Carruth7481ca82013-01-24 11:52:58 +00001519 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001520 Value *SpeculatedStoreValue = nullptr;
1521 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001522 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001523 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001524 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001525 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001526 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001527 if (isa<DbgInfoIntrinsic>(I))
1528 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001529
Mark Lacey274f48b2015-04-12 18:18:51 +00001530 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001531 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001532 ++SpeculationCost;
1533 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001534 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001535
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001536 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001537 if (!isSafeToSpeculativelyExecute(I) &&
1538 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1539 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001540 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001541 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001542 ComputeSpeculationCost(I, TTI) >
1543 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001544 return false;
1545
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001546 // Store the store speculation candidate.
1547 if (SpeculatedStoreValue)
1548 SpeculatedStore = cast<StoreInst>(I);
1549
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001550 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001551 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001552 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001553 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001554 i != e; ++i) {
1555 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001556 if (!OpI || OpI->getParent() != BB ||
1557 OpI->mayHaveSideEffects())
1558 continue; // Not a candidate for sinking.
1559
1560 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001561 }
1562 }
Evan Cheng89200c92008-06-07 08:52:29 +00001563
Chandler Carruthceff2222013-01-25 05:40:09 +00001564 // Consider any sink candidates which are only used in CondBB as costs for
1565 // speculation. Note, while we iterate over a DenseMap here, we are summing
1566 // and so iteration order isn't significant.
1567 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1568 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1569 I != E; ++I)
1570 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001571 ++SpeculationCost;
1572 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001573 return false;
1574 }
1575
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001576 // Check that the PHI nodes can be converted to selects.
1577 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001578 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001579 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001580 Value *OrigV = PN->getIncomingValueForBlock(BB);
1581 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001582
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001583 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001584 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001585 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001586 continue;
1587
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001588 // Don't convert to selects if we could remove undefined behavior instead.
1589 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1590 passingValueIsAlwaysUndefined(ThenV, PN))
1591 return false;
1592
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001593 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001594 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1595 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1596 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001597 continue; // Known safe and cheap.
1598
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001599 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1600 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001601 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001602 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1603 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
James Molloy7c336572015-02-11 12:15:41 +00001604 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1605 TargetTransformInfo::TCC_Basic;
1606 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00001607 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001608
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001609 // Account for the cost of an unfolded ConstantExpr which could end up
1610 // getting expanded into Instructions.
1611 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001612 // constant expression.
1613 ++SpeculationCost;
1614 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001615 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001616 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001617
1618 // If there are no PHIs to process, bail early. This helps ensure idempotence
1619 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001620 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001621 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001622
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001623 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001624 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001625
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001626 // Insert a select of the value of the speculated store.
1627 if (SpeculatedStoreValue) {
1628 IRBuilder<true, NoFolder> Builder(BI);
1629 Value *TrueV = SpeculatedStore->getValueOperand();
1630 Value *FalseV = SpeculatedStoreValue;
1631 if (Invert)
1632 std::swap(TrueV, FalseV);
1633 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1634 "." + FalseV->getName());
1635 SpeculatedStore->setOperand(0, S);
1636 }
1637
Igor Laevsky7310c682015-11-18 14:50:18 +00001638 // Metadata can be dependent on the condition we are hoisting above.
1639 // Conservatively strip all metadata on the instruction.
1640 for (auto &I: *ThenBB)
1641 I.dropUnknownNonDebugMetadata();
1642
Chandler Carruth7481ca82013-01-24 11:52:58 +00001643 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001644 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
1645 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001646
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001647 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001648 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001649 for (BasicBlock::iterator I = EndBB->begin();
1650 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1651 unsigned OrigI = PN->getBasicBlockIndex(BB);
1652 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1653 Value *OrigV = PN->getIncomingValue(OrigI);
1654 Value *ThenV = PN->getIncomingValue(ThenI);
1655
1656 // Skip PHIs which are trivial.
1657 if (OrigV == ThenV)
1658 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001659
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001660 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001661 // false value is the preexisting value. Swap them if the branch
1662 // destinations were inverted.
1663 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001664 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001665 std::swap(TrueV, FalseV);
1666 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1667 TrueV->getName() + "." + FalseV->getName());
1668 PN->setIncomingValue(OrigI, V);
1669 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001670 }
1671
Evan Cheng89553cc2008-06-12 21:15:59 +00001672 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001673 return true;
1674}
1675
Tom Stellarde1631dd2013-10-21 20:07:30 +00001676/// \returns True if this block contains a CallInst with the NoDuplicate
1677/// attribute.
1678static bool HasNoDuplicateCall(const BasicBlock *BB) {
1679 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1680 const CallInst *CI = dyn_cast<CallInst>(I);
1681 if (!CI)
1682 continue;
1683 if (CI->cannotDuplicate())
1684 return true;
1685 }
1686 return false;
1687}
1688
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001689/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001690static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1691 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001692 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001693
Devang Patel84fceff2009-03-10 18:00:05 +00001694 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001695 if (isa<DbgInfoIntrinsic>(BBI))
1696 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001697 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001698 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001699
Dale Johannesened6f5a82009-03-12 23:18:09 +00001700 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001701 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001702 for (User *U : BBI->users()) {
1703 Instruction *UI = cast<Instruction>(U);
1704 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001705 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001706
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001707 // Looks ok, continue checking.
1708 }
Chris Lattner6c701062005-09-20 01:48:40 +00001709
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001710 return true;
1711}
1712
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001713/// If we have a conditional branch on a PHI node value that is defined in the
1714/// same block as the branch and if any PHI entries are constants, thread edges
1715/// corresponding to that entry to be branches to their ultimate destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001716static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001717 BasicBlock *BB = BI->getParent();
1718 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001719 // NOTE: we currently cannot transform this case if the PHI node is used
1720 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001721 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1722 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001723
Chris Lattner748f9032005-09-19 23:49:37 +00001724 // Degenerate case of a single entry PHI.
1725 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001726 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001727 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001728 }
1729
1730 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001731 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001732
Tom Stellarde1631dd2013-10-21 20:07:30 +00001733 if (HasNoDuplicateCall(BB)) return false;
1734
Chris Lattner748f9032005-09-19 23:49:37 +00001735 // Okay, this is a simple enough basic block. See if any phi values are
1736 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001737 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001738 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001739 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001740
Chris Lattner4088e2b2010-12-13 01:47:07 +00001741 // Okay, we now know that all edges from PredBB should be revectored to
1742 // branch to RealDest.
1743 BasicBlock *PredBB = PN->getIncomingBlock(i);
1744 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001745
Chris Lattner4088e2b2010-12-13 01:47:07 +00001746 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001747 // Skip if the predecessor's terminator is an indirect branch.
1748 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001749
Chris Lattner4088e2b2010-12-13 01:47:07 +00001750 // The dest block might have PHI nodes, other predecessors and other
1751 // difficult cases. Instead of being smart about this, just insert a new
1752 // block that jumps to the destination block, effectively splitting
1753 // the edge we are about to create.
1754 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1755 RealDest->getName()+".critedge",
1756 RealDest->getParent(), RealDest);
1757 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001758
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001759 // Update PHI nodes.
1760 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001761
1762 // BB may have instructions that are being threaded over. Clone these
1763 // instructions into EdgeBB. We know that there will be no uses of the
1764 // cloned instructions outside of EdgeBB.
1765 BasicBlock::iterator InsertPt = EdgeBB->begin();
1766 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1767 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1768 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1769 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1770 continue;
1771 }
1772 // Clone the instruction.
1773 Instruction *N = BBI->clone();
1774 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001775
Chris Lattner4088e2b2010-12-13 01:47:07 +00001776 // Update operands due to translation.
1777 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1778 i != e; ++i) {
1779 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1780 if (PI != TranslateMap.end())
1781 *i = PI->second;
1782 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001783
Chris Lattner4088e2b2010-12-13 01:47:07 +00001784 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001785 if (Value *V = SimplifyInstruction(N, DL)) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001786 TranslateMap[&*BBI] = V;
Chris Lattnerd7beca32010-12-14 06:17:25 +00001787 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001788 } else {
1789 // Insert the new instruction into its new home.
1790 EdgeBB->getInstList().insert(InsertPt, N);
1791 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001792 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001793 }
1794 }
1795
1796 // Loop over all of the edges from PredBB to BB, changing them to branch
1797 // to EdgeBB instead.
1798 TerminatorInst *PredBBTI = PredBB->getTerminator();
1799 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1800 if (PredBBTI->getSuccessor(i) == BB) {
1801 BB->removePredecessor(PredBB);
1802 PredBBTI->setSuccessor(i, EdgeBB);
1803 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001804
Chris Lattner4088e2b2010-12-13 01:47:07 +00001805 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001806 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001807 }
Chris Lattner748f9032005-09-19 23:49:37 +00001808
1809 return false;
1810}
1811
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001812/// Given a BB that starts with the specified two-entry PHI node,
1813/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001814static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1815 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001816 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1817 // statement", which has a very simple dominance structure. Basically, we
1818 // are trying to find the condition that is being branched on, which
1819 // subsequently causes this merge to happen. We really want control
1820 // dependence information for this check, but simplifycfg can't keep it up
1821 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001822 BasicBlock *BB = PN->getParent();
1823 BasicBlock *IfTrue, *IfFalse;
1824 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001825 if (!IfCond ||
1826 // Don't bother if the branch will be constant folded trivially.
1827 isa<ConstantInt>(IfCond))
1828 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001829
Chris Lattner95adf8f12006-11-18 19:19:36 +00001830 // Okay, we found that we can merge this two-entry phi node into a select.
1831 // Doing so would require us to fold *all* two entry phi nodes in this block.
1832 // At some point this becomes non-profitable (particularly if the target
1833 // doesn't support cmov's). Only do this transformation if there are two or
1834 // fewer PHI nodes in this block.
1835 unsigned NumPhis = 0;
1836 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1837 if (NumPhis > 2)
1838 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001839
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001840 // Loop over the PHI's seeing if we can promote them all to select
1841 // instructions. While we are at it, keep track of the instructions
1842 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001843 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001844 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1845 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00001846 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1847 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001848
Chris Lattner7499b452010-12-14 08:46:09 +00001849 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1850 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001851 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001852 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001853 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001854 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001855 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001856
Peter Collingbournee3511e12011-04-29 18:47:31 +00001857 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001858 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001859 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001860 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001861 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001862 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001863
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001864 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001865 // we ran out of PHIs then we simplified them all.
1866 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001867 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001868
Chris Lattner7499b452010-12-14 08:46:09 +00001869 // Don't fold i1 branches on PHIs which contain binary operators. These can
1870 // often be turned into switches and other things.
1871 if (PN->getType()->isIntegerTy(1) &&
1872 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1873 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1874 isa<BinaryOperator>(IfCond)))
1875 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001876
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001877 // If we all PHI nodes are promotable, check to make sure that all
1878 // instructions in the predecessor blocks can be promoted as well. If
1879 // not, we won't be able to get rid of the control flow, so it's not
1880 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001881 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001882 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1883 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1884 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001885 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001886 } else {
1887 DomBlock = *pred_begin(IfBlock1);
1888 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001889 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001890 // This is not an aggressive instruction that we can promote.
1891 // Because of this, we won't be able to get rid of the control
1892 // flow, so the xform is not worth it.
1893 return false;
1894 }
1895 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001896
Chris Lattner9ac168d2010-12-14 07:41:39 +00001897 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001898 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001899 } else {
1900 DomBlock = *pred_begin(IfBlock2);
1901 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001902 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001903 // This is not an aggressive instruction that we can promote.
1904 // Because of this, we won't be able to get rid of the control
1905 // flow, so the xform is not worth it.
1906 return false;
1907 }
1908 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001909
Chris Lattner9fd838d2010-12-14 07:23:10 +00001910 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001911 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001912
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001913 // If we can still promote the PHI nodes after this gauntlet of tests,
1914 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001915 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001916 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001917
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001918 // Move all 'aggressive' instructions, which are defined in the
1919 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001920 if (IfBlock1)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001921 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001922 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001923 IfBlock1->getTerminator()->getIterator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001924 if (IfBlock2)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001925 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001926 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001927 IfBlock2->getTerminator()->getIterator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001928
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001929 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1930 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001931 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1932 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001933
1934 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001935 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001936 PN->replaceAllUsesWith(NV);
1937 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001938 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001939 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001940
Chris Lattner335f0e42010-12-14 08:01:53 +00001941 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1942 // has been flattened. Change DomBlock to jump directly to our new block to
1943 // avoid other simplifycfg's kicking in on the diamond.
1944 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001945 Builder.SetInsertPoint(OldTI);
1946 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001947 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001948 return true;
1949}
Chris Lattner748f9032005-09-19 23:49:37 +00001950
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001951/// If we found a conditional branch that goes to two returning blocks,
1952/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00001953/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001954static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001955 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001956 assert(BI->isConditional() && "Must be a conditional branch");
1957 BasicBlock *TrueSucc = BI->getSuccessor(0);
1958 BasicBlock *FalseSucc = BI->getSuccessor(1);
1959 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1960 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001961
Chris Lattner86bbf332008-04-24 00:01:19 +00001962 // Check to ensure both blocks are empty (just a return) or optionally empty
1963 // with PHI nodes. If there are other instructions, merging would cause extra
1964 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001965 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001966 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001967 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001968 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001969
Devang Pateldd14e0f2011-05-18 21:33:11 +00001970 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001971 // Okay, we found a branch that is going to two return nodes. If
1972 // there is no return value for this function, just change the
1973 // branch into a return.
1974 if (FalseRet->getNumOperands() == 0) {
1975 TrueSucc->removePredecessor(BI->getParent());
1976 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001977 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001978 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001979 return true;
1980 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001981
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001982 // Otherwise, figure out what the true and false return values are
1983 // so we can insert a new select instruction.
1984 Value *TrueValue = TrueRet->getReturnValue();
1985 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001986
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001987 // Unwrap any PHI nodes in the return blocks.
1988 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1989 if (TVPN->getParent() == TrueSucc)
1990 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1991 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1992 if (FVPN->getParent() == FalseSucc)
1993 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001994
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001995 // In order for this transformation to be safe, we must be able to
1996 // unconditionally execute both operands to the return. This is
1997 // normally the case, but we could have a potentially-trapping
1998 // constant expression that prevents this transformation from being
1999 // safe.
2000 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2001 if (TCV->canTrap())
2002 return false;
2003 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2004 if (FCV->canTrap())
2005 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002006
Chris Lattner86bbf332008-04-24 00:01:19 +00002007 // Okay, we collected all the mapped values and checked them for sanity, and
2008 // defined to really do this transformation. First, update the CFG.
2009 TrueSucc->removePredecessor(BI->getParent());
2010 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002011
Chris Lattner86bbf332008-04-24 00:01:19 +00002012 // Insert select instructions where needed.
2013 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002014 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002015 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002016 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2017 } else if (isa<UndefValue>(TrueValue)) {
2018 TrueValue = FalseValue;
2019 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00002020 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
2021 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00002022 }
Chris Lattner86bbf332008-04-24 00:01:19 +00002023 }
2024
Andrew Trickf3cf1932012-08-29 21:46:36 +00002025 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00002026 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2027
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00002028 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002029
David Greene725c7c32010-01-05 01:26:52 +00002030 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002031 << "\n " << *BI << "NewRet = " << *RI
2032 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002033
Eli Friedmancb61afb2008-12-16 20:54:32 +00002034 EraseTerminatorInstAndDCECond(BI);
2035
Chris Lattner86bbf332008-04-24 00:01:19 +00002036 return true;
2037}
2038
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002039/// Given a conditional BranchInstruction, retrieve the probabilities of the
2040/// branch taking each edge. Fills in the two APInt parameters and returns true,
2041/// or returns false if no or invalid metadata was found.
Juergen Ributzka194350a2014-12-09 17:32:12 +00002042static bool ExtractBranchMetadata(BranchInst *BI,
2043 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2044 assert(BI->isConditional() &&
2045 "Looking for probabilities on unconditional branch?");
2046 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2047 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002048 ConstantInt *CITrue =
2049 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2050 ConstantInt *CIFalse =
2051 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00002052 if (!CITrue || !CIFalse) return false;
2053 ProbTrue = CITrue->getValue().getZExtValue();
2054 ProbFalse = CIFalse->getValue().getZExtValue();
2055 return true;
2056}
2057
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002058/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002059/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002060static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002061 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2062 return false;
2063 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2064 Instruction *PBI = &*I;
2065 // Check whether Inst and PBI generate the same value.
2066 if (Inst->isIdenticalTo(PBI)) {
2067 Inst->replaceAllUsesWith(PBI);
2068 Inst->eraseFromParent();
2069 return true;
2070 }
2071 }
2072 return false;
2073}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002074
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002075/// If this basic block is simple enough, and if a predecessor branches to us
2076/// and one of our successors, fold the block into the predecessor and use
2077/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002078bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002079 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002080
Craig Topperf40110f2014-04-25 05:29:35 +00002081 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002082 if (BI->isConditional())
2083 Cond = dyn_cast<Instruction>(BI->getCondition());
2084 else {
2085 // For unconditional branch, check for a simple CFG pattern, where
2086 // BB has a single predecessor and BB's successor is also its predecessor's
2087 // successor. If such pattern exisits, check for CSE between BB and its
2088 // predecessor.
2089 if (BasicBlock *PB = BB->getSinglePredecessor())
2090 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2091 if (PBI->isConditional() &&
2092 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2093 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2094 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2095 I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002096 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002097 if (isa<CmpInst>(Curr)) {
2098 Cond = Curr;
2099 break;
2100 }
2101 // Quit if we can't remove this instruction.
2102 if (!checkCSEInPredecessor(Curr, PB))
2103 return false;
2104 }
2105 }
2106
Craig Topperf40110f2014-04-25 05:29:35 +00002107 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002108 return false;
2109 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002110
Craig Topperf40110f2014-04-25 05:29:35 +00002111 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2112 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002113 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002114
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002115 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002116 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002117
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002118 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002119 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002120
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002121 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002122 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002123
Jingyue Wufc029672014-09-30 22:23:38 +00002124 // Only allow this transformation if computing the condition doesn't involve
2125 // too many instructions and these involved instructions can be executed
2126 // unconditionally. We denote all involved instructions except the condition
2127 // as "bonus instructions", and only allow this transformation when the
2128 // number of the bonus instructions does not exceed a certain threshold.
2129 unsigned NumBonusInsts = 0;
2130 for (auto I = BB->begin(); Cond != I; ++I) {
2131 // Ignore dbg intrinsics.
2132 if (isa<DbgInfoIntrinsic>(I))
2133 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002134 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002135 return false;
2136 // I has only one use and can be executed unconditionally.
2137 Instruction *User = dyn_cast<Instruction>(I->user_back());
2138 if (User == nullptr || User->getParent() != BB)
2139 return false;
2140 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2141 // to use any other instruction, User must be an instruction between next(I)
2142 // and Cond.
2143 ++NumBonusInsts;
2144 // Early exits once we reach the limit.
2145 if (NumBonusInsts > BonusInstThreshold)
2146 return false;
2147 }
2148
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002149 // Cond is known to be a compare or binary operator. Check to make sure that
2150 // neither operand is a potentially-trapping constant expression.
2151 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2152 if (CE->canTrap())
2153 return false;
2154 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2155 if (CE->canTrap())
2156 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002157
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002158 // Finally, don't infinitely unroll conditional loops.
2159 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002160 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002161 if (TrueDest == BB || FalseDest == BB)
2162 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002163
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002164 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2165 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002166 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002167
Chris Lattner80b03a12008-07-13 22:23:11 +00002168 // Check that we have two conditional branches. If there is a PHI node in
2169 // the common successor, verify that the same value flows in from both
2170 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002171 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002172 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002173 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002174 !SafeToMergeTerminators(BI, PBI)) ||
2175 (!BI->isConditional() &&
2176 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002177 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002178
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002179 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002180 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002181 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002182
Manman Rend33f4ef2012-06-13 05:43:29 +00002183 if (BI->isConditional()) {
2184 if (PBI->getSuccessor(0) == TrueDest)
2185 Opc = Instruction::Or;
2186 else if (PBI->getSuccessor(1) == FalseDest)
2187 Opc = Instruction::And;
2188 else if (PBI->getSuccessor(0) == FalseDest)
2189 Opc = Instruction::And, InvertPredCond = true;
2190 else if (PBI->getSuccessor(1) == TrueDest)
2191 Opc = Instruction::Or, InvertPredCond = true;
2192 else
2193 continue;
2194 } else {
2195 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2196 continue;
2197 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002198
David Greene725c7c32010-01-05 01:26:52 +00002199 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002200 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002201
Chris Lattner55eaae12008-07-13 21:20:19 +00002202 // If we need to invert the condition in the pred block to match, do so now.
2203 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002204 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002205
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002206 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2207 CmpInst *CI = cast<CmpInst>(NewCond);
2208 CI->setPredicate(CI->getInversePredicate());
2209 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002210 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002211 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002212 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002213
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002214 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002215 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002216 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002217
Jingyue Wufc029672014-09-30 22:23:38 +00002218 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002219 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002220 // bonus instructions to a predecessor block.
2221 ValueToValueMapTy VMap; // maps original values to cloned values
2222 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002223 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002224 // instructions.
2225 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2226 if (isa<DbgInfoIntrinsic>(BonusInst))
2227 continue;
2228 Instruction *NewBonusInst = BonusInst->clone();
2229 RemapInstruction(NewBonusInst, VMap,
2230 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002231 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002232
2233 // If we moved a load, we cannot any longer claim any knowledge about
2234 // its potential value. The previous information might have been valid
2235 // only given the branch precondition.
2236 // For an analogous reason, we must also drop all the metadata whose
2237 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002238 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002239
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002240 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2241 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002242 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002243 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002244
Chris Lattner55eaae12008-07-13 21:20:19 +00002245 // Clone Cond into the predecessor basic block, and or/and the
2246 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002247 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002248 RemapInstruction(New, VMap,
2249 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002250 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002251 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002252 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002253
Manman Rend33f4ef2012-06-13 05:43:29 +00002254 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002255 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002256 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002257 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002258 PBI->setCondition(NewCond);
2259
Manman Renbfb9d432012-09-15 00:39:57 +00002260 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002261 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2262 PredFalseWeight);
2263 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2264 SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002265 SmallVector<uint64_t, 8> NewWeights;
2266
Manman Rend33f4ef2012-06-13 05:43:29 +00002267 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002268 if (PredHasWeights && SuccHasWeights) {
2269 // PBI: br i1 %x, BB, FalseDest
2270 // BI: br i1 %y, TrueDest, FalseDest
2271 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2272 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2273 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2274 // TrueWeight for PBI * FalseWeight for BI.
2275 // We assume that total weights of a BranchInst can fit into 32 bits.
2276 // Therefore, we will not have overflow using 64-bit arithmetic.
2277 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2278 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2279 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002280 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2281 PBI->setSuccessor(0, TrueDest);
2282 }
2283 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002284 if (PredHasWeights && SuccHasWeights) {
2285 // PBI: br i1 %x, TrueDest, BB
2286 // BI: br i1 %y, TrueDest, FalseDest
2287 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2288 // FalseWeight for PBI * TrueWeight for BI.
2289 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2290 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2291 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2292 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2293 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002294 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2295 PBI->setSuccessor(1, FalseDest);
2296 }
Manman Renbfb9d432012-09-15 00:39:57 +00002297 if (NewWeights.size() == 2) {
2298 // Halve the weights if any of them cannot fit in an uint32_t
2299 FitWeights(NewWeights);
2300
2301 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2302 PBI->setMetadata(LLVMContext::MD_prof,
2303 MDBuilder(BI->getContext()).
2304 createBranchWeights(MDWeights));
2305 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002306 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002307 } else {
2308 // Update PHI nodes in the common successors.
2309 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002310 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002311 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2312 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002313 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002314 if (PBI->getSuccessor(0) == TrueDest) {
2315 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2316 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2317 // is false: !PBI_Cond and BI_Value
2318 Instruction *NotCond =
2319 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2320 "not.cond"));
2321 MergedCond =
2322 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2323 NotCond, New,
2324 "and.cond"));
2325 if (PBI_C->isOne())
2326 MergedCond =
2327 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2328 PBI->getCondition(), MergedCond,
2329 "or.cond"));
2330 } else {
2331 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2332 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2333 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002334 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002335 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2336 PBI->getCondition(), New,
2337 "and.cond"));
2338 if (PBI_C->isOne()) {
2339 Instruction *NotCond =
2340 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2341 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002342 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002343 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2344 NotCond, MergedCond,
2345 "or.cond"));
2346 }
2347 }
2348 // Update PHI Node.
2349 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2350 MergedCond);
2351 }
2352 // Change PBI from Conditional to Unconditional.
2353 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2354 EraseTerminatorInstAndDCECond(PBI);
2355 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002356 }
Devang Pateld715ec82011-04-06 22:37:20 +00002357
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002358 // TODO: If BB is reachable from all paths through PredBlock, then we
2359 // could replace PBI's branch probabilities with BI's.
2360
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002361 // Copy any debug value intrinsics into the end of PredBlock.
2362 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2363 if (isa<DbgInfoIntrinsic>(*I))
2364 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002365
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002366 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002367 }
2368 return false;
2369}
2370
James Molloy4de84dd2015-11-04 15:28:04 +00002371// If there is only one store in BB1 and BB2, return it, otherwise return
2372// nullptr.
2373static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2374 StoreInst *S = nullptr;
2375 for (auto *BB : {BB1, BB2}) {
2376 if (!BB)
2377 continue;
2378 for (auto &I : *BB)
2379 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2380 if (S)
2381 // Multiple stores seen.
2382 return nullptr;
2383 else
2384 S = SI;
2385 }
2386 }
2387 return S;
2388}
2389
2390static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2391 Value *AlternativeV = nullptr) {
2392 // PHI is going to be a PHI node that allows the value V that is defined in
2393 // BB to be referenced in BB's only successor.
2394 //
2395 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2396 // doesn't matter to us what the other operand is (it'll never get used). We
2397 // could just create a new PHI with an undef incoming value, but that could
2398 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2399 // other PHI. So here we directly look for some PHI in BB's successor with V
2400 // as an incoming operand. If we find one, we use it, else we create a new
2401 // one.
2402 //
2403 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2404 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2405 // where OtherBB is the single other predecessor of BB's only successor.
2406 PHINode *PHI = nullptr;
2407 BasicBlock *Succ = BB->getSingleSuccessor();
2408
2409 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2410 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2411 PHI = cast<PHINode>(I);
2412 if (!AlternativeV)
2413 break;
2414
2415 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2416 auto PredI = pred_begin(Succ);
2417 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2418 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2419 break;
2420 PHI = nullptr;
2421 }
2422 if (PHI)
2423 return PHI;
2424
James Molloy3d21dcf2015-12-16 14:12:44 +00002425 // If V is not an instruction defined in BB, just return it.
2426 if (!AlternativeV &&
2427 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2428 return V;
2429
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002430 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
James Molloy4de84dd2015-11-04 15:28:04 +00002431 PHI->addIncoming(V, BB);
2432 for (BasicBlock *PredBB : predecessors(Succ))
2433 if (PredBB != BB)
2434 PHI->addIncoming(AlternativeV ? AlternativeV : UndefValue::get(V->getType()),
2435 PredBB);
2436 return PHI;
2437}
2438
2439static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2440 BasicBlock *QTB, BasicBlock *QFB,
2441 BasicBlock *PostBB, Value *Address,
2442 bool InvertPCond, bool InvertQCond) {
2443 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2444 return Operator::getOpcode(&I) == Instruction::BitCast &&
2445 I.getType()->isPointerTy();
2446 };
2447
2448 // If we're not in aggressive mode, we only optimize if we have some
2449 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2450 auto IsWorthwhile = [&](BasicBlock *BB) {
2451 if (!BB)
2452 return true;
2453 // Heuristic: if the block can be if-converted/phi-folded and the
2454 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2455 // thread this store.
James Molloy9e959ac2015-11-05 08:40:19 +00002456 unsigned N = 0;
2457 for (auto &I : *BB) {
2458 // Cheap instructions viable for folding.
2459 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2460 isa<StoreInst>(I))
2461 ++N;
2462 // Free instructions.
2463 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2464 IsaBitcastOfPointerType(I))
2465 continue;
2466 else
James Molloy4de84dd2015-11-04 15:28:04 +00002467 return false;
James Molloy9e959ac2015-11-05 08:40:19 +00002468 }
2469 return N <= PHINodeFoldingThreshold;
James Molloy4de84dd2015-11-04 15:28:04 +00002470 };
2471
2472 if (!MergeCondStoresAggressively && (!IsWorthwhile(PTB) ||
2473 !IsWorthwhile(PFB) ||
2474 !IsWorthwhile(QTB) ||
2475 !IsWorthwhile(QFB)))
2476 return false;
2477
2478 // For every pointer, there must be exactly two stores, one coming from
2479 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2480 // store (to any address) in PTB,PFB or QTB,QFB.
2481 // FIXME: We could relax this restriction with a bit more work and performance
2482 // testing.
2483 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2484 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2485 if (!PStore || !QStore)
2486 return false;
2487
2488 // Now check the stores are compatible.
2489 if (!QStore->isUnordered() || !PStore->isUnordered())
2490 return false;
2491
2492 // Check that sinking the store won't cause program behavior changes. Sinking
2493 // the store out of the Q blocks won't change any behavior as we're sinking
2494 // from a block to its unconditional successor. But we're moving a store from
2495 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2496 // So we need to check that there are no aliasing loads or stores in
2497 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2498 // operations between PStore and the end of its parent block.
2499 //
2500 // The ideal way to do this is to query AliasAnalysis, but we don't
2501 // preserve AA currently so that is dangerous. Be super safe and just
2502 // check there are no other memory operations at all.
2503 for (auto &I : *QFB->getSinglePredecessor())
2504 if (I.mayReadOrWriteMemory())
2505 return false;
2506 for (auto &I : *QFB)
2507 if (&I != QStore && I.mayReadOrWriteMemory())
2508 return false;
2509 if (QTB)
2510 for (auto &I : *QTB)
2511 if (&I != QStore && I.mayReadOrWriteMemory())
2512 return false;
2513 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2514 I != E; ++I)
2515 if (&*I != PStore && I->mayReadOrWriteMemory())
2516 return false;
2517
2518 // OK, we're going to sink the stores to PostBB. The store has to be
2519 // conditional though, so first create the predicate.
2520 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2521 ->getCondition();
2522 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2523 ->getCondition();
2524
2525 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2526 PStore->getParent());
2527 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2528 QStore->getParent(), PPHI);
2529
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002530 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2531
James Molloy4de84dd2015-11-04 15:28:04 +00002532 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2533 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2534
2535 if (InvertPCond)
2536 PPred = QB.CreateNot(PPred);
2537 if (InvertQCond)
2538 QPred = QB.CreateNot(QPred);
2539 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2540
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002541 auto *T =
2542 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
James Molloy4de84dd2015-11-04 15:28:04 +00002543 QB.SetInsertPoint(T);
2544 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2545 AAMDNodes AAMD;
2546 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2547 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2548 SI->setAAMetadata(AAMD);
2549
2550 QStore->eraseFromParent();
2551 PStore->eraseFromParent();
2552
2553 return true;
2554}
2555
2556static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) {
2557 // The intention here is to find diamonds or triangles (see below) where each
2558 // conditional block contains a store to the same address. Both of these
2559 // stores are conditional, so they can't be unconditionally sunk. But it may
2560 // be profitable to speculatively sink the stores into one merged store at the
2561 // end, and predicate the merged store on the union of the two conditions of
2562 // PBI and QBI.
2563 //
2564 // This can reduce the number of stores executed if both of the conditions are
2565 // true, and can allow the blocks to become small enough to be if-converted.
2566 // This optimization will also chain, so that ladders of test-and-set
2567 // sequences can be if-converted away.
2568 //
2569 // We only deal with simple diamonds or triangles:
2570 //
2571 // PBI or PBI or a combination of the two
2572 // / \ | \
2573 // PTB PFB | PFB
2574 // \ / | /
2575 // QBI QBI
2576 // / \ | \
2577 // QTB QFB | QFB
2578 // \ / | /
2579 // PostBB PostBB
2580 //
2581 // We model triangles as a type of diamond with a nullptr "true" block.
2582 // Triangles are canonicalized so that the fallthrough edge is represented by
2583 // a true condition, as in the diagram above.
2584 //
2585 BasicBlock *PTB = PBI->getSuccessor(0);
2586 BasicBlock *PFB = PBI->getSuccessor(1);
2587 BasicBlock *QTB = QBI->getSuccessor(0);
2588 BasicBlock *QFB = QBI->getSuccessor(1);
2589 BasicBlock *PostBB = QFB->getSingleSuccessor();
2590
2591 bool InvertPCond = false, InvertQCond = false;
2592 // Canonicalize fallthroughs to the true branches.
2593 if (PFB == QBI->getParent()) {
2594 std::swap(PFB, PTB);
2595 InvertPCond = true;
2596 }
2597 if (QFB == PostBB) {
2598 std::swap(QFB, QTB);
2599 InvertQCond = true;
2600 }
2601
2602 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
2603 // and QFB may not. Model fallthroughs as a nullptr block.
2604 if (PTB == QBI->getParent())
2605 PTB = nullptr;
2606 if (QTB == PostBB)
2607 QTB = nullptr;
2608
2609 // Legality bailouts. We must have at least the non-fallthrough blocks and
2610 // the post-dominating block, and the non-fallthroughs must only have one
2611 // predecessor.
2612 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
2613 return BB->getSinglePredecessor() == P &&
2614 BB->getSingleSuccessor() == S;
2615 };
2616 if (!PostBB ||
2617 !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
2618 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
2619 return false;
2620 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
2621 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
2622 return false;
2623 if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2)
2624 return false;
2625
2626 // OK, this is a sequence of two diamonds or triangles.
2627 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
2628 SmallPtrSet<Value *,4> PStoreAddresses, QStoreAddresses;
2629 for (auto *BB : {PTB, PFB}) {
2630 if (!BB)
2631 continue;
2632 for (auto &I : *BB)
2633 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2634 PStoreAddresses.insert(SI->getPointerOperand());
2635 }
2636 for (auto *BB : {QTB, QFB}) {
2637 if (!BB)
2638 continue;
2639 for (auto &I : *BB)
2640 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2641 QStoreAddresses.insert(SI->getPointerOperand());
2642 }
2643
2644 set_intersect(PStoreAddresses, QStoreAddresses);
2645 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
2646 // clear what it contains.
2647 auto &CommonAddresses = PStoreAddresses;
2648
2649 bool Changed = false;
2650 for (auto *Address : CommonAddresses)
2651 Changed |= mergeConditionalStoreToAddress(
2652 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond);
2653 return Changed;
2654}
2655
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002656/// If we have a conditional branch as a predecessor of another block,
2657/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00002658/// that PBI and BI are both conditional branches, and BI is in one of the
2659/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00002660static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
2661 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00002662 assert(PBI->isConditional() && BI->isConditional());
2663 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002664
Chris Lattner9aada1d2008-07-13 21:53:26 +00002665 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002666 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002667 // this conditional branch redundant.
2668 if (PBI->getCondition() == BI->getCondition() &&
2669 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2670 // Okay, the outcome of this conditional branch is statically
2671 // knowable. If this block had a single pred, handle specially.
2672 if (BB->getSinglePredecessor()) {
2673 // Turn this into a branch on constant.
2674 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002675 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002676 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002677 return true; // Nuke the branch on constant.
2678 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002679
Chris Lattner9aada1d2008-07-13 21:53:26 +00002680 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2681 // in the constant and simplify the block result. Subsequent passes of
2682 // simplifycfg will thread the block.
2683 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002684 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002685 PHINode *NewPN = PHINode::Create(
2686 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
2687 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00002688 // Okay, we're going to insert the PHI node. Since PBI is not the only
2689 // predecessor, compute the PHI'd conditional value for all of the preds.
2690 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002691 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002692 BasicBlock *P = *PI;
2693 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002694 PBI != BI && PBI->isConditional() &&
2695 PBI->getCondition() == BI->getCondition() &&
2696 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2697 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002698 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002699 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002700 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002701 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002702 }
Gabor Greif8629f122010-07-12 10:59:23 +00002703 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002704
Chris Lattner9aada1d2008-07-13 21:53:26 +00002705 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002706 return true;
2707 }
2708 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002709
Philip Reamesb42db212015-10-14 22:46:19 +00002710 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2711 if (CE->canTrap())
2712 return false;
2713
Philip Reames846e3e42015-10-29 03:11:49 +00002714 // If BI is reached from the true path of PBI and PBI's condition implies
2715 // BI's condition, we know the direction of the BI branch.
2716 if (PBI->getSuccessor(0) == BI->getParent() &&
Sanjoy Das55ea67c2015-11-06 19:01:08 +00002717 isImpliedCondition(PBI->getCondition(), BI->getCondition(), DL) &&
Philip Reames846e3e42015-10-29 03:11:49 +00002718 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
2719 BB->getSinglePredecessor()) {
2720 // Turn this into a branch on constant.
2721 auto *OldCond = BI->getCondition();
2722 BI->setCondition(ConstantInt::getTrue(BB->getContext()));
2723 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
2724 return true; // Nuke the branch on constant.
2725 }
2726
James Molloy4de84dd2015-11-04 15:28:04 +00002727 // If both branches are conditional and both contain stores to the same
2728 // address, remove the stores from the conditionals and create a conditional
2729 // merged store at the end.
2730 if (MergeCondStores && mergeConditionalStores(PBI, BI))
2731 return true;
2732
Chris Lattner9aada1d2008-07-13 21:53:26 +00002733 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002734 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002735 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002736 BasicBlock::iterator BBI = BB->begin();
2737 // Ignore dbg intrinsics.
2738 while (isa<DbgInfoIntrinsic>(BBI))
2739 ++BBI;
2740 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002741 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002742
Chris Lattner834ab4e2008-07-13 22:04:41 +00002743 int PBIOp, BIOp;
2744 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2745 PBIOp = BIOp = 0;
2746 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2747 PBIOp = 0, BIOp = 1;
2748 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2749 PBIOp = 1, BIOp = 0;
2750 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2751 PBIOp = BIOp = 1;
2752 else
2753 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002754
Chris Lattner834ab4e2008-07-13 22:04:41 +00002755 // Check to make sure that the other destination of this branch
2756 // isn't BB itself. If so, this is an infinite loop that will
2757 // keep getting unwound.
2758 if (PBI->getSuccessor(PBIOp) == BB)
2759 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002760
2761 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002762 // insertion of a large number of select instructions. For targets
2763 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002764
Sanjay Patela932da82014-07-07 21:19:00 +00002765 // Also do not perform this transformation if any phi node in the common
2766 // destination block can trap when reached by BB or PBB (PR17073). In that
2767 // case, it would be unsafe to hoist the operation into a select instruction.
2768
2769 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002770 unsigned NumPhis = 0;
2771 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002772 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002773 if (NumPhis > 2) // Disable this xform.
2774 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002775
Sanjay Patela932da82014-07-07 21:19:00 +00002776 PHINode *PN = cast<PHINode>(II);
2777 Value *BIV = PN->getIncomingValueForBlock(BB);
2778 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2779 if (CE->canTrap())
2780 return false;
2781
2782 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2783 Value *PBIV = PN->getIncomingValue(PBBIdx);
2784 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2785 if (CE->canTrap())
2786 return false;
2787 }
2788
Chris Lattner834ab4e2008-07-13 22:04:41 +00002789 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002790 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002791
David Greene725c7c32010-01-05 01:26:52 +00002792 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002793 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002794
2795
Chris Lattner80b03a12008-07-13 22:23:11 +00002796 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2797 // branch in it, where one edge (OtherDest) goes back to itself but the other
2798 // exits. We don't *know* that the program avoids the infinite loop
2799 // (even though that seems likely). If we do this xform naively, we'll end up
2800 // recursively unpeeling the loop. Since we know that (after the xform is
2801 // done) that the block *is* infinite if reached, we just make it an obviously
2802 // infinite loop with no cond branch.
2803 if (OtherDest == BB) {
2804 // Insert it at the end of the function, because it's either code,
2805 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002806 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2807 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002808 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2809 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002810 }
2811
David Greene725c7c32010-01-05 01:26:52 +00002812 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002813
Chris Lattner834ab4e2008-07-13 22:04:41 +00002814 // BI may have other predecessors. Because of this, we leave
2815 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002816
Chris Lattner834ab4e2008-07-13 22:04:41 +00002817 // Make sure we get to CommonDest on True&True directions.
2818 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002819 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002820 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002821 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2822
Chris Lattner834ab4e2008-07-13 22:04:41 +00002823 Value *BICond = BI->getCondition();
2824 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002825 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2826
Chris Lattner834ab4e2008-07-13 22:04:41 +00002827 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002828 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002829
Chris Lattner834ab4e2008-07-13 22:04:41 +00002830 // Modify PBI to branch on the new condition to the new dests.
2831 PBI->setCondition(Cond);
2832 PBI->setSuccessor(0, CommonDest);
2833 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002834
Manman Ren2d4c10f2012-09-17 21:30:40 +00002835 // Update branch weight for PBI.
2836 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002837 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2838 PredFalseWeight);
2839 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2840 SuccFalseWeight);
Manman Ren2d4c10f2012-09-17 21:30:40 +00002841 if (PredHasWeights && SuccHasWeights) {
2842 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2843 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2844 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2845 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2846 // The weight to CommonDest should be PredCommon * SuccTotal +
2847 // PredOther * SuccCommon.
2848 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00002849 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2850 PredOther * SuccCommon,
2851 PredOther * SuccOther};
Manman Ren2d4c10f2012-09-17 21:30:40 +00002852 // Halve the weights if any of them cannot fit in an uint32_t
2853 FitWeights(NewWeights);
2854
Manman Ren2d4c10f2012-09-17 21:30:40 +00002855 PBI->setMetadata(LLVMContext::MD_prof,
Benjamin Kramerea68a942015-02-19 15:26:17 +00002856 MDBuilder(BI->getContext())
2857 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00002858 }
2859
Chris Lattner834ab4e2008-07-13 22:04:41 +00002860 // OtherDest may have phi nodes. If so, add an entry from PBI's
2861 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002862 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002863
Chris Lattner834ab4e2008-07-13 22:04:41 +00002864 // We know that the CommonDest already had an edge from PBI to
2865 // it. If it has PHIs though, the PHIs may have different
2866 // entries for BB and PBI's BB. If so, insert a select to make
2867 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002868 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002869 for (BasicBlock::iterator II = CommonDest->begin();
2870 (PN = dyn_cast<PHINode>(II)); ++II) {
2871 Value *BIV = PN->getIncomingValueForBlock(BB);
2872 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2873 Value *PBIV = PN->getIncomingValue(PBBIdx);
2874 if (BIV != PBIV) {
2875 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002876 Value *NV = cast<SelectInst>
2877 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002878 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002879 }
2880 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002881
David Greene725c7c32010-01-05 01:26:52 +00002882 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2883 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002884
Chris Lattner834ab4e2008-07-13 22:04:41 +00002885 // This basic block is probably dead. We know it has at least
2886 // one fewer predecessor.
2887 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002888}
2889
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002890// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2891// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00002892// Takes care of updating the successors and removing the old terminator.
2893// Also makes sure not to introduce new successors by assuming that edges to
2894// non-successor TrueBBs and FalseBBs aren't reachable.
2895static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002896 BasicBlock *TrueBB, BasicBlock *FalseBB,
2897 uint32_t TrueWeight,
2898 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002899 // Remove any superfluous successor edges from the CFG.
2900 // First, figure out which successors to preserve.
2901 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2902 // successor.
2903 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002904 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002905
2906 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00002907 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002908 // Make sure only to keep exactly one copy of each edge.
2909 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002910 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002911 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002912 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002913 else
David Majnemerdc3b67b2015-10-21 18:22:24 +00002914 Succ->removePredecessor(OldTerm->getParent(),
2915 /*DontDeleteUselessPHIs=*/true);
Frits van Bommel8e158492011-01-11 12:52:11 +00002916 }
2917
Devang Patel2c2ea222011-05-18 18:43:31 +00002918 IRBuilder<> Builder(OldTerm);
2919 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2920
Frits van Bommel8e158492011-01-11 12:52:11 +00002921 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002922 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002923 if (TrueBB == FalseBB)
2924 // We were only looking for one successor, and it was present.
2925 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002926 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002927 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002928 // We found both of the successors we were looking for.
2929 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002930 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2931 if (TrueWeight != FalseWeight)
2932 NewBI->setMetadata(LLVMContext::MD_prof,
2933 MDBuilder(OldTerm->getContext()).
2934 createBranchWeights(TrueWeight, FalseWeight));
2935 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002936 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2937 // Neither of the selected blocks were successors, so this
2938 // terminator must be unreachable.
2939 new UnreachableInst(OldTerm->getContext(), OldTerm);
2940 } else {
2941 // One of the selected values was a successor, but the other wasn't.
2942 // Insert an unconditional branch to the one that was found;
2943 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002944 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002945 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002946 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002947 else
2948 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002949 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002950 }
2951
2952 EraseTerminatorInstAndDCECond(OldTerm);
2953 return true;
2954}
2955
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002956// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00002957// (switch (select cond, X, Y)) on constant X, Y
2958// with a branch - conditional if X and Y lead to distinct BBs,
2959// unconditional otherwise.
2960static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2961 // Check for constant integer values in the select.
2962 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2963 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2964 if (!TrueVal || !FalseVal)
2965 return false;
2966
2967 // Find the relevant condition and destinations.
2968 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002969 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2970 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002971
Manman Ren774246a2012-09-17 22:28:55 +00002972 // Get weight for TrueBB and FalseBB.
2973 uint32_t TrueWeight = 0, FalseWeight = 0;
2974 SmallVector<uint64_t, 8> Weights;
2975 bool HasWeights = HasBranchWeights(SI);
2976 if (HasWeights) {
2977 GetBranchWeights(SI, Weights);
2978 if (Weights.size() == 1 + SI->getNumCases()) {
2979 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2980 getSuccessorIndex()];
2981 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2982 getSuccessorIndex()];
2983 }
2984 }
2985
Frits van Bommel8ae07992011-02-28 09:44:07 +00002986 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002987 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2988 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002989}
2990
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002991// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002992// (indirectbr (select cond, blockaddress(@fn, BlockA),
2993// blockaddress(@fn, BlockB)))
2994// with
2995// (br cond, BlockA, BlockB).
2996static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2997 // Check that both operands of the select are block addresses.
2998 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2999 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3000 if (!TBA || !FBA)
3001 return false;
3002
3003 // Extract the actual blocks.
3004 BasicBlock *TrueBB = TBA->getBasicBlock();
3005 BasicBlock *FalseBB = FBA->getBasicBlock();
3006
Frits van Bommel8e158492011-01-11 12:52:11 +00003007 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00003008 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
3009 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003010}
3011
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003012/// This is called when we find an icmp instruction
3013/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003014/// block that ends with an uncond branch. We are looking for a very specific
3015/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3016/// this case, we merge the first two "or's of icmp" into a switch, but then the
3017/// default value goes to an uncond block with a seteq in it, we get something
3018/// like:
3019///
3020/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3021/// DEFAULT:
3022/// %tmp = icmp eq i8 %A, 92
3023/// br label %end
3024/// end:
3025/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00003026///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003027/// We prefer to split the edge to 'end' so that there is a true/false entry to
3028/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003029static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003030 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
3031 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
3032 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003033 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00003034
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003035 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3036 // complex.
3037 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
3038
3039 Value *V = ICI->getOperand(0);
3040 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00003041
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003042 // The pattern we're looking for is where our only predecessor is a switch on
3043 // 'V' and this block is the default case for the switch. In this case we can
3044 // fold the compared value into the switch to simplify things.
3045 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00003046 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003047
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003048 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3049 if (SI->getCondition() != V)
3050 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003051
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003052 // If BB is reachable on a non-default case, then we simply know the value of
3053 // V in this block. Substitute it and constant fold the icmp instruction
3054 // away.
3055 if (SI->getDefaultDest() != BB) {
3056 ConstantInt *VVal = SI->findCaseDest(BB);
3057 assert(VVal && "Should have a unique destination value");
3058 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003059
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003060 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00003061 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003062 ICI->eraseFromParent();
3063 }
3064 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003065 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003066 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003067
Chris Lattner62cc76e2010-12-13 03:43:57 +00003068 // Ok, the block is reachable from the default dest. If the constant we're
3069 // comparing exists in one of the other edges, then we can constant fold ICI
3070 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003071 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00003072 Value *V;
3073 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3074 V = ConstantInt::getFalse(BB->getContext());
3075 else
3076 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003077
Chris Lattner62cc76e2010-12-13 03:43:57 +00003078 ICI->replaceAllUsesWith(V);
3079 ICI->eraseFromParent();
3080 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003081 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00003082 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003083
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003084 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3085 // the block.
3086 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003087 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00003088 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003089 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3090 return false;
3091
3092 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3093 // true in the PHI.
3094 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3095 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3096
3097 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3098 std::swap(DefaultCst, NewCst);
3099
3100 // Replace ICI (which is used by the PHI for the default value) with true or
3101 // false depending on if it is EQ or NE.
3102 ICI->replaceAllUsesWith(DefaultCst);
3103 ICI->eraseFromParent();
3104
3105 // Okay, the switch goes to this block on a default value. Add an edge from
3106 // the switch to the merge point on the compared value.
3107 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
3108 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00003109 SmallVector<uint64_t, 8> Weights;
3110 bool HasWeights = HasBranchWeights(SI);
3111 if (HasWeights) {
3112 GetBranchWeights(SI, Weights);
3113 if (Weights.size() == 1 + SI->getNumCases()) {
3114 // Split weight for default case to case for "Cst".
3115 Weights[0] = (Weights[0]+1) >> 1;
3116 Weights.push_back(Weights[0]);
3117
3118 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3119 SI->setMetadata(LLVMContext::MD_prof,
3120 MDBuilder(SI->getContext()).
3121 createBranchWeights(MDWeights));
3122 }
3123 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003124 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003125
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003126 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00003127 Builder.SetInsertPoint(NewBB);
3128 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3129 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003130 PHIUse->addIncoming(NewCst, NewBB);
3131 return true;
3132}
3133
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003134/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003135/// Check to see if it is branching on an or/and chain of icmp instructions, and
3136/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003137static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3138 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003139 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00003140 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003141
Chris Lattnera69c4432010-12-13 05:03:41 +00003142 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3143 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3144 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003145
Mehdi Amini9a25cb82014-11-19 20:09:11 +00003146 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00003147 ConstantComparesGatherer ConstantCompare(Cond, DL);
3148 // Unpack the result
3149 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
3150 Value *CompVal = ConstantCompare.CompValue;
3151 unsigned UsedICmps = ConstantCompare.UsedICmps;
3152 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003153
Chris Lattnera69c4432010-12-13 05:03:41 +00003154 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00003155 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00003156
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003157 // Avoid turning single icmps into a switch.
3158 if (UsedICmps <= 1)
3159 return false;
3160
Mehdi Aminiffd01002014-11-20 22:40:25 +00003161 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3162
Chris Lattnera69c4432010-12-13 05:03:41 +00003163 // There might be duplicate constants in the list, which the switch
3164 // instruction can't handle, remove them now.
3165 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3166 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003167
Chris Lattnera69c4432010-12-13 05:03:41 +00003168 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00003169 // transformation. A switch with one value is just a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003170 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003171
Andrew Trick3051aa12012-08-29 21:46:38 +00003172 // TODO: Preserve branch weight metadata, similarly to how
3173 // FoldValueComparisonIntoPredecessors preserves it.
3174
Chris Lattnera69c4432010-12-13 05:03:41 +00003175 // Figure out which block is which destination.
3176 BasicBlock *DefaultBB = BI->getSuccessor(1);
3177 BasicBlock *EdgeBB = BI->getSuccessor(0);
3178 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003179
Chris Lattnera69c4432010-12-13 05:03:41 +00003180 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003181
Chris Lattnerd7beca32010-12-14 06:17:25 +00003182 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003183 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003184
Chris Lattnera69c4432010-12-13 05:03:41 +00003185 // If there are any extra values that couldn't be folded into the switch
3186 // then we evaluate them with an explicit branch first. Split the block
3187 // right before the condbr to handle it.
3188 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003189 BasicBlock *NewBB =
3190 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00003191 // Remove the uncond branch added to the old block.
3192 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00003193 Builder.SetInsertPoint(OldTI);
3194
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003195 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00003196 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003197 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00003198 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003199
Chris Lattnera69c4432010-12-13 05:03:41 +00003200 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003201
Chris Lattnercb570f82010-12-13 05:34:18 +00003202 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3203 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003204 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003205
Chris Lattnerd7beca32010-12-14 06:17:25 +00003206 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
3207 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00003208 BB = NewBB;
3209 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00003210
3211 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00003212 // Convert pointer to int before we switch.
3213 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003214 CompVal = Builder.CreatePtrToInt(
3215 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00003216 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003217
Chris Lattnera69c4432010-12-13 05:03:41 +00003218 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00003219 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00003220
Chris Lattnera69c4432010-12-13 05:03:41 +00003221 // Add all of the 'cases' to the switch instruction.
3222 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3223 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003224
Chris Lattnera69c4432010-12-13 05:03:41 +00003225 // We added edges from PI to the EdgeBB. As such, if there were any
3226 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3227 // the number of edges added.
3228 for (BasicBlock::iterator BBI = EdgeBB->begin();
3229 isa<PHINode>(BBI); ++BBI) {
3230 PHINode *PN = cast<PHINode>(BBI);
3231 Value *InVal = PN->getIncomingValueForBlock(BB);
3232 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
3233 PN->addIncoming(InVal, BB);
3234 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003235
Chris Lattnera69c4432010-12-13 05:03:41 +00003236 // Erase the old branch instruction.
3237 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003238
Chris Lattnerd7beca32010-12-14 06:17:25 +00003239 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00003240 return true;
3241}
3242
Duncan Sands29192d02011-09-05 12:57:57 +00003243bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
Chen Li1689c2f2016-01-10 05:48:01 +00003244 if (isa<PHINode>(RI->getValue()))
3245 return SimplifyCommonResume(RI);
3246 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3247 RI->getValue() == RI->getParent()->getFirstNonPHI())
3248 // The resume must unwind the exception that caused control to branch here.
3249 return SimplifySingleResume(RI);
Chen Li509ff212016-01-11 19:20:53 +00003250
3251 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003252}
3253
3254// Simplify resume that is shared by several landing pads (phi of landing pad).
3255bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3256 BasicBlock *BB = RI->getParent();
3257
3258 // Check that there are no other instructions except for debug intrinsics
3259 // between the phi of landing pads (RI->getValue()) and resume instruction.
3260 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
3261 E = RI->getIterator();
3262 while (++I != E)
3263 if (!isa<DbgInfoIntrinsic>(I))
3264 return false;
3265
3266 SmallSet<BasicBlock *, 4> TrivialUnwindBlocks;
3267 auto *PhiLPInst = cast<PHINode>(RI->getValue());
3268
3269 // Check incoming blocks to see if any of them are trivial.
3270 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues();
3271 Idx != End; Idx++) {
3272 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3273 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3274
3275 // If the block has other successors, we can not delete it because
3276 // it has other dependents.
3277 if (IncomingBB->getUniqueSuccessor() != BB)
3278 continue;
3279
3280 auto *LandingPad =
3281 dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
3282 // Not the landing pad that caused the control to branch here.
3283 if (IncomingValue != LandingPad)
3284 continue;
3285
3286 bool isTrivial = true;
3287
3288 I = IncomingBB->getFirstNonPHI()->getIterator();
3289 E = IncomingBB->getTerminator()->getIterator();
3290 while (++I != E)
3291 if (!isa<DbgInfoIntrinsic>(I)) {
3292 isTrivial = false;
3293 break;
3294 }
3295
3296 if (isTrivial)
3297 TrivialUnwindBlocks.insert(IncomingBB);
3298 }
3299
3300 // If no trivial unwind blocks, don't do any simplifications.
3301 if (TrivialUnwindBlocks.empty()) return false;
3302
3303 // Turn all invokes that unwind here into calls.
3304 for (auto *TrivialBB : TrivialUnwindBlocks) {
3305 // Blocks that will be simplified should be removed from the phi node.
3306 // Note there could be multiple edges to the resume block, and we need
3307 // to remove them all.
3308 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3309 BB->removePredecessor(TrivialBB, true);
3310
3311 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3312 PI != PE;) {
3313 BasicBlock *Pred = *PI++;
3314 removeUnwindEdge(Pred);
3315 }
3316
3317 // In each SimplifyCFG run, only the current processed block can be erased.
3318 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3319 // of erasing TrivialBB, we only remove the branch to the common resume
3320 // block so that we can later erase the resume block since it has no
3321 // predecessors.
3322 TrivialBB->getTerminator()->eraseFromParent();
3323 new UnreachableInst(RI->getContext(), TrivialBB);
3324 }
3325
3326 // Delete the resume block if all its predecessors have been removed.
3327 if (pred_empty(BB))
3328 BB->eraseFromParent();
3329
3330 return !TrivialUnwindBlocks.empty();
3331}
3332
3333// Simplify resume that is only used by a single (non-phi) landing pad.
3334bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
Duncan Sands29192d02011-09-05 12:57:57 +00003335 BasicBlock *BB = RI->getParent();
3336 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
Chen Li1689c2f2016-01-10 05:48:01 +00003337 assert (RI->getValue() == LPInst &&
3338 "Resume must unwind the exception that caused control to here");
Duncan Sands29192d02011-09-05 12:57:57 +00003339
Chen Li7009cd32015-10-23 21:13:01 +00003340 // Check that there are no other instructions except for debug intrinsics.
3341 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
Duncan Sands29192d02011-09-05 12:57:57 +00003342 while (++I != E)
3343 if (!isa<DbgInfoIntrinsic>(I))
3344 return false;
3345
Chen Lic6e28782015-10-22 20:48:38 +00003346 // Turn all invokes that unwind here into calls and delete the basic block.
Chen Li7009cd32015-10-23 21:13:01 +00003347 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3348 BasicBlock *Pred = *PI++;
3349 removeUnwindEdge(Pred);
Chen Lic6e28782015-10-22 20:48:38 +00003350 }
3351
Chen Li7009cd32015-10-23 21:13:01 +00003352 // The landingpad is now unreachable. Zap it.
3353 BB->eraseFromParent();
3354 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00003355}
3356
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003357bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
3358 // If this is a trivial cleanup pad that executes no instructions, it can be
3359 // eliminated. If the cleanup pad continues to the caller, any predecessor
3360 // that is an EH pad will be updated to continue to the caller and any
3361 // predecessor that terminates with an invoke instruction will have its invoke
3362 // instruction converted to a call instruction. If the cleanup pad being
3363 // simplified does not continue to the caller, each predecessor will be
3364 // updated to continue to the unwind destination of the cleanup pad being
3365 // simplified.
3366 BasicBlock *BB = RI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003367 CleanupPadInst *CPInst = RI->getCleanupPad();
3368 if (CPInst->getParent() != BB)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003369 // This isn't an empty cleanup.
3370 return false;
3371
3372 // Check that there are no other instructions except for debug intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003373 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003374 while (++I != E)
3375 if (!isa<DbgInfoIntrinsic>(I))
3376 return false;
3377
David Majnemer8a1c45d2015-12-12 05:38:55 +00003378 // If the cleanup return we are simplifying unwinds to the caller, this will
3379 // set UnwindDest to nullptr.
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003380 BasicBlock *UnwindDest = RI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003381 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003382
3383 // We're about to remove BB from the control flow. Before we do, sink any
3384 // PHINodes into the unwind destination. Doing this before changing the
3385 // control flow avoids some potentially slow checks, since we can currently
3386 // be certain that UnwindDest and BB have no common predecessors (since they
3387 // are both EH pads).
3388 if (UnwindDest) {
3389 // First, go through the PHI nodes in UnwindDest and update any nodes that
3390 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003391 for (BasicBlock::iterator I = UnwindDest->begin(),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003392 IE = DestEHPad->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003393 I != IE; ++I) {
3394 PHINode *DestPN = cast<PHINode>(I);
James Molloy4de84dd2015-11-04 15:28:04 +00003395
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003396 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003397 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003398 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003399 // This PHI node has an incoming value that corresponds to a control
3400 // path through the cleanup pad we are removing. If the incoming
3401 // value is in the cleanup pad, it must be a PHINode (because we
3402 // verified above that the block is otherwise empty). Otherwise, the
3403 // value is either a constant or a value that dominates the cleanup
3404 // pad being removed.
3405 //
3406 // Because BB and UnwindDest are both EH pads, all of their
3407 // predecessors must unwind to these blocks, and since no instruction
3408 // can have multiple unwind destinations, there will be no overlap in
3409 // incoming blocks between SrcPN and DestPN.
3410 Value *SrcVal = DestPN->getIncomingValue(Idx);
3411 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3412
3413 // Remove the entry for the block we are deleting.
3414 DestPN->removeIncomingValue(Idx, false);
3415
3416 if (SrcPN && SrcPN->getParent() == BB) {
3417 // If the incoming value was a PHI node in the cleanup pad we are
3418 // removing, we need to merge that PHI node's incoming values into
3419 // DestPN.
James Molloy4de84dd2015-11-04 15:28:04 +00003420 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003421 SrcIdx != SrcE; ++SrcIdx) {
3422 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3423 SrcPN->getIncomingBlock(SrcIdx));
3424 }
3425 } else {
3426 // Otherwise, the incoming value came from above BB and
3427 // so we can just reuse it. We must associate all of BB's
3428 // predecessors with this value.
3429 for (auto *pred : predecessors(BB)) {
3430 DestPN->addIncoming(SrcVal, pred);
3431 }
3432 }
3433 }
3434
3435 // Sink any remaining PHI nodes directly into UnwindDest.
David Majnemer8a1c45d2015-12-12 05:38:55 +00003436 Instruction *InsertPt = DestEHPad;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003437 for (BasicBlock::iterator I = BB->begin(),
3438 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003439 I != IE;) {
3440 // The iterator must be incremented here because the instructions are
3441 // being moved to another block.
3442 PHINode *PN = cast<PHINode>(I++);
3443 if (PN->use_empty())
3444 // If the PHI node has no uses, just leave it. It will be erased
3445 // when we erase BB below.
3446 continue;
3447
3448 // Otherwise, sink this PHI node into UnwindDest.
3449 // Any predecessors to UnwindDest which are not already represented
3450 // must be back edges which inherit the value from the path through
3451 // BB. In this case, the PHI value must reference itself.
3452 for (auto *pred : predecessors(UnwindDest))
3453 if (pred != BB)
3454 PN->addIncoming(PN, pred);
3455 PN->moveBefore(InsertPt);
3456 }
3457 }
3458
3459 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3460 // The iterator must be updated here because we are removing this pred.
3461 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003462 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003463 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003464 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003465 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003466 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003467 }
3468 }
3469
3470 // The cleanup pad is now unreachable. Zap it.
3471 BB->eraseFromParent();
3472 return true;
3473}
3474
Devang Pateldd14e0f2011-05-18 21:33:11 +00003475bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003476 BasicBlock *BB = RI->getParent();
3477 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003478
Chris Lattner25c3af32010-12-13 06:25:44 +00003479 // Find predecessors that end with branches.
3480 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3481 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003482 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3483 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003484 TerminatorInst *PTI = P->getTerminator();
3485 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3486 if (BI->isUnconditional())
3487 UncondBranchPreds.push_back(P);
3488 else
3489 CondBranchPreds.push_back(BI);
3490 }
3491 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003492
Chris Lattner25c3af32010-12-13 06:25:44 +00003493 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00003494 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003495 while (!UncondBranchPreds.empty()) {
3496 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3497 DEBUG(dbgs() << "FOLDING: " << *BB
3498 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00003499 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00003500 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003501
Chris Lattner25c3af32010-12-13 06:25:44 +00003502 // If we eliminated all predecessors of the block, delete the block now.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003503 if (pred_empty(BB))
Chris Lattner25c3af32010-12-13 06:25:44 +00003504 // We know there are no successors, so just nuke the block.
3505 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003506
Chris Lattner25c3af32010-12-13 06:25:44 +00003507 return true;
3508 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003509
Chris Lattner25c3af32010-12-13 06:25:44 +00003510 // Check out all of the conditional branches going to this return
3511 // instruction. If any of them just select between returns, change the
3512 // branch itself into a select/return pair.
3513 while (!CondBranchPreds.empty()) {
3514 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003515
Chris Lattner25c3af32010-12-13 06:25:44 +00003516 // Check to see if the non-BB successor is also a return block.
3517 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3518 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003519 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003520 return true;
3521 }
3522 return false;
3523}
3524
Chris Lattner25c3af32010-12-13 06:25:44 +00003525bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3526 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003527
Chris Lattner25c3af32010-12-13 06:25:44 +00003528 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003529
Chris Lattner25c3af32010-12-13 06:25:44 +00003530 // If there are any instructions immediately before the unreachable that can
3531 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003532 while (UI->getIterator() != BB->begin()) {
3533 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00003534 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003535 // Do not delete instructions that can have side effects which might cause
3536 // the unreachable to not be reachable; specifically, calls and volatile
3537 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003538 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003539
3540 if (BBI->mayHaveSideEffects()) {
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003541 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003542 if (SI->isVolatile())
3543 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003544 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003545 if (LI->isVolatile())
3546 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003547 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003548 if (RMWI->isVolatile())
3549 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003550 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003551 if (CXI->isVolatile())
3552 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003553 } else if (isa<CatchPadInst>(BBI)) {
3554 // A catchpad may invoke exception object constructors and such, which
3555 // in some languages can be arbitrary code, so be conservative by
3556 // default.
3557 // For CoreCLR, it just involves a type test, so can be removed.
3558 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
3559 EHPersonality::CoreCLR)
3560 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003561 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3562 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003563 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003564 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003565 // Note that deleting LandingPad's here is in fact okay, although it
3566 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3567 // all the predecessors of this block will be the unwind edges of Invokes,
3568 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003569 }
3570
Eli Friedmanaac35b32011-03-09 00:48:33 +00003571 // Delete this instruction (any uses are guaranteed to be dead)
3572 if (!BBI->use_empty())
3573 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003574 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003575 Changed = true;
3576 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003577
Chris Lattner25c3af32010-12-13 06:25:44 +00003578 // If the unreachable instruction is the first in the block, take a gander
3579 // at all of the predecessors of this instruction, and simplify them.
3580 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003581
Chris Lattner25c3af32010-12-13 06:25:44 +00003582 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3583 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3584 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003585 IRBuilder<> Builder(TI);
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003586 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003587 if (BI->isUnconditional()) {
3588 if (BI->getSuccessor(0) == BB) {
3589 new UnreachableInst(TI->getContext(), TI);
3590 TI->eraseFromParent();
3591 Changed = true;
3592 }
3593 } else {
3594 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003595 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003596 EraseTerminatorInstAndDCECond(BI);
3597 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003598 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003599 EraseTerminatorInstAndDCECond(BI);
3600 Changed = true;
3601 }
3602 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003603 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003604 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003605 i != e; ++i)
3606 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003607 BB->removePredecessor(SI->getParent());
3608 SI->removeCase(i);
3609 --i; --e;
3610 Changed = true;
3611 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003612 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
3613 if (II->getUnwindDest() == BB) {
3614 removeUnwindEdge(TI->getParent());
3615 Changed = true;
3616 }
3617 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3618 if (CSI->getUnwindDest() == BB) {
3619 removeUnwindEdge(TI->getParent());
3620 Changed = true;
3621 continue;
3622 }
3623
3624 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
3625 E = CSI->handler_end();
3626 I != E; ++I) {
3627 if (*I == BB) {
3628 CSI->removeHandler(I);
3629 --I;
3630 --E;
3631 Changed = true;
3632 }
3633 }
3634 if (CSI->getNumHandlers() == 0) {
3635 BasicBlock *CatchSwitchBB = CSI->getParent();
3636 if (CSI->hasUnwindDest()) {
3637 // Redirect preds to the unwind dest
3638 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
3639 } else {
3640 // Rewrite all preds to unwind to caller (or from invoke to call).
3641 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
3642 for (BasicBlock *EHPred : EHPreds)
3643 removeUnwindEdge(EHPred);
3644 }
3645 // The catchswitch is no longer reachable.
3646 new UnreachableInst(CSI->getContext(), CSI);
3647 CSI->eraseFromParent();
3648 Changed = true;
3649 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003650 } else if (isa<CleanupReturnInst>(TI)) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003651 new UnreachableInst(TI->getContext(), TI);
3652 TI->eraseFromParent();
3653 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00003654 }
3655 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003656
Chris Lattner25c3af32010-12-13 06:25:44 +00003657 // If this block is now dead, remove it.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003658 if (pred_empty(BB) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00003659 BB != &BB->getParent()->getEntryBlock()) {
3660 // We know there are no successors, so just nuke the block.
3661 BB->eraseFromParent();
3662 return true;
3663 }
3664
3665 return Changed;
3666}
3667
Hans Wennborg68000082015-01-26 19:52:32 +00003668static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3669 assert(Cases.size() >= 1);
3670
3671 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3672 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3673 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3674 return false;
3675 }
3676 return true;
3677}
3678
3679/// Turn a switch with two reachable destinations into an integer range
3680/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003681static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003682 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003683
Hans Wennborg68000082015-01-26 19:52:32 +00003684 bool HasDefault =
3685 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003686
Hans Wennborg68000082015-01-26 19:52:32 +00003687 // Partition the cases into two sets with different destinations.
3688 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3689 BasicBlock *DestB = nullptr;
3690 SmallVector <ConstantInt *, 16> CasesA;
3691 SmallVector <ConstantInt *, 16> CasesB;
3692
3693 for (SwitchInst::CaseIt I : SI->cases()) {
3694 BasicBlock *Dest = I.getCaseSuccessor();
3695 if (!DestA) DestA = Dest;
3696 if (Dest == DestA) {
3697 CasesA.push_back(I.getCaseValue());
3698 continue;
3699 }
3700 if (!DestB) DestB = Dest;
3701 if (Dest == DestB) {
3702 CasesB.push_back(I.getCaseValue());
3703 continue;
3704 }
3705 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003706 }
3707
Hans Wennborg68000082015-01-26 19:52:32 +00003708 assert(DestA && DestB && "Single-destination switch should have been folded.");
3709 assert(DestA != DestB);
3710 assert(DestB != SI->getDefaultDest());
3711 assert(!CasesB.empty() && "There must be non-default cases.");
3712 assert(!CasesA.empty() || HasDefault);
3713
3714 // Figure out if one of the sets of cases form a contiguous range.
3715 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3716 BasicBlock *ContiguousDest = nullptr;
3717 BasicBlock *OtherDest = nullptr;
3718 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3719 ContiguousCases = &CasesA;
3720 ContiguousDest = DestA;
3721 OtherDest = DestB;
3722 } else if (CasesAreContiguous(CasesB)) {
3723 ContiguousCases = &CasesB;
3724 ContiguousDest = DestB;
3725 OtherDest = DestA;
3726 } else
3727 return false;
3728
3729 // Start building the compare and branch.
3730
3731 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3732 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003733
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003734 Value *Sub = SI->getCondition();
3735 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00003736 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3737
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003738 Value *Cmp;
3739 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00003740 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003741 Cmp = ConstantInt::getTrue(SI->getContext());
3742 else
3743 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00003744 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003745
Manman Ren56575552012-09-18 00:47:33 +00003746 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00003747 if (HasBranchWeights(SI)) {
3748 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00003749 GetBranchWeights(SI, Weights);
3750 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00003751 uint64_t TrueWeight = 0;
3752 uint64_t FalseWeight = 0;
3753 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3754 if (SI->getSuccessor(I) == ContiguousDest)
3755 TrueWeight += Weights[I];
3756 else
3757 FalseWeight += Weights[I];
3758 }
3759 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3760 TrueWeight /= 2;
3761 FalseWeight /= 2;
3762 }
Manman Ren56575552012-09-18 00:47:33 +00003763 NewBI->setMetadata(LLVMContext::MD_prof,
Hans Wennborg68000082015-01-26 19:52:32 +00003764 MDBuilder(SI->getContext()).createBranchWeights(
3765 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00003766 }
3767 }
3768
Hans Wennborg68000082015-01-26 19:52:32 +00003769 // Prune obsolete incoming values off the successors' PHI nodes.
3770 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3771 unsigned PreviousEdges = ContiguousCases->size();
3772 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3773 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003774 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3775 }
Hans Wennborg68000082015-01-26 19:52:32 +00003776 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3777 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3778 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3779 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3780 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3781 }
3782
3783 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003784 SI->eraseFromParent();
3785
3786 return true;
3787}
Chris Lattner25c3af32010-12-13 06:25:44 +00003788
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003789/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003790/// and use it to remove dead cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003791static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3792 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003793 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003794 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003795 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003796 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003797
3798 // Gather dead cases.
3799 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003800 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003801 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3802 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3803 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003804 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003805 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003806 }
3807 }
3808
Philip Reames98a2dab2015-08-26 23:56:46 +00003809 // If we can prove that the cases must cover all possible values, the
Philip Reames05370132015-09-10 17:44:47 +00003810 // default destination becomes dead and we can remove it. If we know some
3811 // of the bits in the value, we can use that to more precisely compute the
3812 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00003813 bool HasDefault =
3814 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Philip Reames05370132015-09-10 17:44:47 +00003815 const unsigned NumUnknownBits = Bits -
3816 (KnownZero.Or(KnownOne)).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00003817 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00003818 if (HasDefault && DeadCases.empty() &&
3819 NumUnknownBits < 64 /* avoid overflow */ &&
3820 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00003821 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
3822 BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(),
3823 SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003824 SI->setDefaultDest(&*NewDefault);
3825 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00003826 auto *OldTI = NewDefault->getTerminator();
3827 new UnreachableInst(SI->getContext(), OldTI);
3828 EraseTerminatorInstAndDCECond(OldTI);
3829 return true;
3830 }
3831
Manman Ren56575552012-09-18 00:47:33 +00003832 SmallVector<uint64_t, 8> Weights;
3833 bool HasWeight = HasBranchWeights(SI);
3834 if (HasWeight) {
3835 GetBranchWeights(SI, Weights);
3836 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3837 }
3838
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003839 // Remove dead cases from the switch.
3840 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003841 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003842 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003843 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003844 if (HasWeight) {
3845 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3846 Weights.pop_back();
3847 }
3848
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003849 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003850 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003851 SI->removeCase(Case);
3852 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003853 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003854 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3855 SI->setMetadata(LLVMContext::MD_prof,
3856 MDBuilder(SI->getParent()->getContext()).
3857 createBranchWeights(MDWeights));
3858 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003859
3860 return !DeadCases.empty();
3861}
3862
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003863/// If BB would be eligible for simplification by
3864/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003865/// by an unconditional branch), look at the phi node for BB in the successor
3866/// block and see if the incoming value is equal to CaseValue. If so, return
3867/// the phi node, and set PhiIndex to BB's index in the phi node.
3868static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3869 BasicBlock *BB,
3870 int *PhiIndex) {
3871 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003872 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003873 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003874 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003875
3876 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3877 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003878 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003879
3880 BasicBlock *Succ = Branch->getSuccessor(0);
3881
3882 BasicBlock::iterator I = Succ->begin();
3883 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3884 int Idx = PHI->getBasicBlockIndex(BB);
3885 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3886
3887 Value *InValue = PHI->getIncomingValue(Idx);
3888 if (InValue != CaseValue) continue;
3889
3890 *PhiIndex = Idx;
3891 return PHI;
3892 }
3893
Craig Topperf40110f2014-04-25 05:29:35 +00003894 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003895}
3896
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003897/// Try to forward the condition of a switch instruction to a phi node
3898/// dominated by the switch, if that would mean that some of the destination
3899/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003900/// Returns true if a change is made.
3901static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3902 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3903 ForwardingNodesMap ForwardingNodes;
3904
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003905 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003906 ConstantInt *CaseValue = I.getCaseValue();
3907 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003908
3909 int PhiIndex;
3910 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3911 &PhiIndex);
3912 if (!PHI) continue;
3913
3914 ForwardingNodes[PHI].push_back(PhiIndex);
3915 }
3916
3917 bool Changed = false;
3918
3919 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3920 E = ForwardingNodes.end(); I != E; ++I) {
3921 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003922 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003923
3924 if (Indexes.size() < 2) continue;
3925
3926 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3927 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3928 Changed = true;
3929 }
3930
3931 return Changed;
3932}
3933
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003934/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003935/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003936static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003937 if (C->isThreadDependent())
3938 return false;
3939 if (C->isDLLImportDependent())
3940 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003941
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003942 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3943 return CE->isGEPWithNoNotionalOverIndexing();
3944
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003945 return isa<ConstantFP>(C) ||
3946 isa<ConstantInt>(C) ||
3947 isa<ConstantPointerNull>(C) ||
3948 isa<GlobalValue>(C) ||
3949 isa<UndefValue>(C);
3950}
3951
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003952/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003953/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003954static Constant *LookupConstant(Value *V,
3955 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3956 if (Constant *C = dyn_cast<Constant>(V))
3957 return C;
3958 return ConstantPool.lookup(V);
3959}
3960
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003961/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003962/// simple instructions such as binary operations where both operands are
3963/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003964/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003965static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003966ConstantFold(Instruction *I, const DataLayout &DL,
3967 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003968 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003969 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3970 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003971 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003972 if (A->isAllOnesValue())
3973 return LookupConstant(Select->getTrueValue(), ConstantPool);
3974 if (A->isNullValue())
3975 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003976 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003977 }
3978
Benjamin Kramer7c302602013-11-12 12:24:36 +00003979 SmallVector<Constant *, 4> COps;
3980 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3981 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3982 COps.push_back(A);
3983 else
Craig Topperf40110f2014-04-25 05:29:35 +00003984 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003985 }
3986
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003987 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00003988 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3989 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003990 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00003991
3992 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003993}
3994
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003995/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003996/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003997/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003998/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003999static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004000GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00004001 BasicBlock **CommonDest,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004002 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
4003 const DataLayout &DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004004 // The block from which we enter the common destination.
4005 BasicBlock *Pred = SI->getParent();
4006
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004007 // If CaseDest is empty except for some side-effect free instructions through
4008 // which we can constant-propagate the CaseVal, continue to its successor.
4009 SmallDenseMap<Value*, Constant*> ConstantPool;
4010 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4011 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4012 ++I) {
4013 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4014 // If the terminator is a simple branch, continue to the next block.
4015 if (T->getNumSuccessors() != 1)
4016 return false;
4017 Pred = CaseDest;
4018 CaseDest = T->getSuccessor(0);
4019 } else if (isa<DbgInfoIntrinsic>(I)) {
4020 // Skip debug intrinsic.
4021 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004022 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004023 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00004024
4025 // If the instruction has uses outside this block or a phi node slot for
4026 // the block, it is not safe to bypass the instruction since it would then
4027 // no longer dominate all its uses.
4028 for (auto &Use : I->uses()) {
4029 User *User = Use.getUser();
4030 if (Instruction *I = dyn_cast<Instruction>(User))
4031 if (I->getParent() == CaseDest)
4032 continue;
4033 if (PHINode *Phi = dyn_cast<PHINode>(User))
4034 if (Phi->getIncomingBlock(Use) == CaseDest)
4035 continue;
4036 return false;
4037 }
4038
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004039 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004040 } else {
4041 break;
4042 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004043 }
4044
4045 // If we did not have a CommonDest before, use the current one.
4046 if (!*CommonDest)
4047 *CommonDest = CaseDest;
4048 // If the destination isn't the common one, abort.
4049 if (CaseDest != *CommonDest)
4050 return false;
4051
4052 // Get the values for this case from phi nodes in the destination block.
4053 BasicBlock::iterator I = (*CommonDest)->begin();
4054 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4055 int Idx = PHI->getBasicBlockIndex(Pred);
4056 if (Idx == -1)
4057 continue;
4058
Hans Wennborg09acdb92012-10-31 15:14:39 +00004059 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
4060 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004061 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004062 return false;
4063
4064 // Be conservative about which kinds of constants we support.
4065 if (!ValidLookupTableConstant(ConstVal))
4066 return false;
4067
4068 Res.push_back(std::make_pair(PHI, ConstVal));
4069 }
4070
Hans Wennborgac114a32014-01-12 00:44:41 +00004071 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004072}
4073
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004074// Helper function used to add CaseVal to the list of cases that generate
4075// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004076static void MapCaseToResult(ConstantInt *CaseVal,
4077 SwitchCaseResultVectorTy &UniqueResults,
4078 Constant *Result) {
4079 for (auto &I : UniqueResults) {
4080 if (I.first == Result) {
4081 I.second.push_back(CaseVal);
4082 return;
4083 }
4084 }
4085 UniqueResults.push_back(std::make_pair(Result,
4086 SmallVector<ConstantInt*, 4>(1, CaseVal)));
4087}
4088
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004089// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004090// results for the PHI node of the common destination block for a switch
4091// instruction. Returns false if multiple PHI nodes have been found or if
4092// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004093static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4094 BasicBlock *&CommonDest,
4095 SwitchCaseResultVectorTy &UniqueResults,
4096 Constant *&DefaultResult,
4097 const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004098 for (auto &I : SI->cases()) {
4099 ConstantInt *CaseVal = I.getCaseValue();
4100
4101 // Resulting value at phi nodes for this case value.
4102 SwitchCaseResultsTy Results;
4103 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4104 DL))
4105 return false;
4106
4107 // Only one value per case is permitted
4108 if (Results.size() > 1)
4109 return false;
4110 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4111
4112 // Check the PHI consistency.
4113 if (!PHI)
4114 PHI = Results[0].first;
4115 else if (PHI != Results[0].first)
4116 return false;
4117 }
4118 // Find the default result value.
4119 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4120 BasicBlock *DefaultDest = SI->getDefaultDest();
4121 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4122 DL);
4123 // If the default value is not found abort unless the default destination
4124 // is unreachable.
4125 DefaultResult =
4126 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4127 if ((!DefaultResult &&
4128 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
4129 return false;
4130
4131 return true;
4132}
4133
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004134// Helper function that checks if it is possible to transform a switch with only
4135// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004136// Example:
4137// switch (a) {
4138// case 10: %0 = icmp eq i32 %a, 10
4139// return 10; %1 = select i1 %0, i32 10, i32 4
4140// case 20: ----> %2 = icmp eq i32 %a, 20
4141// return 2; %3 = select i1 %2, i32 2, i32 %1
4142// default:
4143// return 4;
4144// }
4145static Value *
4146ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4147 Constant *DefaultResult, Value *Condition,
4148 IRBuilder<> &Builder) {
4149 assert(ResultVector.size() == 2 &&
4150 "We should have exactly two unique results at this point");
4151 // If we are selecting between only two cases transform into a simple
4152 // select or a two-way select if default is possible.
4153 if (ResultVector[0].second.size() == 1 &&
4154 ResultVector[1].second.size() == 1) {
4155 ConstantInt *const FirstCase = ResultVector[0].second[0];
4156 ConstantInt *const SecondCase = ResultVector[1].second[0];
4157
4158 bool DefaultCanTrigger = DefaultResult;
4159 Value *SelectValue = ResultVector[1].first;
4160 if (DefaultCanTrigger) {
4161 Value *const ValueCompare =
4162 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4163 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4164 DefaultResult, "switch.select");
4165 }
4166 Value *const ValueCompare =
4167 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
4168 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
4169 "switch.select");
4170 }
4171
4172 return nullptr;
4173}
4174
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004175// Helper function to cleanup a switch instruction that has been converted into
4176// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004177static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4178 Value *SelectValue,
4179 IRBuilder<> &Builder) {
4180 BasicBlock *SelectBB = SI->getParent();
4181 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4182 PHI->removeIncomingValue(SelectBB);
4183 PHI->addIncoming(SelectValue, SelectBB);
4184
4185 Builder.CreateBr(PHI->getParent());
4186
4187 // Remove the switch.
4188 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4189 BasicBlock *Succ = SI->getSuccessor(i);
4190
4191 if (Succ == PHI->getParent())
4192 continue;
4193 Succ->removePredecessor(SelectBB);
4194 }
4195 SI->eraseFromParent();
4196}
4197
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004198/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004199/// phi nodes in a common successor block with only two different
4200/// constant values, replace the switch with select.
4201static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004202 AssumptionCache *AC, const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004203 Value *const Cond = SI->getCondition();
4204 PHINode *PHI = nullptr;
4205 BasicBlock *CommonDest = nullptr;
4206 Constant *DefaultResult;
4207 SwitchCaseResultVectorTy UniqueResults;
4208 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004209 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4210 DL))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004211 return false;
4212 // Selects choose between maximum two values.
4213 if (UniqueResults.size() != 2)
4214 return false;
4215 assert(PHI != nullptr && "PHI for value select not found");
4216
4217 Builder.SetInsertPoint(SI);
4218 Value *SelectValue = ConvertTwoCaseSwitch(
4219 UniqueResults,
4220 DefaultResult, Cond, Builder);
4221 if (SelectValue) {
4222 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4223 return true;
4224 }
4225 // The switch couldn't be converted into a select.
4226 return false;
4227}
4228
Hans Wennborg776d7122012-09-26 09:34:53 +00004229namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004230 /// This class represents a lookup table that can be used to replace a switch.
Hans Wennborg776d7122012-09-26 09:34:53 +00004231 class SwitchLookupTable {
4232 public:
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004233 /// Create a lookup table to use as a switch replacement with the contents
4234 /// of Values, using DefaultValue to fill any holes in the table.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004235 SwitchLookupTable(
4236 Module &M, uint64_t TableSize, ConstantInt *Offset,
4237 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4238 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004239
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004240 /// Build instructions with Builder to retrieve the value at
Hans Wennborg776d7122012-09-26 09:34:53 +00004241 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00004242 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00004243
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004244 /// Return true if a table with TableSize elements of
Hans Wennborg39583b82012-09-26 09:44:49 +00004245 /// type ElementType would fit in a target-legal register.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004246 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004247 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004248
Hans Wennborg776d7122012-09-26 09:34:53 +00004249 private:
4250 // Depending on the contents of the table, it can be represented in
4251 // different ways.
4252 enum {
4253 // For tables where each element contains the same value, we just have to
4254 // store that single value and return it for each lookup.
4255 SingleValueKind,
4256
Erik Eckstein105374f2014-11-17 09:13:57 +00004257 // For tables where there is a linear relationship between table index
4258 // and values. We calculate the result with a simple multiplication
4259 // and addition instead of a table lookup.
4260 LinearMapKind,
4261
Hans Wennborg39583b82012-09-26 09:44:49 +00004262 // For small tables with integer elements, we can pack them into a bitmap
4263 // that fits into a target-legal register. Values are retrieved by
4264 // shift and mask operations.
4265 BitMapKind,
4266
Hans Wennborg776d7122012-09-26 09:34:53 +00004267 // The table is stored as an array of values. Values are retrieved by load
4268 // instructions from the table.
4269 ArrayKind
4270 } Kind;
4271
4272 // For SingleValueKind, this is the single value.
4273 Constant *SingleValue;
4274
Hans Wennborg39583b82012-09-26 09:44:49 +00004275 // For BitMapKind, this is the bitmap.
4276 ConstantInt *BitMap;
4277 IntegerType *BitMapElementTy;
4278
Erik Eckstein105374f2014-11-17 09:13:57 +00004279 // For LinearMapKind, these are the constants used to derive the value.
4280 ConstantInt *LinearOffset;
4281 ConstantInt *LinearMultiplier;
4282
Hans Wennborg776d7122012-09-26 09:34:53 +00004283 // For ArrayKind, this is the array.
4284 GlobalVariable *Array;
4285 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +00004286}
Hans Wennborg776d7122012-09-26 09:34:53 +00004287
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004288SwitchLookupTable::SwitchLookupTable(
4289 Module &M, uint64_t TableSize, ConstantInt *Offset,
4290 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4291 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00004292 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00004293 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004294 assert(Values.size() && "Can't build lookup table without values!");
4295 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004296
4297 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00004298 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004299
Hans Wennborgac114a32014-01-12 00:44:41 +00004300 Type *ValueType = Values.begin()->second->getType();
4301
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004302 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00004303 SmallVector<Constant*, 64> TableContents(TableSize);
4304 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4305 ConstantInt *CaseVal = Values[I].first;
4306 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00004307 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004308
Hans Wennborg776d7122012-09-26 09:34:53 +00004309 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
4310 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004311 TableContents[Idx] = CaseRes;
4312
Hans Wennborg776d7122012-09-26 09:34:53 +00004313 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004314 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004315 }
4316
4317 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00004318 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00004319 assert(DefaultValue &&
4320 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00004321 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00004322 for (uint64_t I = 0; I < TableSize; ++I) {
4323 if (!TableContents[I])
4324 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004325 }
4326
Hans Wennborg776d7122012-09-26 09:34:53 +00004327 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004328 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004329 }
4330
Hans Wennborg776d7122012-09-26 09:34:53 +00004331 // If each element in the table contains the same value, we only need to store
4332 // that single value.
4333 if (SingleValue) {
4334 Kind = SingleValueKind;
4335 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004336 }
4337
Erik Eckstein105374f2014-11-17 09:13:57 +00004338 // Check if we can derive the value with a linear transformation from the
4339 // table index.
4340 if (isa<IntegerType>(ValueType)) {
4341 bool LinearMappingPossible = true;
4342 APInt PrevVal;
4343 APInt DistToPrev;
4344 assert(TableSize >= 2 && "Should be a SingleValue table.");
4345 // Check if there is the same distance between two consecutive values.
4346 for (uint64_t I = 0; I < TableSize; ++I) {
4347 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4348 if (!ConstVal) {
4349 // This is an undef. We could deal with it, but undefs in lookup tables
4350 // are very seldom. It's probably not worth the additional complexity.
4351 LinearMappingPossible = false;
4352 break;
4353 }
4354 APInt Val = ConstVal->getValue();
4355 if (I != 0) {
4356 APInt Dist = Val - PrevVal;
4357 if (I == 1) {
4358 DistToPrev = Dist;
4359 } else if (Dist != DistToPrev) {
4360 LinearMappingPossible = false;
4361 break;
4362 }
4363 }
4364 PrevVal = Val;
4365 }
4366 if (LinearMappingPossible) {
4367 LinearOffset = cast<ConstantInt>(TableContents[0]);
4368 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4369 Kind = LinearMapKind;
4370 ++NumLinearMaps;
4371 return;
4372 }
4373 }
4374
Hans Wennborg39583b82012-09-26 09:44:49 +00004375 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004376 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004377 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004378 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4379 for (uint64_t I = TableSize; I > 0; --I) {
4380 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00004381 // Insert values into the bitmap. Undef values are set to zero.
4382 if (!isa<UndefValue>(TableContents[I - 1])) {
4383 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4384 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4385 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004386 }
4387 BitMap = ConstantInt::get(M.getContext(), TableInt);
4388 BitMapElementTy = IT;
4389 Kind = BitMapKind;
4390 ++NumBitMaps;
4391 return;
4392 }
4393
Hans Wennborg776d7122012-09-26 09:34:53 +00004394 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004395 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004396 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4397
Hans Wennborg776d7122012-09-26 09:34:53 +00004398 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
4399 GlobalVariable::PrivateLinkage,
4400 Initializer,
4401 "switch.table");
4402 Array->setUnnamedAddr(true);
4403 Kind = ArrayKind;
4404}
4405
Manman Ren4d189fb2014-07-24 21:13:20 +00004406Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004407 switch (Kind) {
4408 case SingleValueKind:
4409 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00004410 case LinearMapKind: {
4411 // Derive the result value from the input value.
4412 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4413 false, "switch.idx.cast");
4414 if (!LinearMultiplier->isOne())
4415 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4416 if (!LinearOffset->isZero())
4417 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4418 return Result;
4419 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004420 case BitMapKind: {
4421 // Type of the bitmap (e.g. i59).
4422 IntegerType *MapTy = BitMap->getType();
4423
4424 // Cast Index to the same type as the bitmap.
4425 // Note: The Index is <= the number of elements in the table, so
4426 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00004427 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004428
4429 // Multiply the shift amount by the element width.
4430 ShiftAmt = Builder.CreateMul(ShiftAmt,
4431 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4432 "switch.shiftamt");
4433
4434 // Shift down.
4435 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
4436 "switch.downshift");
4437 // Mask off.
4438 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
4439 "switch.masked");
4440 }
Hans Wennborg776d7122012-09-26 09:34:53 +00004441 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00004442 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00004443 IntegerType *IT = cast<IntegerType>(Index->getType());
4444 uint64_t TableSize = Array->getInitializer()->getType()
4445 ->getArrayNumElements();
4446 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4447 Index = Builder.CreateZExt(Index,
4448 IntegerType::get(IT->getContext(),
4449 IT->getBitWidth() + 1),
4450 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00004451
Hans Wennborg776d7122012-09-26 09:34:53 +00004452 Value *GEPIndices[] = { Builder.getInt32(0), Index };
David Blaikieaa41cd52015-04-03 21:33:42 +00004453 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4454 GEPIndices, "switch.gep");
Hans Wennborg776d7122012-09-26 09:34:53 +00004455 return Builder.CreateLoad(GEP, "switch.load");
4456 }
4457 }
4458 llvm_unreachable("Unknown lookup table kind!");
4459}
4460
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004461bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00004462 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004463 Type *ElementType) {
4464 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004465 if (!IT)
4466 return false;
4467 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4468 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004469
4470 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4471 if (TableSize >= UINT_MAX/IT->getBitWidth())
4472 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004473 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00004474}
4475
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004476/// Determine whether a lookup table should be built for this switch, based on
4477/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004478static bool
4479ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4480 const TargetTransformInfo &TTI, const DataLayout &DL,
4481 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004482 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4483 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00004484
Chandler Carruth77d433d2012-11-30 09:26:25 +00004485 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00004486 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00004487 for (const auto &I : ResultTypes) {
4488 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004489
4490 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004491 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004492
4493 // Saturate this flag to false.
4494 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004495 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004496
4497 // If both flags saturate, we're done. NOTE: This *only* works with
4498 // saturating flags, and all flags have to saturate first due to the
4499 // non-deterministic behavior of iterating over a dense map.
4500 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00004501 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00004502 }
Evan Cheng65df8082012-11-30 02:02:42 +00004503
Chandler Carruth77d433d2012-11-30 09:26:25 +00004504 // If each table would fit in a register, we should build it anyway.
4505 if (AllTablesFitInRegister)
4506 return true;
4507
4508 // Don't build a table that doesn't fit in-register if it has illegal types.
4509 if (HasIllegalType)
4510 return false;
4511
4512 // The table density should be at least 40%. This is the same criterion as for
4513 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4514 // FIXME: Find the best cut-off.
4515 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004516}
4517
Erik Eckstein0d86c762014-11-27 15:13:14 +00004518/// Try to reuse the switch table index compare. Following pattern:
4519/// \code
4520/// if (idx < tablesize)
4521/// r = table[idx]; // table does not contain default_value
4522/// else
4523/// r = default_value;
4524/// if (r != default_value)
4525/// ...
4526/// \endcode
4527/// Is optimized to:
4528/// \code
4529/// cond = idx < tablesize;
4530/// if (cond)
4531/// r = table[idx];
4532/// else
4533/// r = default_value;
4534/// if (cond)
4535/// ...
4536/// \endcode
4537/// Jump threading will then eliminate the second if(cond).
4538static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4539 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4540 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4541
4542 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4543 if (!CmpInst)
4544 return;
4545
4546 // We require that the compare is in the same block as the phi so that jump
4547 // threading can do its work afterwards.
4548 if (CmpInst->getParent() != PhiBlock)
4549 return;
4550
4551 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4552 if (!CmpOp1)
4553 return;
4554
4555 Value *RangeCmp = RangeCheckBranch->getCondition();
4556 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4557 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4558
4559 // Check if the compare with the default value is constant true or false.
4560 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4561 DefaultValue, CmpOp1, true);
4562 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4563 return;
4564
4565 // Check if the compare with the case values is distinct from the default
4566 // compare result.
4567 for (auto ValuePair : Values) {
4568 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4569 ValuePair.second, CmpOp1, true);
4570 if (!CaseConst || CaseConst == DefaultConst)
4571 return;
4572 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4573 "Expect true or false as compare result.");
4574 }
James Molloy4de84dd2015-11-04 15:28:04 +00004575
Erik Eckstein0d86c762014-11-27 15:13:14 +00004576 // Check if the branch instruction dominates the phi node. It's a simple
4577 // dominance check, but sufficient for our needs.
4578 // Although this check is invariant in the calling loops, it's better to do it
4579 // at this late stage. Practically we do it at most once for a switch.
4580 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4581 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4582 BasicBlock *Pred = *PI;
4583 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4584 return;
4585 }
4586
4587 if (DefaultConst == FalseConst) {
4588 // The compare yields the same result. We can replace it.
4589 CmpInst->replaceAllUsesWith(RangeCmp);
4590 ++NumTableCmpReuses;
4591 } else {
4592 // The compare yields the same result, just inverted. We can replace it.
4593 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4594 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4595 RangeCheckBranch);
4596 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4597 ++NumTableCmpReuses;
4598 }
4599}
4600
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004601/// If the switch is only used to initialize one or more phi nodes in a common
4602/// successor block with different constant values, replace the switch with
4603/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004604static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4605 const DataLayout &DL,
4606 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004607 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004608
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004609 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004610 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004611 return false;
4612
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004613 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4614 // split off a dense part and build a lookup table for that.
4615
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004616 // FIXME: This creates arrays of GEPs to constant strings, which means each
4617 // GEP needs a runtime relocation in PIC code. We should just build one big
4618 // string and lookup indices into that.
4619
Hans Wennborg4744ac12014-01-15 05:00:27 +00004620 // Ignore switches with less than three cases. Lookup tables will not make them
4621 // faster, so we don't analyze them.
4622 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004623 return false;
4624
4625 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00004626 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004627 assert(SI->case_begin() != SI->case_end());
4628 SwitchInst::CaseIt CI = SI->case_begin();
4629 ConstantInt *MinCaseVal = CI.getCaseValue();
4630 ConstantInt *MaxCaseVal = CI.getCaseValue();
4631
Craig Topperf40110f2014-04-25 05:29:35 +00004632 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004633 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004634 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4635 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4636 SmallDenseMap<PHINode*, Type*> ResultTypes;
4637 SmallVector<PHINode*, 4> PHIs;
4638
4639 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4640 ConstantInt *CaseVal = CI.getCaseValue();
4641 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4642 MinCaseVal = CaseVal;
4643 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4644 MaxCaseVal = CaseVal;
4645
4646 // Resulting value at phi nodes for this case value.
4647 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4648 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004649 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004650 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004651 return false;
4652
4653 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004654 for (const auto &I : Results) {
4655 PHINode *PHI = I.first;
4656 Constant *Value = I.second;
4657 if (!ResultLists.count(PHI))
4658 PHIs.push_back(PHI);
4659 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004660 }
4661 }
4662
Hans Wennborgac114a32014-01-12 00:44:41 +00004663 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004664 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004665 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4666 }
4667
4668 uint64_t NumResults = ResultLists[PHIs[0]].size();
4669 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4670 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4671 bool TableHasHoles = (NumResults < TableSize);
4672
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004673 // If the table has holes, we need a constant result for the default case
4674 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004675 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00004676 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004677 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00004678
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004679 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4680 if (NeedMask) {
4681 // As an extra penalty for the validity test we require more cases.
4682 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4683 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004684 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004685 return false;
4686 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004687
Hans Wennborga6a11a92014-11-18 02:37:11 +00004688 for (const auto &I : DefaultResultsList) {
4689 PHINode *PHI = I.first;
4690 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004691 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004692 }
4693
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004694 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004695 return false;
4696
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004697 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004698 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004699 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4700 "switch.lookup",
4701 CommonDest->getParent(),
4702 CommonDest);
4703
Michael Gottesmanc024f322013-10-20 07:04:37 +00004704 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004705 Builder.SetInsertPoint(SI);
4706 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4707 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004708
4709 // Compute the maximum table size representable by the integer type we are
4710 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004711 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004712 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004713 assert(MaxTableSize >= TableSize &&
4714 "It is impossible for a switch to have more entries than the max "
4715 "representable value of its input integer type's size.");
4716
Hans Wennborgb64cb272015-01-26 19:52:34 +00004717 // If the default destination is unreachable, or if the lookup table covers
4718 // all values of the conditional variable, branch directly to the lookup table
4719 // BB. Otherwise, check that the condition is within the case range.
4720 const bool DefaultIsReachable =
4721 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4722 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004723 BranchInst *RangeCheckBranch = nullptr;
4724
Hans Wennborgb64cb272015-01-26 19:52:34 +00004725 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00004726 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00004727 // Note: We call removeProdecessor later since we need to be able to get the
4728 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00004729 } else {
4730 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004731 MinCaseVal->getType(), TableSize));
Erik Eckstein0d86c762014-11-27 15:13:14 +00004732 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00004733 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004734
4735 // Populate the BB that does the lookups.
4736 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004737
4738 if (NeedMask) {
4739 // Before doing the lookup we do the hole check.
4740 // The LookupBB is therefore re-purposed to do the hole check
4741 // and we create a new LookupBB.
4742 BasicBlock *MaskBB = LookupBB;
4743 MaskBB->setName("switch.hole_check");
4744 LookupBB = BasicBlock::Create(Mod.getContext(),
4745 "switch.lookup",
4746 CommonDest->getParent(),
4747 CommonDest);
4748
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004749 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4750 // unnecessary illegal types.
4751 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4752 APInt MaskInt(TableSizePowOf2, 0);
4753 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004754 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004755 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4756 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4757 uint64_t Idx = (ResultList[I].first->getValue() -
4758 MinCaseVal->getValue()).getLimitedValue();
4759 MaskInt |= One << Idx;
4760 }
4761 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4762
4763 // Get the TableIndex'th bit of the bitmask.
4764 // If this bit is 0 (meaning hole) jump to the default destination,
4765 // else continue with table lookup.
4766 IntegerType *MapTy = TableMask->getType();
4767 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4768 "switch.maskindex");
4769 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4770 "switch.shifted");
4771 Value *LoBit = Builder.CreateTrunc(Shifted,
4772 Type::getInt1Ty(Mod.getContext()),
4773 "switch.lobit");
4774 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4775
4776 Builder.SetInsertPoint(LookupBB);
4777 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4778 }
4779
Hans Wennborg86ac6302015-04-24 20:57:56 +00004780 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4781 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4782 // do not delete PHINodes here.
4783 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4784 /*DontDeleteUselessPHIs=*/true);
4785 }
4786
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004787 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004788 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4789 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004790 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004791
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004792 // If using a bitmask, use any value to fill the lookup table holes.
4793 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004794 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004795
Manman Ren4d189fb2014-07-24 21:13:20 +00004796 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004797
Hans Wennborgf744fa92012-09-19 14:24:21 +00004798 // If the result is used to return immediately from the function, we want to
4799 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004800 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4801 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004802 Builder.CreateRet(Result);
4803 ReturnedEarly = true;
4804 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004805 }
4806
Erik Eckstein0d86c762014-11-27 15:13:14 +00004807 // Do a small peephole optimization: re-use the switch table compare if
4808 // possible.
4809 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4810 BasicBlock *PhiBlock = PHI->getParent();
4811 // Search for compare instructions which use the phi.
4812 for (auto *User : PHI->users()) {
4813 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4814 }
4815 }
4816
Hans Wennborgf744fa92012-09-19 14:24:21 +00004817 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004818 }
4819
4820 if (!ReturnedEarly)
4821 Builder.CreateBr(CommonDest);
4822
4823 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004824 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004825 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004826
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004827 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004828 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004829 Succ->removePredecessor(SI->getParent());
4830 }
4831 SI->eraseFromParent();
4832
4833 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004834 if (NeedMask)
4835 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004836 return true;
4837}
4838
Devang Patela7ec47d2011-05-18 20:35:38 +00004839bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004840 BasicBlock *BB = SI->getParent();
4841
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004842 if (isValueEqualityComparison(SI)) {
4843 // If we only have one predecessor, and if it is a branch on this value,
4844 // see if that predecessor totally determines the outcome of this switch.
4845 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4846 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004847 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004848
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004849 Value *Cond = SI->getCondition();
4850 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4851 if (SimplifySwitchOnSelect(SI, Select))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004852 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004853
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004854 // If the block only contains the switch, see if we can fold the block
4855 // away into any preds.
4856 BasicBlock::iterator BBI = BB->begin();
4857 // Ignore dbg intrinsics.
4858 while (isa<DbgInfoIntrinsic>(BBI))
4859 ++BBI;
4860 if (SI == &*BBI)
4861 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004862 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004863 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004864
4865 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004866 if (TurnSwitchRangeIntoICmp(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004867 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004868
4869 // Remove unreachable cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004870 if (EliminateDeadSwitchCases(SI, AC, DL))
4871 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004872
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004873 if (SwitchToSelect(SI, Builder, AC, DL))
4874 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004875
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004876 if (ForwardSwitchConditionToPHI(SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004877 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004878
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004879 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4880 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004881
Chris Lattner25c3af32010-12-13 06:25:44 +00004882 return false;
4883}
4884
4885bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4886 BasicBlock *BB = IBI->getParent();
4887 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004888
Chris Lattner25c3af32010-12-13 06:25:44 +00004889 // Eliminate redundant destinations.
4890 SmallPtrSet<Value *, 8> Succs;
4891 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4892 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004893 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004894 Dest->removePredecessor(BB);
4895 IBI->removeDestination(i);
4896 --i; --e;
4897 Changed = true;
4898 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004899 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004900
4901 if (IBI->getNumDestinations() == 0) {
4902 // If the indirectbr has no successors, change it to unreachable.
4903 new UnreachableInst(IBI->getContext(), IBI);
4904 EraseTerminatorInstAndDCECond(IBI);
4905 return true;
4906 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004907
Chris Lattner25c3af32010-12-13 06:25:44 +00004908 if (IBI->getNumDestinations() == 1) {
4909 // If the indirectbr has one successor, change it to a direct branch.
4910 BranchInst::Create(IBI->getDestination(0), IBI);
4911 EraseTerminatorInstAndDCECond(IBI);
4912 return true;
4913 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004914
Chris Lattner25c3af32010-12-13 06:25:44 +00004915 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4916 if (SimplifyIndirectBrOnSelect(IBI, SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004917 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004918 }
4919 return Changed;
4920}
4921
Philip Reames2b969d72015-03-24 22:28:45 +00004922/// Given an block with only a single landing pad and a unconditional branch
4923/// try to find another basic block which this one can be merged with. This
4924/// handles cases where we have multiple invokes with unique landing pads, but
4925/// a shared handler.
4926///
4927/// We specifically choose to not worry about merging non-empty blocks
4928/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4929/// practice, the optimizer produces empty landing pad blocks quite frequently
4930/// when dealing with exception dense code. (see: instcombine, gvn, if-else
4931/// sinking in this file)
4932///
4933/// This is primarily a code size optimization. We need to avoid performing
4934/// any transform which might inhibit optimization (such as our ability to
4935/// specialize a particular handler via tail commoning). We do this by not
4936/// merging any blocks which require us to introduce a phi. Since the same
4937/// values are flowing through both blocks, we don't loose any ability to
4938/// specialize. If anything, we make such specialization more likely.
4939///
4940/// TODO - This transformation could remove entries from a phi in the target
4941/// block when the inputs in the phi are the same for the two blocks being
4942/// merged. In some cases, this could result in removal of the PHI entirely.
4943static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
4944 BasicBlock *BB) {
4945 auto Succ = BB->getUniqueSuccessor();
4946 assert(Succ);
4947 // If there's a phi in the successor block, we'd likely have to introduce
4948 // a phi into the merged landing pad block.
4949 if (isa<PHINode>(*Succ->begin()))
4950 return false;
4951
4952 for (BasicBlock *OtherPred : predecessors(Succ)) {
4953 if (BB == OtherPred)
4954 continue;
4955 BasicBlock::iterator I = OtherPred->begin();
4956 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
4957 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
4958 continue;
4959 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4960 BranchInst *BI2 = dyn_cast<BranchInst>(I);
4961 if (!BI2 || !BI2->isIdenticalTo(BI))
4962 continue;
4963
4964 // We've found an identical block. Update our predeccessors to take that
4965 // path instead and make ourselves dead.
4966 SmallSet<BasicBlock *, 16> Preds;
4967 Preds.insert(pred_begin(BB), pred_end(BB));
4968 for (BasicBlock *Pred : Preds) {
4969 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
4970 assert(II->getNormalDest() != BB &&
4971 II->getUnwindDest() == BB && "unexpected successor");
4972 II->setUnwindDest(OtherPred);
4973 }
4974
4975 // The debug info in OtherPred doesn't cover the merged control flow that
4976 // used to go through BB. We need to delete it or update it.
4977 for (auto I = OtherPred->begin(), E = OtherPred->end();
4978 I != E;) {
4979 Instruction &Inst = *I; I++;
4980 if (isa<DbgInfoIntrinsic>(Inst))
4981 Inst.eraseFromParent();
4982 }
4983
4984 SmallSet<BasicBlock *, 16> Succs;
4985 Succs.insert(succ_begin(BB), succ_end(BB));
4986 for (BasicBlock *Succ : Succs) {
4987 Succ->removePredecessor(BB);
4988 }
4989
4990 IRBuilder<> Builder(BI);
4991 Builder.CreateUnreachable();
4992 BI->eraseFromParent();
4993 return true;
4994 }
4995 return false;
4996}
4997
Devang Patel767f6932011-05-18 18:28:48 +00004998bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00004999 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005000
Manman Ren93ab6492012-09-20 22:37:36 +00005001 if (SinkCommon && SinkThenElseCodeToEnd(BI))
5002 return true;
5003
Chris Lattner25c3af32010-12-13 06:25:44 +00005004 // If the Terminator is the only non-phi instruction, simplify the block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00005005 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00005006 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
5007 TryToSimplifyUncondBranchFromEmptyBlock(BB))
5008 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005009
Chris Lattner25c3af32010-12-13 06:25:44 +00005010 // If the only instruction in the block is a seteq/setne comparison
5011 // against a constant, try to simplify the block.
5012 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5013 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5014 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5015 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005016 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005017 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
5018 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00005019 return true;
5020 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005021
Philip Reames2b969d72015-03-24 22:28:45 +00005022 // See if we can merge an empty landing pad block with another which is
5023 // equivalent.
5024 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
5025 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
5026 if (I->isTerminator() &&
5027 TryToMergeLandingPad(LPad, BI, BB))
5028 return true;
5029 }
5030
Manman Rend33f4ef2012-06-13 05:43:29 +00005031 // If this basic block is ONLY a compare and a branch, and if a predecessor
5032 // branches to us and our successor, fold the comparison into the
5033 // predecessor and use logical operations to update the incoming value
5034 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005035 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5036 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005037 return false;
5038}
5039
James Molloy4de84dd2015-11-04 15:28:04 +00005040static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5041 BasicBlock *PredPred = nullptr;
5042 for (auto *P : predecessors(BB)) {
5043 BasicBlock *PPred = P->getSinglePredecessor();
5044 if (!PPred || (PredPred && PredPred != PPred))
5045 return nullptr;
5046 PredPred = PPred;
5047 }
5048 return PredPred;
5049}
Chris Lattner25c3af32010-12-13 06:25:44 +00005050
Devang Patela7ec47d2011-05-18 20:35:38 +00005051bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005052 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005053
Chris Lattner25c3af32010-12-13 06:25:44 +00005054 // Conditional branch
5055 if (isValueEqualityComparison(BI)) {
5056 // If we only have one predecessor, and if it is a branch on this value,
5057 // see if that predecessor totally determines the outcome of this
5058 // switch.
5059 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00005060 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005061 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005062
Chris Lattner25c3af32010-12-13 06:25:44 +00005063 // This block must be empty, except for the setcond inst, if it exists.
5064 // Ignore dbg intrinsics.
5065 BasicBlock::iterator I = BB->begin();
5066 // Ignore dbg intrinsics.
5067 while (isa<DbgInfoIntrinsic>(I))
5068 ++I;
5069 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00005070 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005071 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005072 } else if (&*I == cast<Instruction>(BI->getCondition())){
5073 ++I;
5074 // Ignore dbg intrinsics.
5075 while (isa<DbgInfoIntrinsic>(I))
5076 ++I;
Devang Patel58380552011-05-18 20:53:17 +00005077 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005078 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005079 }
5080 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005081
Chris Lattner25c3af32010-12-13 06:25:44 +00005082 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005083 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00005084 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005085
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00005086 // If this basic block is ONLY a compare and a branch, and if a predecessor
5087 // branches to us and one of our successors, fold the comparison into the
5088 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005089 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5090 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005091
Chris Lattner25c3af32010-12-13 06:25:44 +00005092 // We have a conditional branch to two blocks that are only reachable
5093 // from BI. We know that the condbr dominates the two blocks, so see if
5094 // there is any identical code in the "then" and "else" blocks. If so, we
5095 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00005096 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5097 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005098 if (HoistThenElseCodeToIf(BI, TTI))
5099 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005100 } else {
5101 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005102 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00005103 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5104 if (Succ0TI->getNumSuccessors() == 1 &&
5105 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005106 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
5107 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005108 }
Craig Topperf40110f2014-04-25 05:29:35 +00005109 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005110 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005111 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00005112 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5113 if (Succ1TI->getNumSuccessors() == 1 &&
5114 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005115 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
5116 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005117 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005118
Chris Lattner25c3af32010-12-13 06:25:44 +00005119 // If this is a branch on a phi node in the current block, thread control
5120 // through this block if any PHI node entries are constants.
5121 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5122 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005123 if (FoldCondBranchOnPHI(BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005124 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005125
Chris Lattner25c3af32010-12-13 06:25:44 +00005126 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00005127 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5128 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00005129 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00005130 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005131 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005132
James Molloy4de84dd2015-11-04 15:28:04 +00005133 // Look for diamond patterns.
5134 if (MergeCondStores)
5135 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5136 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5137 if (PBI != BI && PBI->isConditional())
5138 if (mergeConditionalStores(PBI, BI))
5139 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5140
Chris Lattner25c3af32010-12-13 06:25:44 +00005141 return false;
5142}
5143
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005144/// Check if passing a value to an instruction will cause undefined behavior.
5145static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5146 Constant *C = dyn_cast<Constant>(V);
5147 if (!C)
5148 return false;
5149
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005150 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005151 return false;
5152
5153 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005154 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00005155 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005156
5157 // Now make sure that there are no instructions in between that can alter
5158 // control flow (eg. calls)
5159 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00005160 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005161 return false;
5162
5163 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5164 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5165 if (GEP->getPointerOperand() == I)
5166 return passingValueIsAlwaysUndefined(V, GEP);
5167
5168 // Look through bitcasts.
5169 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5170 return passingValueIsAlwaysUndefined(V, BC);
5171
Benjamin Kramer0655b782011-08-26 02:25:55 +00005172 // Load from null is undefined.
5173 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005174 if (!LI->isVolatile())
5175 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005176
Benjamin Kramer0655b782011-08-26 02:25:55 +00005177 // Store to null is undefined.
5178 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005179 if (!SI->isVolatile())
5180 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005181 }
5182 return false;
5183}
5184
5185/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005186/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005187static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5188 for (BasicBlock::iterator i = BB->begin();
5189 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5190 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5191 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5192 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5193 IRBuilder<> Builder(T);
5194 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5195 BB->removePredecessor(PHI->getIncomingBlock(i));
5196 // Turn uncoditional branches into unreachables and remove the dead
5197 // destination from conditional branches.
5198 if (BI->isUnconditional())
5199 Builder.CreateUnreachable();
5200 else
5201 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
5202 BI->getSuccessor(0));
5203 BI->eraseFromParent();
5204 return true;
5205 }
5206 // TODO: SwitchInst.
5207 }
5208
5209 return false;
5210}
5211
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005212bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00005213 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00005214
Chris Lattnerd7beca32010-12-14 06:17:25 +00005215 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00005216 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00005217
Dan Gohman4a63fad2010-08-14 00:29:42 +00005218 // Remove basic blocks that have no predecessors (except the entry block)...
5219 // or that just have themself as a predecessor. These are unreachable.
Ramkumar Ramachandra181233b2015-01-13 04:17:47 +00005220 if ((pred_empty(BB) &&
Chris Lattnerd7beca32010-12-14 06:17:25 +00005221 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00005222 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00005223 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00005224 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00005225 return true;
5226 }
5227
Chris Lattner031340a2003-08-17 19:41:53 +00005228 // Check to see if we can constant propagate this terminator instruction
5229 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00005230 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00005231
Dan Gohman1a951062009-10-30 22:39:04 +00005232 // Check for and eliminate duplicate PHI nodes in this block.
5233 Changed |= EliminateDuplicatePHINodes(BB);
5234
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005235 // Check for and remove branches that will always cause undefined behavior.
5236 Changed |= removeUndefIntroducingPredecessor(BB);
5237
Chris Lattner2e3832d2010-12-13 05:10:48 +00005238 // Merge basic blocks into their predecessor if there is only one distinct
5239 // pred, and if there is only one distinct successor of the predecessor, and
5240 // if there are no PHI nodes.
5241 //
5242 if (MergeBlockIntoPredecessor(BB))
5243 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005244
Devang Patel15ad6762011-05-18 18:01:27 +00005245 IRBuilder<> Builder(BB);
5246
Dan Gohman20af5a02008-03-11 21:53:06 +00005247 // If there is a trivial two-entry PHI node in this basic block, and we can
5248 // eliminate it, do so now.
5249 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5250 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005251 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00005252
Devang Patela7ec47d2011-05-18 20:35:38 +00005253 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00005254 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00005255 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00005256 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005257 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00005258 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005259 }
5260 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00005261 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00005262 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
5263 if (SimplifyResume(RI, Builder)) return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00005264 } else if (CleanupReturnInst *RI =
5265 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5266 if (SimplifyCleanupReturn(RI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005267 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00005268 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005269 } else if (UnreachableInst *UI =
5270 dyn_cast<UnreachableInst>(BB->getTerminator())) {
5271 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005272 } else if (IndirectBrInst *IBI =
5273 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
5274 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00005275 }
5276
Chris Lattner031340a2003-08-17 19:41:53 +00005277 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00005278}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005279
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005280/// This function is used to do simplification of a CFG.
5281/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005282/// eliminates unreachable basic blocks, and does other "peephole" optimization
5283/// of the CFG. It returns true if a modification was made.
5284///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005285bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005286 unsigned BonusInstThreshold, AssumptionCache *AC) {
5287 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
5288 BonusInstThreshold, AC).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005289}