blob: 1eff0badb65f5eebc1ea73d5940e34088bd809ee [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
James Molloy4de84dd2015-11-04 15:28:04 +000017#include "llvm/ADT/SetOperations.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000022#include "llvm/Analysis/ConstantFolding.h"
Joseph Tremoulet0d808882016-01-05 02:37:41 +000023#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000027#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000028#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Constants.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DerivedTypes.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/IntrinsicInst.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/MDBuilder.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000040#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000042#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Type.h"
Evan Chengd983eba2011-01-29 04:46:23 +000044#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000045#include "llvm/Support/Debug.h"
46#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000047#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Jingyue Wufc029672014-09-30 22:23:38 +000048#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000049#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000050#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000052using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000053using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000054
Chandler Carruth964daaa2014-04-22 02:55:47 +000055#define DEBUG_TYPE "simplifycfg"
56
James Molloy1b6207e2015-02-13 10:48:30 +000057// Chosen as 2 so as to be cheap, but still to have enough power to fold
58// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
59// To catch this, we need to fold a compare and a select, hence '2' being the
60// minimum reasonable default.
Peter Collingbourne616044a2011-04-29 18:47:38 +000061static cl::opt<unsigned>
James Molloy1b6207e2015-02-13 10:48:30 +000062PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
63 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
Peter Collingbourne616044a2011-04-29 18:47:38 +000064
Evan Chengd983eba2011-01-29 04:46:23 +000065static cl::opt<bool>
66DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
67 cl::desc("Duplicate return instructions into unconditional branches"));
68
Manman Ren93ab6492012-09-20 22:37:36 +000069static cl::opt<bool>
70SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
71 cl::desc("Sink common instructions down to the end block"));
72
Alp Tokercb402912014-01-24 17:20:08 +000073static cl::opt<bool> HoistCondStores(
74 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
75 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000076
James Molloy4de84dd2015-11-04 15:28:04 +000077static cl::opt<bool> MergeCondStores(
78 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
79 cl::desc("Hoist conditional stores even if an unconditional store does not "
80 "precede - hoist multiple conditional stores into a single "
81 "predicated store"));
82
83static cl::opt<bool> MergeCondStoresAggressively(
84 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
85 cl::desc("When merging conditional stores, do so even if the resultant "
86 "basic blocks are unlikely to be if-converted as a result"));
87
David Majnemerfccf5c62016-01-27 02:59:41 +000088static cl::opt<bool> SpeculateOneExpensiveInst(
89 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
90 cl::desc("Allow exactly one expensive instruction to be speculatively "
91 "executed"));
92
Sanjay Patel5264cc72016-01-27 19:22:45 +000093static cl::opt<unsigned> MaxSpeculationDepth(
94 "max-speculation-depth", cl::Hidden, cl::init(10),
95 cl::desc("Limit maximum recursion depth when calculating costs of "
96 "speculatively executed instructions"));
97
Hans Wennborg39583b82012-09-26 09:44:49 +000098STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000099STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +0000100STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +0000101STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +0000102STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Manman Ren93ab6492012-09-20 22:37:36 +0000103STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +0000104STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +0000105
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000106namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000107 // The first field contains the value that the switch produces when a certain
Sanjay Patel9361d352015-09-10 16:31:19 +0000108 // case group is selected, and the second field is a vector containing the
109 // cases composing the case group.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000110 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
111 SwitchCaseResultVectorTy;
112 // The first field contains the phi node that generates a result of the switch
Sanjay Patel9361d352015-09-10 16:31:19 +0000113 // and the second field contains the value generated for a certain case in the
114 // switch for that PHI.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000115 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
116
Eric Christopherb65acc62012-07-02 23:22:21 +0000117 /// ValueEqualityComparisonCase - Represents a case of a switch.
118 struct ValueEqualityComparisonCase {
119 ConstantInt *Value;
120 BasicBlock *Dest;
121
122 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
123 : Value(Value), Dest(Dest) {}
124
125 bool operator<(ValueEqualityComparisonCase RHS) const {
126 // Comparing pointers is ok as we only rely on the order for uniquing.
127 return Value < RHS.Value;
128 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000129
130 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000131 };
132
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000133class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000134 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000135 const DataLayout &DL;
Jingyue Wufc029672014-09-30 22:23:38 +0000136 unsigned BonusInstThreshold;
Chandler Carruth66b31302015-01-04 12:03:27 +0000137 AssumptionCache *AC;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000138 Value *isValueEqualityComparison(TerminatorInst *TI);
139 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000140 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000141 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000142 BasicBlock *Pred,
143 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000144 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
145 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000146
Devang Pateldd14e0f2011-05-18 21:33:11 +0000147 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000148 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chen Li1689c2f2016-01-10 05:48:01 +0000149 bool SimplifySingleResume(ResumeInst *RI);
150 bool SimplifyCommonResume(ResumeInst *RI);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000151 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000152 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000153 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000154 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000155 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000156 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000157
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000158public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000159 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
160 unsigned BonusInstThreshold, AssumptionCache *AC)
161 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000162 bool run(BasicBlock *BB);
163};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000164}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000165
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000166/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000167/// terminator instructions together.
Chris Lattner76dc2042005-08-03 00:19:45 +0000168static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
169 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000170
Chris Lattner76dc2042005-08-03 00:19:45 +0000171 // It is not safe to merge these two switch instructions if they have a common
172 // successor, and if that successor has a PHI node, and if *that* PHI node has
173 // conflicting incoming values from the two switch blocks.
174 BasicBlock *SI1BB = SI1->getParent();
175 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000176 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000177
Sanjay Patel5781d842016-03-12 16:52:17 +0000178 for (BasicBlock *Succ : successors(SI2BB))
179 if (SI1Succs.count(Succ))
180 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000181 PHINode *PN = cast<PHINode>(BBI);
182 if (PN->getIncomingValueForBlock(SI1BB) !=
183 PN->getIncomingValueForBlock(SI2BB))
184 return false;
185 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000186
Chris Lattner76dc2042005-08-03 00:19:45 +0000187 return true;
188}
189
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000190/// Return true if it is safe and profitable to merge these two terminator
191/// instructions together, where SI1 is an unconditional branch. PhiNodes will
192/// store all PHI nodes in common successors.
Manman Rend33f4ef2012-06-13 05:43:29 +0000193static bool isProfitableToFoldUnconditional(BranchInst *SI1,
194 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000195 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000196 SmallVectorImpl<PHINode*> &PhiNodes) {
197 if (SI1 == SI2) return false; // Can't merge with self!
198 assert(SI1->isUnconditional() && SI2->isConditional());
199
200 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000201 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000202 // 1> We have a constant incoming value for the conditional branch;
203 // 2> We have "Cond" as the incoming value for the unconditional branch;
204 // 3> SI2->getCondition() and Cond have same operands.
205 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
206 if (!Ci2) return false;
207 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
208 Cond->getOperand(1) == Ci2->getOperand(1)) &&
209 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
210 Cond->getOperand(1) == Ci2->getOperand(0)))
211 return false;
212
213 BasicBlock *SI1BB = SI1->getParent();
214 BasicBlock *SI2BB = SI2->getParent();
215 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Sanjay Patel5781d842016-03-12 16:52:17 +0000216 for (BasicBlock *Succ : successors(SI2BB))
217 if (SI1Succs.count(Succ))
218 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
Manman Rend33f4ef2012-06-13 05:43:29 +0000219 PHINode *PN = cast<PHINode>(BBI);
220 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000221 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000222 return false;
223 PhiNodes.push_back(PN);
224 }
225 return true;
226}
227
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000228/// Update PHI nodes in Succ to indicate that there will now be entries in it
229/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
230/// will be the same as those coming in from ExistPred, an existing predecessor
231/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000232static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
233 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000234 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000235
Chris Lattner80b03a12008-07-13 22:23:11 +0000236 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +0000237 for (BasicBlock::iterator I = Succ->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
Chris Lattner80b03a12008-07-13 22:23:11 +0000238 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000239}
240
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000241/// Compute an abstract "cost" of speculating the given instruction,
242/// which is assumed to be safe to speculate. TCC_Free means cheap,
243/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000244/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000245static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000246 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000247 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000248 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000249 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000250}
Sanjay Patelf9b77632015-09-15 15:24:42 +0000251
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000252/// If we have a merge point of an "if condition" as accepted above,
253/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000254/// don't handle the true generality of domination here, just a special case
255/// which works well enough for us.
256///
257/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000258/// see if V (which must be an instruction) and its recursive operands
259/// that do not dominate BB have a combined cost lower than CostRemaining and
260/// are non-trapping. If both are true, the instruction is inserted into the
261/// set and true is returned.
262///
263/// The cost for most non-trapping instructions is defined as 1 except for
264/// Select whose cost is 2.
265///
266/// After this function returns, CostRemaining is decreased by the cost of
267/// V plus its non-dominating operands. If that cost is greater than
268/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000269static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000270 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000271 unsigned &CostRemaining,
David Majnemerfccf5c62016-01-27 02:59:41 +0000272 const TargetTransformInfo &TTI,
273 unsigned Depth = 0) {
Sanjay Patel5264cc72016-01-27 19:22:45 +0000274 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
275 // so limit the recursion depth.
276 // TODO: While this recursion limit does prevent pathological behavior, it
277 // would be better to track visited instructions to avoid cycles.
278 if (Depth == MaxSpeculationDepth)
279 return false;
280
Chris Lattner0aa56562004-04-09 22:50:22 +0000281 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000282 if (!I) {
283 // Non-instructions all dominate instructions, but not all constantexprs
284 // can be executed unconditionally.
285 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
286 if (C->canTrap())
287 return false;
288 return true;
289 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000290 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000291
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000292 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000293 // the bottom of this block.
294 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000295
Chris Lattner0aa56562004-04-09 22:50:22 +0000296 // If this instruction is defined in a block that contains an unconditional
297 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000298 // statement". If not, it definitely dominates the region.
299 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000300 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000301 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000302
Chris Lattner9ac168d2010-12-14 07:41:39 +0000303 // If we aren't allowing aggressive promotion anymore, then don't consider
304 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000305 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000306
Peter Collingbournee3511e12011-04-29 18:47:31 +0000307 // If we have seen this instruction before, don't count it again.
308 if (AggressiveInsts->count(I)) return true;
309
Chris Lattner9ac168d2010-12-14 07:41:39 +0000310 // Okay, it looks like the instruction IS in the "condition". Check to
311 // see if it's a cheap instruction to unconditionally compute, and if it
312 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000313 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000314 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000315
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000316 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000317
David Majnemerfccf5c62016-01-27 02:59:41 +0000318 // Allow exactly one instruction to be speculated regardless of its cost
319 // (as long as it is safe to do so).
320 // This is intended to flatten the CFG even if the instruction is a division
321 // or other expensive operation. The speculation of an expensive instruction
322 // is expected to be undone in CodeGenPrepare if the speculation has not
323 // enabled further IR optimizations.
324 if (Cost > CostRemaining &&
325 (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0))
Peter Collingbournee3511e12011-04-29 18:47:31 +0000326 return false;
327
David Majnemerfccf5c62016-01-27 02:59:41 +0000328 // Avoid unsigned wrap.
329 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000330
331 // Okay, we can only really hoist these out if their operands do
332 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000333 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
David Majnemerfccf5c62016-01-27 02:59:41 +0000334 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
335 Depth + 1))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000336 return false;
337 // Okay, it's safe to do this! Remember this instruction.
338 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000339 return true;
340}
Chris Lattner466a0492002-05-21 20:50:24 +0000341
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000342/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000343/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000344static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000345 // Normal constant int.
346 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000347 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000348 return CI;
349
350 // This is some kind of pointer constant. Turn it into a pointer-sized
351 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000352 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000353
354 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
355 if (isa<ConstantPointerNull>(V))
356 return ConstantInt::get(PtrTy, 0);
357
358 // IntToPtr const int.
359 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
360 if (CE->getOpcode() == Instruction::IntToPtr)
361 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
362 // The constant is very likely to have the right type already.
363 if (CI->getType() == PtrTy)
364 return CI;
365 else
366 return cast<ConstantInt>
367 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
368 }
Craig Topperf40110f2014-04-25 05:29:35 +0000369 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000370}
371
Mehdi Aminiffd01002014-11-20 22:40:25 +0000372namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000373
Mehdi Aminiffd01002014-11-20 22:40:25 +0000374/// Given a chain of or (||) or and (&&) comparison of a value against a
375/// constant, this will try to recover the information required for a switch
376/// structure.
377/// It will depth-first traverse the chain of comparison, seeking for patterns
378/// like %a == 12 or %a < 4 and combine them to produce a set of integer
379/// representing the different cases for the switch.
380/// Note that if the chain is composed of '||' it will build the set of elements
381/// that matches the comparisons (i.e. any of this value validate the chain)
382/// while for a chain of '&&' it will build the set elements that make the test
383/// fail.
384struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000385 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000386 Value *CompValue; /// Value found for the switch comparison
387 Value *Extra; /// Extra clause to be checked before the switch
388 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
389 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000390
Mehdi Aminiffd01002014-11-20 22:40:25 +0000391 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000392 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
393 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
394 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000395 }
396
Mehdi Aminiffd01002014-11-20 22:40:25 +0000397 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000398 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000399 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000400 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000401
Mehdi Aminiffd01002014-11-20 22:40:25 +0000402private:
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000403
Mehdi Aminiffd01002014-11-20 22:40:25 +0000404 /// Try to set the current value used for the comparison, it succeeds only if
405 /// it wasn't set before or if the new value is the same as the old one
406 bool setValueOnce(Value *NewVal) {
Sanjay Patel2e002772016-03-12 18:05:53 +0000407 if (CompValue && CompValue != NewVal) return false;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000408 CompValue = NewVal;
409 return (CompValue != nullptr);
410 }
411
412 /// Try to match Instruction "I" as a comparison against a constant and
413 /// populates the array Vals with the set of values that match (or do not
414 /// match depending on isEQ).
415 /// Return false on failure. On success, the Value the comparison matched
416 /// against is placed in CompValue.
417 /// If CompValue is already set, the function is expected to fail if a match
418 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000419 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000420 // If this is an icmp against a constant, handle this as one of the cases.
421 ICmpInst *ICI;
422 ConstantInt *C;
423 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
424 (C = GetConstantInt(I->getOperand(1), DL)))) {
425 return false;
426 }
427
428 Value *RHSVal;
429 ConstantInt *RHSC;
430
431 // Pattern match a special case
David Majnemerc761afd2016-01-27 02:43:28 +0000432 // (x & ~2^z) == y --> x == y || x == y|2^z
Mehdi Aminiffd01002014-11-20 22:40:25 +0000433 // This undoes a transformation done by instcombine to fuse 2 compares.
434 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
435 if (match(ICI->getOperand(0),
436 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
437 APInt Not = ~RHSC->getValue();
David Majnemerc761afd2016-01-27 02:43:28 +0000438 if (Not.isPowerOf2() && C->getValue().isPowerOf2() &&
439 Not != C->getValue()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000440 // If we already have a value for the switch, it has to match!
441 if(!setValueOnce(RHSVal))
442 return false;
443
444 Vals.push_back(C);
445 Vals.push_back(ConstantInt::get(C->getContext(),
446 C->getValue() | Not));
447 UsedICmps++;
448 return true;
449 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000450 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000451
452 // If we already have a value for the switch, it has to match!
453 if(!setValueOnce(ICI->getOperand(0)))
454 return false;
455
456 UsedICmps++;
457 Vals.push_back(C);
458 return ICI->getOperand(0);
459 }
460
461 // 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 +0000462 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
463 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000464
465 // Shift the range if the compare is fed by an add. This is the range
466 // compare idiom as emitted by instcombine.
467 Value *CandidateVal = I->getOperand(0);
468 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
469 Span = Span.subtract(RHSC->getValue());
470 CandidateVal = RHSVal;
471 }
472
473 // If this is an and/!= check, then we are looking to build the set of
474 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
475 // x != 0 && x != 1.
476 if (!isEQ)
477 Span = Span.inverse();
478
479 // If there are a ton of values, we don't want to make a ginormous switch.
480 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
481 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000482 }
483
484 // If we already have a value for the switch, it has to match!
Mehdi Aminiffd01002014-11-20 22:40:25 +0000485 if(!setValueOnce(CandidateVal))
486 return false;
487
488 // Add all values from the range to the set
489 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
490 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000491
492 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000493 return true;
494
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000495 }
496
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000497 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000498 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
499 /// the value being compared, and stick the list constants into the Vals
500 /// vector.
501 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000502 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000503 Instruction *I = dyn_cast<Instruction>(V);
504 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000505
Mehdi Aminiffd01002014-11-20 22:40:25 +0000506 // Keep a stack (SmallVector for efficiency) for depth-first traversal
507 SmallVector<Value *, 8> DFT;
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000508 SmallPtrSet<Value *, 8> Visited;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000509
Mehdi Aminiffd01002014-11-20 22:40:25 +0000510 // Initialize
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000511 Visited.insert(V);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000512 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000513
Mehdi Aminiffd01002014-11-20 22:40:25 +0000514 while(!DFT.empty()) {
515 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000516
Mehdi Aminiffd01002014-11-20 22:40:25 +0000517 if (Instruction *I = dyn_cast<Instruction>(V)) {
518 // If it is a || (or && depending on isEQ), process the operands.
519 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000520 if (Visited.insert(I->getOperand(1)).second)
521 DFT.push_back(I->getOperand(1));
522 if (Visited.insert(I->getOperand(0)).second)
523 DFT.push_back(I->getOperand(0));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000524 continue;
525 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000526
Mehdi Aminiffd01002014-11-20 22:40:25 +0000527 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000528 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000529 // Match succeed, continue the loop
530 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000531 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000532
Mehdi Aminiffd01002014-11-20 22:40:25 +0000533 // One element of the sequence of || (or &&) could not be match as a
534 // comparison against the same value as the others.
535 // We allow only one "Extra" case to be checked before the switch
536 if (!Extra) {
537 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000538 continue;
539 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000540 // Failed to parse a proper sequence, abort now
541 CompValue = nullptr;
542 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000543 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000544 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000545};
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000546
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000547}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000548
Eli Friedmancb61afb2008-12-16 20:54:32 +0000549static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000550 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000551 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
552 Cond = dyn_cast<Instruction>(SI->getCondition());
553 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
554 if (BI->isConditional())
555 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000556 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
557 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000558 }
559
560 TI->eraseFromParent();
561 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
562}
563
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000564/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000565/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000566Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000567 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000568 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
569 // Do not permit merging of large switch instructions into their
570 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000571 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
572 pred_end(SI->getParent())) <= 128)
573 CV = SI->getCondition();
574 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000575 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000576 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000577 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000578 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000579 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000580
581 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000582 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000583 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
584 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000585 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000586 CV = Ptr;
587 }
588 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000589 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000590}
591
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000592/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000593/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000594BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000595GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000596 std::vector<ValueEqualityComparisonCase>
597 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000598 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000599 Cases.reserve(SI->getNumCases());
600 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
601 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
602 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000603 return SI->getDefaultDest();
604 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000605
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000606 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000607 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000608 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
609 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000610 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000611 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000612 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000613}
614
Eric Christopherb65acc62012-07-02 23:22:21 +0000615
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000616/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000617/// in the list that match the specified block.
618static void EliminateBlockCases(BasicBlock *BB,
619 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000620 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000621}
622
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000623/// Return true if there are any keys in C1 that exist in C2 as well.
Eric Christopherb65acc62012-07-02 23:22:21 +0000624static bool
625ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
626 std::vector<ValueEqualityComparisonCase > &C2) {
627 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
628
629 // Make V1 be smaller than V2.
630 if (V1->size() > V2->size())
631 std::swap(V1, V2);
632
633 if (V1->size() == 0) return false;
634 if (V1->size() == 1) {
635 // Just scan V2.
636 ConstantInt *TheVal = (*V1)[0].Value;
637 for (unsigned i = 0, e = V2->size(); i != e; ++i)
638 if (TheVal == (*V2)[i].Value)
639 return true;
640 }
641
642 // Otherwise, just sort both lists and compare element by element.
643 array_pod_sort(V1->begin(), V1->end());
644 array_pod_sort(V2->begin(), V2->end());
645 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
646 while (i1 != e1 && i2 != e2) {
647 if ((*V1)[i1].Value == (*V2)[i2].Value)
648 return true;
649 if ((*V1)[i1].Value < (*V2)[i2].Value)
650 ++i1;
651 else
652 ++i2;
653 }
654 return false;
655}
656
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000657/// If TI is known to be a terminator instruction and its block is known to
658/// only have a single predecessor block, check to see if that predecessor is
659/// also a value comparison with the same value, and if that comparison
660/// determines the outcome of this comparison. If so, simplify TI. This does a
661/// very limited form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000662bool SimplifyCFGOpt::
663SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000664 BasicBlock *Pred,
665 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000666 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
667 if (!PredVal) return false; // Not a value comparison in predecessor.
668
669 Value *ThisVal = isValueEqualityComparison(TI);
670 assert(ThisVal && "This isn't a value comparison!!");
671 if (ThisVal != PredVal) return false; // Different predicates.
672
Andrew Trick3051aa12012-08-29 21:46:38 +0000673 // TODO: Preserve branch weight metadata, similarly to how
674 // FoldValueComparisonIntoPredecessors preserves it.
675
Chris Lattner1cca9592005-02-24 06:17:52 +0000676 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000677 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000678 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
679 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000680 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000681
Chris Lattner1cca9592005-02-24 06:17:52 +0000682 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000683 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000684 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000685 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000686
687 // If TI's block is the default block from Pred's comparison, potentially
688 // simplify TI based on this knowledge.
689 if (PredDef == TI->getParent()) {
690 // If we are here, we know that the value is none of those cases listed in
691 // PredCases. If there are any cases in ThisCases that are in PredCases, we
692 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000693 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000694 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000695
Chris Lattner4088e2b2010-12-13 01:47:07 +0000696 if (isa<BranchInst>(TI)) {
697 // Okay, one of the successors of this condbr is dead. Convert it to a
698 // uncond br.
699 assert(ThisCases.size() == 1 && "Branch can only have one case!");
700 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000701 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000702 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000703
Chris Lattner4088e2b2010-12-13 01:47:07 +0000704 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000705 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000706
Chris Lattner4088e2b2010-12-13 01:47:07 +0000707 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
708 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000709
Chris Lattner4088e2b2010-12-13 01:47:07 +0000710 EraseTerminatorInstAndDCECond(TI);
711 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000712 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000713
Chris Lattner4088e2b2010-12-13 01:47:07 +0000714 SwitchInst *SI = cast<SwitchInst>(TI);
715 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000716 SmallPtrSet<Constant*, 16> DeadCases;
717 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
718 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000719
David Greene725c7c32010-01-05 01:26:52 +0000720 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000721 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000722
Manman Ren8691e522012-09-14 21:53:06 +0000723 // Collect branch weights into a vector.
724 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000725 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000726 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
727 if (HasWeight)
728 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
729 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000730 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000731 Weights.push_back(CI->getValue().getZExtValue());
732 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000733 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
734 --i;
735 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000736 if (HasWeight) {
737 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
738 Weights.pop_back();
739 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000740 i.getCaseSuccessor()->removePredecessor(TI->getParent());
741 SI->removeCase(i);
742 }
743 }
Manman Ren97c18762012-10-11 22:28:34 +0000744 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000745 SI->setMetadata(LLVMContext::MD_prof,
746 MDBuilder(SI->getParent()->getContext()).
747 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000748
749 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000750 return true;
751 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000752
Chris Lattner4088e2b2010-12-13 01:47:07 +0000753 // Otherwise, TI's block must correspond to some matched value. Find out
754 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000755 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000756 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000757 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
758 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000759 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000760 return false; // Cannot handle multiple values coming to this block.
761 TIV = PredCases[i].Value;
762 }
763 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000764
765 // Okay, we found the one constant that our value can be if we get into TI's
766 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000767 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000768 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
769 if (ThisCases[i].Value == TIV) {
770 TheRealDest = ThisCases[i].Dest;
771 break;
772 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000773
774 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000775 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000776
777 // Remove PHI node entries for dead edges.
778 BasicBlock *CheckEdge = TheRealDest;
Sanjay Patel5781d842016-03-12 16:52:17 +0000779 for (BasicBlock *Succ : successors(TIBB))
780 if (Succ != CheckEdge)
781 Succ->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000782 else
Craig Topperf40110f2014-04-25 05:29:35 +0000783 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000784
785 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000786 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000787 (void) NI;
788
789 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
790 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
791
792 EraseTerminatorInstAndDCECond(TI);
793 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000794}
795
Dale Johannesen7f99d222009-03-12 21:01:11 +0000796namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000797 /// This class implements a stable ordering of constant
Dale Johannesen7f99d222009-03-12 21:01:11 +0000798 /// integers that does not depend on their address. This is important for
799 /// applications that sort ConstantInt's to ensure uniqueness.
800 struct ConstantIntOrdering {
801 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
802 return LHS->getValue().ult(RHS->getValue());
803 }
804 };
805}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000806
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000807static int ConstantIntSortPredicate(ConstantInt *const *P1,
808 ConstantInt *const *P2) {
809 const ConstantInt *LHS = *P1;
810 const ConstantInt *RHS = *P2;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000811 if (LHS == RHS)
Chris Lattnere893e262010-12-15 04:52:41 +0000812 return 0;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000813 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000814}
815
Andrew Trick3051aa12012-08-29 21:46:38 +0000816static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000817 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000818 if (ProfMD && ProfMD->getOperand(0))
819 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
820 return MDS->getString().equals("branch_weights");
821
822 return false;
823}
824
Manman Ren571d9e42012-09-11 17:43:35 +0000825/// Get Weights of a given TerminatorInst, the default weight is at the front
826/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
827/// metadata.
828static void GetBranchWeights(TerminatorInst *TI,
829 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000830 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000831 assert(MD);
832 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000833 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000834 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000835 }
836
Manman Ren571d9e42012-09-11 17:43:35 +0000837 // If TI is a conditional eq, the default case is the false case,
838 // and the corresponding branch-weight data is at index 2. We swap the
839 // default weight to be the first entry.
840 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
841 assert(Weights.size() == 2);
842 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
843 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
844 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000845 }
846}
847
Manman Renf1cb16e2014-01-27 23:39:03 +0000848/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000849static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000850 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
851 if (Max > UINT_MAX) {
852 unsigned Offset = 32 - countLeadingZeros(Max);
853 for (uint64_t &I : Weights)
854 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000855 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000856}
857
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000858/// The specified terminator is a value equality comparison instruction
859/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000860/// See if any of the predecessors of the terminator block are value comparisons
861/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000862bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
863 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000864 BasicBlock *BB = TI->getParent();
865 Value *CV = isValueEqualityComparison(TI); // CondVal
866 assert(CV && "Not a comparison?");
867 bool Changed = false;
868
Chris Lattner6b39cb92008-02-18 07:42:56 +0000869 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000870 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000871 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000872
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000873 // See if the predecessor is a comparison with the same value.
874 TerminatorInst *PTI = Pred->getTerminator();
875 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
876
877 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
878 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000879 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000880 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
881
Eric Christopherb65acc62012-07-02 23:22:21 +0000882 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000883 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
884
885 // Based on whether the default edge from PTI goes to BB or not, fill in
886 // PredCases and PredDefault with the new switch cases we would like to
887 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000888 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000889
Andrew Trick3051aa12012-08-29 21:46:38 +0000890 // Update the branch weight metadata along the way
891 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000892 bool PredHasWeights = HasBranchWeights(PTI);
893 bool SuccHasWeights = HasBranchWeights(TI);
894
Manman Ren5e5049d2012-09-14 19:05:19 +0000895 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000896 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000897 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000898 if (Weights.size() != 1 + PredCases.size())
899 PredHasWeights = SuccHasWeights = false;
900 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000901 // If there are no predecessor weights but there are successor weights,
902 // populate Weights with 1, which will later be scaled to the sum of
903 // successor's weights
904 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000905
Manman Ren571d9e42012-09-11 17:43:35 +0000906 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000907 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000908 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000909 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000910 if (SuccWeights.size() != 1 + BBCases.size())
911 PredHasWeights = SuccHasWeights = false;
912 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000913 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000914
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000915 if (PredDefault == BB) {
916 // If this is the default destination from PTI, only the edges in TI
917 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000918 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
919 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
920 if (PredCases[i].Dest != BB)
921 PTIHandled.insert(PredCases[i].Value);
922 else {
923 // The default destination is BB, we don't need explicit targets.
924 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000925
Manman Ren571d9e42012-09-11 17:43:35 +0000926 if (PredHasWeights || SuccHasWeights) {
927 // Increase weight for the default case.
928 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000929 std::swap(Weights[i+1], Weights.back());
930 Weights.pop_back();
931 }
932
Eric Christopherb65acc62012-07-02 23:22:21 +0000933 PredCases.pop_back();
934 --i; --e;
935 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000936
Eric Christopherb65acc62012-07-02 23:22:21 +0000937 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000938 if (PredDefault != BBDefault) {
939 PredDefault->removePredecessor(Pred);
940 PredDefault = BBDefault;
941 NewSuccessors.push_back(BBDefault);
942 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000943
Manman Ren571d9e42012-09-11 17:43:35 +0000944 unsigned CasesFromPred = Weights.size();
945 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000946 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
947 if (!PTIHandled.count(BBCases[i].Value) &&
948 BBCases[i].Dest != BBDefault) {
949 PredCases.push_back(BBCases[i]);
950 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000951 if (SuccHasWeights || PredHasWeights) {
952 // The default weight is at index 0, so weight for the ith case
953 // should be at index i+1. Scale the cases from successor by
954 // PredDefaultWeight (Weights[0]).
955 Weights.push_back(Weights[0] * SuccWeights[i+1]);
956 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000957 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000958 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000959
Manman Ren571d9e42012-09-11 17:43:35 +0000960 if (SuccHasWeights || PredHasWeights) {
961 ValidTotalSuccWeight += SuccWeights[0];
962 // Scale the cases from predecessor by ValidTotalSuccWeight.
963 for (unsigned i = 1; i < CasesFromPred; ++i)
964 Weights[i] *= ValidTotalSuccWeight;
965 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
966 Weights[0] *= SuccWeights[0];
967 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000968 } else {
969 // If this is not the default destination from PSI, only the edges
970 // in SI that occur in PSI with a destination of BB will be
971 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000972 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000973 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000974 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
975 if (PredCases[i].Dest == BB) {
976 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000977
978 if (PredHasWeights || SuccHasWeights) {
979 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
980 std::swap(Weights[i+1], Weights.back());
981 Weights.pop_back();
982 }
983
Eric Christopherb65acc62012-07-02 23:22:21 +0000984 std::swap(PredCases[i], PredCases.back());
985 PredCases.pop_back();
986 --i; --e;
987 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000988
989 // Okay, now we know which constants were sent to BB from the
990 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000991 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
992 if (PTIHandled.count(BBCases[i].Value)) {
993 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000994 if (PredHasWeights || SuccHasWeights)
995 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000996 PredCases.push_back(BBCases[i]);
997 NewSuccessors.push_back(BBCases[i].Dest);
998 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
999 }
1000
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001001 // If there are any constants vectored to BB that TI doesn't handle,
1002 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001003 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +00001004 PTIHandled.begin(),
1005 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +00001006 if (PredHasWeights || SuccHasWeights)
1007 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +00001008 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001009 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +00001010 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001011 }
1012
1013 // Okay, at this point, we know which new successor Pred will get. Make
1014 // sure we update the number of entries in the PHI nodes for these
1015 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +00001016 for (BasicBlock *NewSuccessor : NewSuccessors)
1017 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001018
Devang Patel58380552011-05-18 20:53:17 +00001019 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001020 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +00001021 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001022 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +00001023 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001024 }
1025
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001026 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +00001027 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
1028 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001029 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +00001030 for (ValueEqualityComparisonCase &V : PredCases)
1031 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001032
Andrew Trick3051aa12012-08-29 21:46:38 +00001033 if (PredHasWeights || SuccHasWeights) {
1034 // Halve the weights if any of them cannot fit in an uint32_t
1035 FitWeights(Weights);
1036
1037 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1038
1039 NewSI->setMetadata(LLVMContext::MD_prof,
1040 MDBuilder(BB->getContext()).
1041 createBranchWeights(MDWeights));
1042 }
1043
Eli Friedmancb61afb2008-12-16 20:54:32 +00001044 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001045
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001046 // Okay, last check. If BB is still a successor of PSI, then we must
1047 // have an infinite loop case. If so, add an infinitely looping block
1048 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001049 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001050 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1051 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001052 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001053 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001054 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001055 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1056 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001057 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001058 }
1059 NewSI->setSuccessor(i, InfLoopBlock);
1060 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001061
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001062 Changed = true;
1063 }
1064 }
1065 return Changed;
1066}
1067
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001068// If we would need to insert a select that uses the value of this invoke
1069// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1070// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001071static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1072 Instruction *I1, Instruction *I2) {
Sanjay Patel5781d842016-03-12 16:52:17 +00001073 for (BasicBlock *Succ : successors(BB1)) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001074 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001075 for (BasicBlock::iterator BBI = Succ->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001076 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1077 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1078 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1079 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1080 return false;
1081 }
1082 }
1083 }
1084 return true;
1085}
1086
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001087static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1088
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001089/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1090/// in the two blocks up into the branch block. The caller of this function
1091/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001092static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001093 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001094 // This does very trivial matching, with limited scanning, to find identical
1095 // instructions in the two blocks. In particular, we don't want to get into
1096 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1097 // such, we currently just scan for obviously identical instructions in an
1098 // identical order.
1099 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1100 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1101
Devang Patelf10e2872009-02-04 00:03:08 +00001102 BasicBlock::iterator BB1_Itr = BB1->begin();
1103 BasicBlock::iterator BB2_Itr = BB2->begin();
1104
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001105 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001106 // Skip debug info if it is not identical.
1107 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1108 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1109 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1110 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001111 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001112 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001113 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001114 }
Devang Patele48ddf82011-04-07 00:30:15 +00001115 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001116 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001117 return false;
1118
Chris Lattner389cfac2004-11-30 00:29:14 +00001119 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001120
David Majnemerc82f27a2013-06-03 20:43:12 +00001121 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001122 do {
1123 // If we are hoisting the terminator instruction, don't move one (making a
1124 // broken BB), instead clone it, and remove BI.
1125 if (isa<TerminatorInst>(I1))
1126 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001127
Chad Rosier54390052015-02-23 19:15:16 +00001128 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1129 return Changed;
1130
Chris Lattner389cfac2004-11-30 00:29:14 +00001131 // For a normal instruction, we just move one to right before the branch,
1132 // then replace all uses of the other with the first. Finally, we remove
1133 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001134 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001135 if (!I2->use_empty())
1136 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001137 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001138 unsigned KnownIDs[] = {
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001139 LLVMContext::MD_tbaa, LLVMContext::MD_range,
1140 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001141 LLVMContext::MD_nonnull, LLVMContext::MD_invariant_group,
1142 LLVMContext::MD_align, LLVMContext::MD_dereferenceable,
1143 LLVMContext::MD_dereferenceable_or_null};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001144 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001145 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001146 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001147
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001148 I1 = &*BB1_Itr++;
1149 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001150 // Skip debug info if it is not identical.
1151 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1152 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1153 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1154 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001155 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001156 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001157 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001158 }
Devang Patele48ddf82011-04-07 00:30:15 +00001159 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001160
1161 return true;
1162
1163HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001164 // It may not be possible to hoist an invoke.
1165 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001166 return Changed;
1167
Sanjay Patel5781d842016-03-12 16:52:17 +00001168 for (BasicBlock *Succ : successors(BB1)) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001169 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001170 for (BasicBlock::iterator BBI = Succ->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001171 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1172 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1173 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1174 if (BB1V == BB2V)
1175 continue;
1176
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001177 // Check for passingValueIsAlwaysUndefined here because we would rather
1178 // eliminate undefined control flow then converting it to a select.
1179 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1180 passingValueIsAlwaysUndefined(BB2V, PN))
1181 return Changed;
1182
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001183 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001184 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001185 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001186 return Changed;
1187 }
1188 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001189
Chris Lattner389cfac2004-11-30 00:29:14 +00001190 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001191 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001192 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001193 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001194 I1->replaceAllUsesWith(NT);
1195 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001196 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001197 }
1198
Eric Christopher35abd052016-03-12 01:47:22 +00001199 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001200 // Hoisting one of the terminators from our successor is a great thing.
1201 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1202 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1203 // nodes, so we insert select instruction to compute the final result.
1204 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Sanjay Patel5781d842016-03-12 16:52:17 +00001205 for (BasicBlock *Succ : successors(BB1)) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001206 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001207 for (BasicBlock::iterator BBI = Succ->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001208 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001209 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1210 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001211 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001212
Chris Lattner4088e2b2010-12-13 01:47:07 +00001213 // These values do not agree. Insert a select instruction before NT
1214 // that determines the right value.
1215 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001216 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001217 SI = cast<SelectInst>
1218 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
Sanjay Patel2e002772016-03-12 18:05:53 +00001219 BB1V->getName() + "." + BB2V->getName()));
Devang Patel1407fb42011-05-19 20:52:46 +00001220
Chris Lattner4088e2b2010-12-13 01:47:07 +00001221 // Make the PHI node use the select for all incoming values for BB1/BB2
1222 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1223 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1224 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001225 }
1226 }
1227
1228 // Update any PHI nodes in our new successors.
Sanjay Patel5781d842016-03-12 16:52:17 +00001229 for (BasicBlock *Succ : successors(BB1))
1230 AddPredecessorToBlock(Succ, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001231
Eli Friedmancb61afb2008-12-16 20:54:32 +00001232 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001233 return true;
1234}
1235
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001236/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001237/// check whether BBEnd has only two predecessors and the other predecessor
1238/// ends with an unconditional branch. If it is true, sink any common code
1239/// in the two predecessors to BBEnd.
1240static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1241 assert(BI1->isUnconditional());
1242 BasicBlock *BB1 = BI1->getParent();
1243 BasicBlock *BBEnd = BI1->getSuccessor(0);
1244
1245 // Check that BBEnd has two predecessors and the other predecessor ends with
1246 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001247 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1248 BasicBlock *Pred0 = *PI++;
1249 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001250 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001251 BasicBlock *Pred1 = *PI++;
1252 if (PI != PE) // More than two predecessors.
1253 return false;
1254 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001255 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1256 if (!BI2 || !BI2->isUnconditional())
1257 return false;
1258
1259 // Gather the PHI nodes in BBEnd.
Michael Liao5313da32014-12-23 08:26:55 +00001260 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
Craig Topperf40110f2014-04-25 05:29:35 +00001261 Instruction *FirstNonPhiInBBEnd = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001262 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
Manman Ren93ab6492012-09-20 22:37:36 +00001263 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1264 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001265 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Michael Liao5313da32014-12-23 08:26:55 +00001266 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
Manman Ren93ab6492012-09-20 22:37:36 +00001267 } else {
1268 FirstNonPhiInBBEnd = &*I;
1269 break;
1270 }
1271 }
1272 if (!FirstNonPhiInBBEnd)
1273 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001274
Manman Ren93ab6492012-09-20 22:37:36 +00001275 // This does very trivial matching, with limited scanning, to find identical
1276 // instructions in the two blocks. We scan backward for obviously identical
1277 // instructions in an identical order.
1278 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
Michael Liao5313da32014-12-23 08:26:55 +00001279 RE1 = BB1->getInstList().rend(),
1280 RI2 = BB2->getInstList().rbegin(),
1281 RE2 = BB2->getInstList().rend();
Manman Ren93ab6492012-09-20 22:37:36 +00001282 // Skip debug info.
1283 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1284 if (RI1 == RE1)
1285 return false;
1286 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1287 if (RI2 == RE2)
1288 return false;
1289 // Skip the unconditional branches.
1290 ++RI1;
1291 ++RI2;
1292
1293 bool Changed = false;
1294 while (RI1 != RE1 && RI2 != RE2) {
1295 // Skip debug info.
1296 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1297 if (RI1 == RE1)
1298 return Changed;
1299 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1300 if (RI2 == RE2)
1301 return Changed;
1302
1303 Instruction *I1 = &*RI1, *I2 = &*RI2;
Michael Liao5313da32014-12-23 08:26:55 +00001304 auto InstPair = std::make_pair(I1, I2);
Manman Ren93ab6492012-09-20 22:37:36 +00001305 // I1 and I2 should have a single use in the same PHI node, and they
1306 // perform the same operation.
1307 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1308 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1309 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
David Majnemerba275f92015-08-19 19:54:02 +00001310 I1->isEHPad() || I2->isEHPad() ||
Manman Ren93ab6492012-09-20 22:37:36 +00001311 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1312 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1313 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1314 !I1->hasOneUse() || !I2->hasOneUse() ||
Michael Liao5313da32014-12-23 08:26:55 +00001315 !JointValueMap.count(InstPair))
Manman Ren93ab6492012-09-20 22:37:36 +00001316 return Changed;
1317
1318 // Check whether we should swap the operands of ICmpInst.
Michael Liao5313da32014-12-23 08:26:55 +00001319 // TODO: Add support of communativity.
Manman Ren93ab6492012-09-20 22:37:36 +00001320 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1321 bool SwapOpnds = false;
1322 if (ICmp1 && ICmp2 &&
1323 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1324 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1325 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1326 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1327 ICmp2->swapOperands();
1328 SwapOpnds = true;
1329 }
1330 if (!I1->isSameOperationAs(I2)) {
1331 if (SwapOpnds)
1332 ICmp2->swapOperands();
1333 return Changed;
1334 }
1335
1336 // The operands should be either the same or they need to be generated
1337 // with a PHI node after sinking. We only handle the case where there is
1338 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001339 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001340 unsigned Op1Idx = ~0U;
Manman Ren93ab6492012-09-20 22:37:36 +00001341 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1342 if (I1->getOperand(I) == I2->getOperand(I))
1343 continue;
Michael Liao5313da32014-12-23 08:26:55 +00001344 // Early exit if we have more-than one pair of different operands or if
1345 // we need a PHI node to replace a constant.
1346 if (Op1Idx != ~0U ||
Manman Ren93ab6492012-09-20 22:37:36 +00001347 isa<Constant>(I1->getOperand(I)) ||
1348 isa<Constant>(I2->getOperand(I))) {
1349 // If we can't sink the instructions, undo the swapping.
1350 if (SwapOpnds)
1351 ICmp2->swapOperands();
1352 return Changed;
1353 }
1354 DifferentOp1 = I1->getOperand(I);
1355 Op1Idx = I;
1356 DifferentOp2 = I2->getOperand(I);
1357 }
1358
Michael Liao5313da32014-12-23 08:26:55 +00001359 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1360 DEBUG(dbgs() << " " << *I2 << "\n");
1361
1362 // We insert the pair of different operands to JointValueMap and
1363 // remove (I1, I2) from JointValueMap.
1364 if (Op1Idx != ~0U) {
1365 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1366 if (!NewPN) {
1367 NewPN =
1368 PHINode::Create(DifferentOp1->getType(), 2,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001369 DifferentOp1->getName() + ".sink", &BBEnd->front());
Michael Liao5313da32014-12-23 08:26:55 +00001370 NewPN->addIncoming(DifferentOp1, BB1);
1371 NewPN->addIncoming(DifferentOp2, BB2);
1372 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1373 }
Manman Ren93ab6492012-09-20 22:37:36 +00001374 // I1 should use NewPN instead of DifferentOp1.
1375 I1->setOperand(Op1Idx, NewPN);
Manman Ren93ab6492012-09-20 22:37:36 +00001376 }
Michael Liao5313da32014-12-23 08:26:55 +00001377 PHINode *OldPN = JointValueMap[InstPair];
1378 JointValueMap.erase(InstPair);
Manman Ren93ab6492012-09-20 22:37:36 +00001379
Manman Ren93ab6492012-09-20 22:37:36 +00001380 // We need to update RE1 and RE2 if we are going to sink the first
1381 // instruction in the basic block down.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00001382 bool UpdateRE1 = (I1 == &BB1->front()), UpdateRE2 = (I2 == &BB2->front());
Manman Ren93ab6492012-09-20 22:37:36 +00001383 // Sink the instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001384 BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(),
1385 BB1->getInstList(), I1);
Manman Ren93ab6492012-09-20 22:37:36 +00001386 if (!OldPN->use_empty())
1387 OldPN->replaceAllUsesWith(I1);
1388 OldPN->eraseFromParent();
1389
1390 if (!I2->use_empty())
1391 I2->replaceAllUsesWith(I1);
1392 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001393 // TODO: Use combineMetadata here to preserve what metadata we can
1394 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001395 I2->eraseFromParent();
1396
1397 if (UpdateRE1)
1398 RE1 = BB1->getInstList().rend();
1399 if (UpdateRE2)
1400 RE2 = BB2->getInstList().rend();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001401 FirstNonPhiInBBEnd = &*I1;
Manman Ren93ab6492012-09-20 22:37:36 +00001402 NumSinkCommons++;
1403 Changed = true;
1404 }
1405 return Changed;
1406}
1407
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001408/// \brief Determine if we can hoist sink a sole store instruction out of a
1409/// conditional block.
1410///
1411/// We are looking for code like the following:
1412/// BrBB:
1413/// store i32 %add, i32* %arrayidx2
1414/// ... // No other stores or function calls (we could be calling a memory
1415/// ... // function).
1416/// %cmp = icmp ult %x, %y
1417/// br i1 %cmp, label %EndBB, label %ThenBB
1418/// ThenBB:
1419/// store i32 %add5, i32* %arrayidx2
1420/// br label EndBB
1421/// EndBB:
1422/// ...
1423/// We are going to transform this into:
1424/// BrBB:
1425/// store i32 %add, i32* %arrayidx2
1426/// ... //
1427/// %cmp = icmp ult %x, %y
1428/// %add.add5 = select i1 %cmp, i32 %add, %add5
1429/// store i32 %add.add5, i32* %arrayidx2
1430/// ...
1431///
1432/// \return The pointer to the value of the previous store if the store can be
1433/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001434static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1435 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001436 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1437 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001438 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001439
1440 // Volatile or atomic.
1441 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001442 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001443
1444 Value *StorePtr = StoreToHoist->getPointerOperand();
1445
1446 // Look for a store to the same pointer in BrBB.
1447 unsigned MaxNumInstToLookAt = 10;
1448 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1449 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1450 Instruction *CurI = &*RI;
1451
1452 // Could be calling an instruction that effects memory like free().
1453 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001454 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001455
1456 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1457 // Found the previous store make sure it stores to the same location.
1458 if (SI && SI->getPointerOperand() == StorePtr)
1459 // Found the previous store, return its value operand.
1460 return SI->getValueOperand();
1461 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001462 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001463 }
1464
Craig Topperf40110f2014-04-25 05:29:35 +00001465 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001466}
1467
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001468/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001469///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001470/// Note that this is a very risky transform currently. Speculating
1471/// instructions like this is most often not desirable. Instead, there is an MI
1472/// pass which can do it with full awareness of the resource constraints.
1473/// However, some cases are "obvious" and we should do directly. An example of
1474/// this is speculating a single, reasonably cheap instruction.
1475///
1476/// There is only one distinct advantage to flattening the CFG at the IR level:
1477/// it makes very common but simplistic optimizations such as are common in
1478/// instcombine and the DAG combiner more powerful by removing CFG edges and
1479/// modeling their effects with easier to reason about SSA value graphs.
1480///
1481///
1482/// An illustration of this transform is turning this IR:
1483/// \code
1484/// BB:
1485/// %cmp = icmp ult %x, %y
1486/// br i1 %cmp, label %EndBB, label %ThenBB
1487/// ThenBB:
1488/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001489/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001490/// EndBB:
1491/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1492/// ...
1493/// \endcode
1494///
1495/// Into this IR:
1496/// \code
1497/// BB:
1498/// %cmp = icmp ult %x, %y
1499/// %sub = sub %x, %y
1500/// %cond = select i1 %cmp, 0, %sub
1501/// ...
1502/// \endcode
1503///
1504/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001505static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001506 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001507 // Be conservative for now. FP select instruction can often be expensive.
1508 Value *BrCond = BI->getCondition();
1509 if (isa<FCmpInst>(BrCond))
1510 return false;
1511
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001512 BasicBlock *BB = BI->getParent();
1513 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1514
1515 // If ThenBB is actually on the false edge of the conditional branch, remember
1516 // to swap the select operands later.
1517 bool Invert = false;
1518 if (ThenBB != BI->getSuccessor(0)) {
1519 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1520 Invert = true;
1521 }
1522 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1523
Chandler Carruthceff2222013-01-25 05:40:09 +00001524 // Keep a count of how many times instructions are used within CondBB when
1525 // they are candidates for sinking into CondBB. Specifically:
1526 // - They are defined in BB, and
1527 // - They have no side effects, and
1528 // - All of their uses are in CondBB.
1529 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1530
Chandler Carruth7481ca82013-01-24 11:52:58 +00001531 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001532 Value *SpeculatedStoreValue = nullptr;
1533 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001534 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001535 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001536 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001537 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001538 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001539 if (isa<DbgInfoIntrinsic>(I))
1540 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001541
Mark Lacey274f48b2015-04-12 18:18:51 +00001542 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001543 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001544 ++SpeculationCost;
1545 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001546 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001547
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001548 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001549 if (!isSafeToSpeculativelyExecute(I) &&
1550 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1551 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001552 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001553 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001554 ComputeSpeculationCost(I, TTI) >
1555 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001556 return false;
1557
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001558 // Store the store speculation candidate.
1559 if (SpeculatedStoreValue)
1560 SpeculatedStore = cast<StoreInst>(I);
1561
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001562 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001563 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001564 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001565 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001566 i != e; ++i) {
1567 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001568 if (!OpI || OpI->getParent() != BB ||
1569 OpI->mayHaveSideEffects())
1570 continue; // Not a candidate for sinking.
1571
1572 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001573 }
1574 }
Evan Cheng89200c92008-06-07 08:52:29 +00001575
Chandler Carruthceff2222013-01-25 05:40:09 +00001576 // Consider any sink candidates which are only used in CondBB as costs for
1577 // speculation. Note, while we iterate over a DenseMap here, we are summing
1578 // and so iteration order isn't significant.
1579 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1580 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1581 I != E; ++I)
1582 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001583 ++SpeculationCost;
1584 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001585 return false;
1586 }
1587
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001588 // Check that the PHI nodes can be converted to selects.
1589 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001590 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001591 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001592 Value *OrigV = PN->getIncomingValueForBlock(BB);
1593 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001594
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001595 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001596 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001597 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001598 continue;
1599
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001600 // Don't convert to selects if we could remove undefined behavior instead.
1601 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1602 passingValueIsAlwaysUndefined(ThenV, PN))
1603 return false;
1604
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001605 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001606 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1607 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1608 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001609 continue; // Known safe and cheap.
1610
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001611 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1612 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001613 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001614 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1615 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
James Molloy7c336572015-02-11 12:15:41 +00001616 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1617 TargetTransformInfo::TCC_Basic;
1618 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00001619 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001620
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001621 // Account for the cost of an unfolded ConstantExpr which could end up
1622 // getting expanded into Instructions.
1623 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001624 // constant expression.
1625 ++SpeculationCost;
1626 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001627 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001628 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001629
1630 // If there are no PHIs to process, bail early. This helps ensure idempotence
1631 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001632 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001633 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001634
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001635 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001636 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001637
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001638 // Insert a select of the value of the speculated store.
1639 if (SpeculatedStoreValue) {
Eric Christopher35abd052016-03-12 01:47:22 +00001640 IRBuilder<true, NoFolder> Builder(BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001641 Value *TrueV = SpeculatedStore->getValueOperand();
1642 Value *FalseV = SpeculatedStoreValue;
1643 if (Invert)
1644 std::swap(TrueV, FalseV);
1645 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1646 "." + FalseV->getName());
1647 SpeculatedStore->setOperand(0, S);
1648 }
1649
Igor Laevsky7310c682015-11-18 14:50:18 +00001650 // Metadata can be dependent on the condition we are hoisting above.
1651 // Conservatively strip all metadata on the instruction.
1652 for (auto &I: *ThenBB)
1653 I.dropUnknownNonDebugMetadata();
1654
Chandler Carruth7481ca82013-01-24 11:52:58 +00001655 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001656 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
1657 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001658
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001659 // Insert selects and rewrite the PHI operands.
Eric Christopher35abd052016-03-12 01:47:22 +00001660 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001661 for (BasicBlock::iterator I = EndBB->begin();
1662 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1663 unsigned OrigI = PN->getBasicBlockIndex(BB);
1664 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1665 Value *OrigV = PN->getIncomingValue(OrigI);
1666 Value *ThenV = PN->getIncomingValue(ThenI);
1667
1668 // Skip PHIs which are trivial.
1669 if (OrigV == ThenV)
1670 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001671
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001672 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001673 // false value is the preexisting value. Swap them if the branch
1674 // destinations were inverted.
1675 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001676 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001677 std::swap(TrueV, FalseV);
1678 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1679 TrueV->getName() + "." + FalseV->getName());
1680 PN->setIncomingValue(OrigI, V);
1681 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001682 }
1683
Evan Cheng89553cc2008-06-12 21:15:59 +00001684 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001685 return true;
1686}
1687
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001688/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001689static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1690 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001691 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001692
Devang Patel84fceff2009-03-10 18:00:05 +00001693 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001694 if (isa<DbgInfoIntrinsic>(BBI))
1695 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001696 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001697 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001698
Dale Johannesened6f5a82009-03-12 23:18:09 +00001699 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001700 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001701 for (User *U : BBI->users()) {
1702 Instruction *UI = cast<Instruction>(U);
1703 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001704 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001705
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001706 // Looks ok, continue checking.
1707 }
Chris Lattner6c701062005-09-20 01:48:40 +00001708
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001709 return true;
1710}
1711
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001712/// If we have a conditional branch on a PHI node value that is defined in the
1713/// same block as the branch and if any PHI entries are constants, thread edges
1714/// corresponding to that entry to be branches to their ultimate destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001715static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001716 BasicBlock *BB = BI->getParent();
1717 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001718 // NOTE: we currently cannot transform this case if the PHI node is used
1719 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001720 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1721 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001722
Chris Lattner748f9032005-09-19 23:49:37 +00001723 // Degenerate case of a single entry PHI.
1724 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001725 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001726 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001727 }
1728
1729 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001730 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001731
Justin Lebardb639492016-02-12 21:01:36 +00001732 // Can't fold blocks that contain noduplicate or convergent calls.
1733 if (llvm::any_of(*BB, [](const Instruction &I) {
1734 const CallInst *CI = dyn_cast<CallInst>(&I);
1735 return CI && (CI->cannotDuplicate() || CI->isConvergent());
1736 }))
1737 return false;
Tom Stellarde1631dd2013-10-21 20:07:30 +00001738
Chris Lattner748f9032005-09-19 23:49:37 +00001739 // Okay, this is a simple enough basic block. See if any phi values are
1740 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001741 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001742 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001743 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001744
Chris Lattner4088e2b2010-12-13 01:47:07 +00001745 // Okay, we now know that all edges from PredBB should be revectored to
1746 // branch to RealDest.
1747 BasicBlock *PredBB = PN->getIncomingBlock(i);
1748 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001749
Chris Lattner4088e2b2010-12-13 01:47:07 +00001750 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001751 // Skip if the predecessor's terminator is an indirect branch.
1752 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001753
Chris Lattner4088e2b2010-12-13 01:47:07 +00001754 // The dest block might have PHI nodes, other predecessors and other
1755 // difficult cases. Instead of being smart about this, just insert a new
1756 // block that jumps to the destination block, effectively splitting
1757 // the edge we are about to create.
1758 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1759 RealDest->getName()+".critedge",
1760 RealDest->getParent(), RealDest);
1761 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001762
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001763 // Update PHI nodes.
1764 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001765
1766 // BB may have instructions that are being threaded over. Clone these
1767 // instructions into EdgeBB. We know that there will be no uses of the
1768 // cloned instructions outside of EdgeBB.
1769 BasicBlock::iterator InsertPt = EdgeBB->begin();
1770 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1771 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1772 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1773 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1774 continue;
1775 }
1776 // Clone the instruction.
1777 Instruction *N = BBI->clone();
1778 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001779
Chris Lattner4088e2b2010-12-13 01:47:07 +00001780 // Update operands due to translation.
1781 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1782 i != e; ++i) {
1783 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1784 if (PI != TranslateMap.end())
1785 *i = PI->second;
1786 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001787
Chris Lattner4088e2b2010-12-13 01:47:07 +00001788 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001789 if (Value *V = SimplifyInstruction(N, DL)) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001790 TranslateMap[&*BBI] = V;
Chris Lattnerd7beca32010-12-14 06:17:25 +00001791 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001792 } else {
1793 // Insert the new instruction into its new home.
1794 EdgeBB->getInstList().insert(InsertPt, N);
1795 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001796 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001797 }
1798 }
1799
1800 // Loop over all of the edges from PredBB to BB, changing them to branch
1801 // to EdgeBB instead.
1802 TerminatorInst *PredBBTI = PredBB->getTerminator();
1803 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1804 if (PredBBTI->getSuccessor(i) == BB) {
1805 BB->removePredecessor(PredBB);
1806 PredBBTI->setSuccessor(i, EdgeBB);
1807 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001808
Chris Lattner4088e2b2010-12-13 01:47:07 +00001809 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001810 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001811 }
Chris Lattner748f9032005-09-19 23:49:37 +00001812
1813 return false;
1814}
1815
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001816/// Given a BB that starts with the specified two-entry PHI node,
1817/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001818static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1819 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001820 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1821 // statement", which has a very simple dominance structure. Basically, we
1822 // are trying to find the condition that is being branched on, which
1823 // subsequently causes this merge to happen. We really want control
1824 // dependence information for this check, but simplifycfg can't keep it up
1825 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001826 BasicBlock *BB = PN->getParent();
1827 BasicBlock *IfTrue, *IfFalse;
1828 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001829 if (!IfCond ||
1830 // Don't bother if the branch will be constant folded trivially.
1831 isa<ConstantInt>(IfCond))
1832 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001833
Chris Lattner95adf8f12006-11-18 19:19:36 +00001834 // Okay, we found that we can merge this two-entry phi node into a select.
1835 // Doing so would require us to fold *all* two entry phi nodes in this block.
1836 // At some point this becomes non-profitable (particularly if the target
1837 // doesn't support cmov's). Only do this transformation if there are two or
1838 // fewer PHI nodes in this block.
1839 unsigned NumPhis = 0;
1840 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1841 if (NumPhis > 2)
1842 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001843
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001844 // Loop over the PHI's seeing if we can promote them all to select
1845 // instructions. While we are at it, keep track of the instructions
1846 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001847 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001848 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1849 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00001850 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1851 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001852
Chris Lattner7499b452010-12-14 08:46:09 +00001853 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1854 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001855 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001856 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001857 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001858 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001859 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001860
Peter Collingbournee3511e12011-04-29 18:47:31 +00001861 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001862 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001863 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001864 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001865 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001866 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001867
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001868 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001869 // we ran out of PHIs then we simplified them all.
1870 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001871 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001872
Chris Lattner7499b452010-12-14 08:46:09 +00001873 // Don't fold i1 branches on PHIs which contain binary operators. These can
1874 // often be turned into switches and other things.
1875 if (PN->getType()->isIntegerTy(1) &&
1876 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1877 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1878 isa<BinaryOperator>(IfCond)))
1879 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001880
Sanjay Patel2e002772016-03-12 18:05:53 +00001881 // If all PHI nodes are promotable, check to make sure that all instructions
1882 // in the predecessor blocks can be promoted as well. If not, we won't be able
1883 // to get rid of the control flow, so it's not worth promoting to select
1884 // instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001885 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001886 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1887 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1888 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001889 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001890 } else {
1891 DomBlock = *pred_begin(IfBlock1);
1892 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001893 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001894 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00001895 // Because of this, we won't be able to get rid of the control flow, so
1896 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001897 return false;
1898 }
1899 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001900
Chris Lattner9ac168d2010-12-14 07:41:39 +00001901 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001902 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001903 } else {
1904 DomBlock = *pred_begin(IfBlock2);
1905 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001906 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001907 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00001908 // Because of this, we won't be able to get rid of the control flow, so
1909 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001910 return false;
1911 }
1912 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001913
Chris Lattner9fd838d2010-12-14 07:23:10 +00001914 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001915 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001916
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001917 // If we can still promote the PHI nodes after this gauntlet of tests,
1918 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001919 Instruction *InsertPt = DomBlock->getTerminator();
Eric Christopher35abd052016-03-12 01:47:22 +00001920 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001921
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001922 // Move all 'aggressive' instructions, which are defined in the
1923 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001924 if (IfBlock1)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001925 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001926 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001927 IfBlock1->getTerminator()->getIterator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001928 if (IfBlock2)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001929 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001930 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001931 IfBlock2->getTerminator()->getIterator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001932
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001933 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1934 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001935 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1936 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001937
1938 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001939 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001940 PN->replaceAllUsesWith(NV);
1941 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001942 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001943 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001944
Chris Lattner335f0e42010-12-14 08:01:53 +00001945 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1946 // has been flattened. Change DomBlock to jump directly to our new block to
1947 // avoid other simplifycfg's kicking in on the diamond.
1948 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001949 Builder.SetInsertPoint(OldTI);
1950 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001951 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001952 return true;
1953}
Chris Lattner748f9032005-09-19 23:49:37 +00001954
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001955/// If we found a conditional branch that goes to two returning blocks,
1956/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00001957/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001958static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001959 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001960 assert(BI->isConditional() && "Must be a conditional branch");
1961 BasicBlock *TrueSucc = BI->getSuccessor(0);
1962 BasicBlock *FalseSucc = BI->getSuccessor(1);
1963 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1964 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001965
Chris Lattner86bbf332008-04-24 00:01:19 +00001966 // Check to ensure both blocks are empty (just a return) or optionally empty
1967 // with PHI nodes. If there are other instructions, merging would cause extra
1968 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001969 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001970 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001971 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001972 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001973
Devang Pateldd14e0f2011-05-18 21:33:11 +00001974 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001975 // Okay, we found a branch that is going to two return nodes. If
1976 // there is no return value for this function, just change the
1977 // branch into a return.
1978 if (FalseRet->getNumOperands() == 0) {
1979 TrueSucc->removePredecessor(BI->getParent());
1980 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001981 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001982 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001983 return true;
1984 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001985
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001986 // Otherwise, figure out what the true and false return values are
1987 // so we can insert a new select instruction.
1988 Value *TrueValue = TrueRet->getReturnValue();
1989 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001990
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001991 // Unwrap any PHI nodes in the return blocks.
1992 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1993 if (TVPN->getParent() == TrueSucc)
1994 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1995 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1996 if (FVPN->getParent() == FalseSucc)
1997 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001998
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001999 // In order for this transformation to be safe, we must be able to
2000 // unconditionally execute both operands to the return. This is
2001 // normally the case, but we could have a potentially-trapping
2002 // constant expression that prevents this transformation from being
2003 // safe.
2004 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2005 if (TCV->canTrap())
2006 return false;
2007 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2008 if (FCV->canTrap())
2009 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002010
Chris Lattner86bbf332008-04-24 00:01:19 +00002011 // Okay, we collected all the mapped values and checked them for sanity, and
2012 // defined to really do this transformation. First, update the CFG.
2013 TrueSucc->removePredecessor(BI->getParent());
2014 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002015
Chris Lattner86bbf332008-04-24 00:01:19 +00002016 // Insert select instructions where needed.
2017 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002018 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002019 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002020 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2021 } else if (isa<UndefValue>(TrueValue)) {
2022 TrueValue = FalseValue;
2023 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00002024 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
2025 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00002026 }
Chris Lattner86bbf332008-04-24 00:01:19 +00002027 }
2028
Andrew Trickf3cf1932012-08-29 21:46:36 +00002029 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00002030 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2031
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00002032 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002033
David Greene725c7c32010-01-05 01:26:52 +00002034 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002035 << "\n " << *BI << "NewRet = " << *RI
2036 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002037
Eli Friedmancb61afb2008-12-16 20:54:32 +00002038 EraseTerminatorInstAndDCECond(BI);
2039
Chris Lattner86bbf332008-04-24 00:01:19 +00002040 return true;
2041}
2042
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002043/// Given a conditional BranchInstruction, retrieve the probabilities of the
2044/// branch taking each edge. Fills in the two APInt parameters and returns true,
2045/// or returns false if no or invalid metadata was found.
Juergen Ributzka194350a2014-12-09 17:32:12 +00002046static bool ExtractBranchMetadata(BranchInst *BI,
2047 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2048 assert(BI->isConditional() &&
2049 "Looking for probabilities on unconditional branch?");
2050 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2051 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002052 ConstantInt *CITrue =
2053 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2054 ConstantInt *CIFalse =
2055 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00002056 if (!CITrue || !CIFalse) return false;
2057 ProbTrue = CITrue->getValue().getZExtValue();
2058 ProbFalse = CIFalse->getValue().getZExtValue();
2059 return true;
2060}
2061
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002062/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002063/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002064static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002065 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2066 return false;
2067 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2068 Instruction *PBI = &*I;
2069 // Check whether Inst and PBI generate the same value.
2070 if (Inst->isIdenticalTo(PBI)) {
2071 Inst->replaceAllUsesWith(PBI);
2072 Inst->eraseFromParent();
2073 return true;
2074 }
2075 }
2076 return false;
2077}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002078
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002079/// If this basic block is simple enough, and if a predecessor branches to us
2080/// and one of our successors, fold the block into the predecessor and use
2081/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002082bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002083 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002084
Craig Topperf40110f2014-04-25 05:29:35 +00002085 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002086 if (BI->isConditional())
2087 Cond = dyn_cast<Instruction>(BI->getCondition());
2088 else {
2089 // For unconditional branch, check for a simple CFG pattern, where
2090 // BB has a single predecessor and BB's successor is also its predecessor's
2091 // successor. If such pattern exisits, check for CSE between BB and its
2092 // predecessor.
2093 if (BasicBlock *PB = BB->getSinglePredecessor())
2094 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2095 if (PBI->isConditional() &&
2096 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2097 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2098 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2099 I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002100 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002101 if (isa<CmpInst>(Curr)) {
2102 Cond = Curr;
2103 break;
2104 }
2105 // Quit if we can't remove this instruction.
2106 if (!checkCSEInPredecessor(Curr, PB))
2107 return false;
2108 }
2109 }
2110
Craig Topperf40110f2014-04-25 05:29:35 +00002111 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002112 return false;
2113 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002114
Craig Topperf40110f2014-04-25 05:29:35 +00002115 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2116 Cond->getParent() != BB || !Cond->hasOneUse())
Sanjay Patel2e002772016-03-12 18:05:53 +00002117 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002118
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002119 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002120 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002121
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002122 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002123 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002124
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002125 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002126 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002127
Jingyue Wufc029672014-09-30 22:23:38 +00002128 // Only allow this transformation if computing the condition doesn't involve
2129 // too many instructions and these involved instructions can be executed
2130 // unconditionally. We denote all involved instructions except the condition
2131 // as "bonus instructions", and only allow this transformation when the
2132 // number of the bonus instructions does not exceed a certain threshold.
2133 unsigned NumBonusInsts = 0;
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002134 for (auto I = BB->begin(); Cond != &*I; ++I) {
Jingyue Wufc029672014-09-30 22:23:38 +00002135 // Ignore dbg intrinsics.
2136 if (isa<DbgInfoIntrinsic>(I))
2137 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002138 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002139 return false;
2140 // I has only one use and can be executed unconditionally.
2141 Instruction *User = dyn_cast<Instruction>(I->user_back());
2142 if (User == nullptr || User->getParent() != BB)
2143 return false;
2144 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2145 // to use any other instruction, User must be an instruction between next(I)
2146 // and Cond.
2147 ++NumBonusInsts;
2148 // Early exits once we reach the limit.
2149 if (NumBonusInsts > BonusInstThreshold)
2150 return false;
2151 }
2152
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002153 // Cond is known to be a compare or binary operator. Check to make sure that
2154 // neither operand is a potentially-trapping constant expression.
2155 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2156 if (CE->canTrap())
2157 return false;
2158 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2159 if (CE->canTrap())
2160 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002161
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002162 // Finally, don't infinitely unroll conditional loops.
2163 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002164 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002165 if (TrueDest == BB || FalseDest == BB)
2166 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002167
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002168 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2169 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002170 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002171
Chris Lattner80b03a12008-07-13 22:23:11 +00002172 // Check that we have two conditional branches. If there is a PHI node in
2173 // the common successor, verify that the same value flows in from both
2174 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002175 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002176 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002177 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002178 !SafeToMergeTerminators(BI, PBI)) ||
2179 (!BI->isConditional() &&
2180 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002181 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002182
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002183 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002184 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002185 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002186
Manman Rend33f4ef2012-06-13 05:43:29 +00002187 if (BI->isConditional()) {
Richard Trieu7a083812016-02-18 22:09:30 +00002188 if (PBI->getSuccessor(0) == TrueDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002189 Opc = Instruction::Or;
Richard Trieu7a083812016-02-18 22:09:30 +00002190 } else if (PBI->getSuccessor(1) == FalseDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002191 Opc = Instruction::And;
Richard Trieu7a083812016-02-18 22:09:30 +00002192 } else if (PBI->getSuccessor(0) == FalseDest) {
2193 Opc = Instruction::And;
2194 InvertPredCond = true;
2195 } else if (PBI->getSuccessor(1) == TrueDest) {
2196 Opc = Instruction::Or;
2197 InvertPredCond = true;
2198 } else {
Manman Rend33f4ef2012-06-13 05:43:29 +00002199 continue;
Richard Trieu7a083812016-02-18 22:09:30 +00002200 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002201 } else {
2202 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2203 continue;
2204 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002205
David Greene725c7c32010-01-05 01:26:52 +00002206 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002207 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002208
Chris Lattner55eaae12008-07-13 21:20:19 +00002209 // If we need to invert the condition in the pred block to match, do so now.
2210 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002211 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002212
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002213 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2214 CmpInst *CI = cast<CmpInst>(NewCond);
2215 CI->setPredicate(CI->getInversePredicate());
2216 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002217 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002218 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002219 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002220
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002221 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002222 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002223 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002224
Jingyue Wufc029672014-09-30 22:23:38 +00002225 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002226 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002227 // bonus instructions to a predecessor block.
2228 ValueToValueMapTy VMap; // maps original values to cloned values
2229 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002230 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002231 // instructions.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002232 for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
Jingyue Wufc029672014-09-30 22:23:38 +00002233 if (isa<DbgInfoIntrinsic>(BonusInst))
2234 continue;
2235 Instruction *NewBonusInst = BonusInst->clone();
2236 RemapInstruction(NewBonusInst, VMap,
2237 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002238 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002239
2240 // If we moved a load, we cannot any longer claim any knowledge about
2241 // its potential value. The previous information might have been valid
2242 // only given the branch precondition.
2243 // For an analogous reason, we must also drop all the metadata whose
2244 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002245 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002246
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002247 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2248 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002249 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002250 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002251
Chris Lattner55eaae12008-07-13 21:20:19 +00002252 // Clone Cond into the predecessor basic block, and or/and the
2253 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002254 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002255 RemapInstruction(New, VMap,
2256 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002257 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002258 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002259 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002260
Manman Rend33f4ef2012-06-13 05:43:29 +00002261 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002262 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002263 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002264 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002265 PBI->setCondition(NewCond);
2266
Manman Renbfb9d432012-09-15 00:39:57 +00002267 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002268 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2269 PredFalseWeight);
2270 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2271 SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002272 SmallVector<uint64_t, 8> NewWeights;
2273
Manman Rend33f4ef2012-06-13 05:43:29 +00002274 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002275 if (PredHasWeights && SuccHasWeights) {
2276 // PBI: br i1 %x, BB, FalseDest
2277 // BI: br i1 %y, TrueDest, FalseDest
2278 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2279 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2280 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2281 // TrueWeight for PBI * FalseWeight for BI.
2282 // We assume that total weights of a BranchInst can fit into 32 bits.
2283 // Therefore, we will not have overflow using 64-bit arithmetic.
2284 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2285 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2286 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002287 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2288 PBI->setSuccessor(0, TrueDest);
2289 }
2290 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002291 if (PredHasWeights && SuccHasWeights) {
2292 // PBI: br i1 %x, TrueDest, BB
2293 // BI: br i1 %y, TrueDest, FalseDest
2294 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2295 // FalseWeight for PBI * TrueWeight for BI.
2296 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2297 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2298 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2299 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2300 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002301 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2302 PBI->setSuccessor(1, FalseDest);
2303 }
Manman Renbfb9d432012-09-15 00:39:57 +00002304 if (NewWeights.size() == 2) {
2305 // Halve the weights if any of them cannot fit in an uint32_t
2306 FitWeights(NewWeights);
2307
2308 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2309 PBI->setMetadata(LLVMContext::MD_prof,
2310 MDBuilder(BI->getContext()).
2311 createBranchWeights(MDWeights));
2312 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002313 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002314 } else {
2315 // Update PHI nodes in the common successors.
2316 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002317 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002318 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2319 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002320 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002321 if (PBI->getSuccessor(0) == TrueDest) {
2322 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2323 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2324 // is false: !PBI_Cond and BI_Value
2325 Instruction *NotCond =
2326 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2327 "not.cond"));
2328 MergedCond =
2329 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2330 NotCond, New,
2331 "and.cond"));
2332 if (PBI_C->isOne())
2333 MergedCond =
2334 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2335 PBI->getCondition(), MergedCond,
2336 "or.cond"));
2337 } else {
2338 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2339 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2340 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002341 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002342 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2343 PBI->getCondition(), New,
2344 "and.cond"));
2345 if (PBI_C->isOne()) {
2346 Instruction *NotCond =
2347 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2348 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002349 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002350 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2351 NotCond, MergedCond,
2352 "or.cond"));
2353 }
2354 }
2355 // Update PHI Node.
2356 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2357 MergedCond);
2358 }
2359 // Change PBI from Conditional to Unconditional.
2360 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2361 EraseTerminatorInstAndDCECond(PBI);
2362 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002363 }
Devang Pateld715ec82011-04-06 22:37:20 +00002364
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002365 // TODO: If BB is reachable from all paths through PredBlock, then we
2366 // could replace PBI's branch probabilities with BI's.
2367
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002368 // Copy any debug value intrinsics into the end of PredBlock.
2369 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2370 if (isa<DbgInfoIntrinsic>(*I))
2371 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002372
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002373 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002374 }
2375 return false;
2376}
2377
James Molloy4de84dd2015-11-04 15:28:04 +00002378// If there is only one store in BB1 and BB2, return it, otherwise return
2379// nullptr.
2380static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2381 StoreInst *S = nullptr;
2382 for (auto *BB : {BB1, BB2}) {
2383 if (!BB)
2384 continue;
2385 for (auto &I : *BB)
2386 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2387 if (S)
2388 // Multiple stores seen.
2389 return nullptr;
2390 else
2391 S = SI;
2392 }
2393 }
2394 return S;
2395}
2396
2397static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2398 Value *AlternativeV = nullptr) {
2399 // PHI is going to be a PHI node that allows the value V that is defined in
2400 // BB to be referenced in BB's only successor.
2401 //
2402 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2403 // doesn't matter to us what the other operand is (it'll never get used). We
2404 // could just create a new PHI with an undef incoming value, but that could
2405 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2406 // other PHI. So here we directly look for some PHI in BB's successor with V
2407 // as an incoming operand. If we find one, we use it, else we create a new
2408 // one.
2409 //
2410 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2411 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2412 // where OtherBB is the single other predecessor of BB's only successor.
2413 PHINode *PHI = nullptr;
2414 BasicBlock *Succ = BB->getSingleSuccessor();
2415
2416 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2417 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2418 PHI = cast<PHINode>(I);
2419 if (!AlternativeV)
2420 break;
2421
2422 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2423 auto PredI = pred_begin(Succ);
2424 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2425 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2426 break;
2427 PHI = nullptr;
2428 }
2429 if (PHI)
2430 return PHI;
2431
James Molloy3d21dcf2015-12-16 14:12:44 +00002432 // If V is not an instruction defined in BB, just return it.
2433 if (!AlternativeV &&
2434 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2435 return V;
2436
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002437 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
James Molloy4de84dd2015-11-04 15:28:04 +00002438 PHI->addIncoming(V, BB);
2439 for (BasicBlock *PredBB : predecessors(Succ))
2440 if (PredBB != BB)
2441 PHI->addIncoming(AlternativeV ? AlternativeV : UndefValue::get(V->getType()),
2442 PredBB);
2443 return PHI;
2444}
2445
2446static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2447 BasicBlock *QTB, BasicBlock *QFB,
2448 BasicBlock *PostBB, Value *Address,
2449 bool InvertPCond, bool InvertQCond) {
2450 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2451 return Operator::getOpcode(&I) == Instruction::BitCast &&
2452 I.getType()->isPointerTy();
2453 };
2454
2455 // If we're not in aggressive mode, we only optimize if we have some
2456 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2457 auto IsWorthwhile = [&](BasicBlock *BB) {
2458 if (!BB)
2459 return true;
2460 // Heuristic: if the block can be if-converted/phi-folded and the
2461 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2462 // thread this store.
James Molloy9e959ac2015-11-05 08:40:19 +00002463 unsigned N = 0;
2464 for (auto &I : *BB) {
2465 // Cheap instructions viable for folding.
2466 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2467 isa<StoreInst>(I))
2468 ++N;
2469 // Free instructions.
2470 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2471 IsaBitcastOfPointerType(I))
2472 continue;
2473 else
James Molloy4de84dd2015-11-04 15:28:04 +00002474 return false;
James Molloy9e959ac2015-11-05 08:40:19 +00002475 }
2476 return N <= PHINodeFoldingThreshold;
James Molloy4de84dd2015-11-04 15:28:04 +00002477 };
2478
2479 if (!MergeCondStoresAggressively && (!IsWorthwhile(PTB) ||
2480 !IsWorthwhile(PFB) ||
2481 !IsWorthwhile(QTB) ||
2482 !IsWorthwhile(QFB)))
2483 return false;
2484
2485 // For every pointer, there must be exactly two stores, one coming from
2486 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2487 // store (to any address) in PTB,PFB or QTB,QFB.
2488 // FIXME: We could relax this restriction with a bit more work and performance
2489 // testing.
2490 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2491 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2492 if (!PStore || !QStore)
2493 return false;
2494
2495 // Now check the stores are compatible.
2496 if (!QStore->isUnordered() || !PStore->isUnordered())
2497 return false;
2498
2499 // Check that sinking the store won't cause program behavior changes. Sinking
2500 // the store out of the Q blocks won't change any behavior as we're sinking
2501 // from a block to its unconditional successor. But we're moving a store from
2502 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2503 // So we need to check that there are no aliasing loads or stores in
2504 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2505 // operations between PStore and the end of its parent block.
2506 //
2507 // The ideal way to do this is to query AliasAnalysis, but we don't
2508 // preserve AA currently so that is dangerous. Be super safe and just
2509 // check there are no other memory operations at all.
2510 for (auto &I : *QFB->getSinglePredecessor())
2511 if (I.mayReadOrWriteMemory())
2512 return false;
2513 for (auto &I : *QFB)
2514 if (&I != QStore && I.mayReadOrWriteMemory())
2515 return false;
2516 if (QTB)
2517 for (auto &I : *QTB)
2518 if (&I != QStore && I.mayReadOrWriteMemory())
2519 return false;
2520 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2521 I != E; ++I)
2522 if (&*I != PStore && I->mayReadOrWriteMemory())
2523 return false;
2524
2525 // OK, we're going to sink the stores to PostBB. The store has to be
2526 // conditional though, so first create the predicate.
2527 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2528 ->getCondition();
2529 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2530 ->getCondition();
2531
2532 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2533 PStore->getParent());
2534 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2535 QStore->getParent(), PPHI);
2536
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002537 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2538
James Molloy4de84dd2015-11-04 15:28:04 +00002539 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2540 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2541
2542 if (InvertPCond)
2543 PPred = QB.CreateNot(PPred);
2544 if (InvertQCond)
2545 QPred = QB.CreateNot(QPred);
2546 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2547
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002548 auto *T =
2549 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
James Molloy4de84dd2015-11-04 15:28:04 +00002550 QB.SetInsertPoint(T);
2551 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2552 AAMDNodes AAMD;
2553 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2554 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2555 SI->setAAMetadata(AAMD);
2556
2557 QStore->eraseFromParent();
2558 PStore->eraseFromParent();
2559
2560 return true;
2561}
2562
2563static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) {
2564 // The intention here is to find diamonds or triangles (see below) where each
2565 // conditional block contains a store to the same address. Both of these
2566 // stores are conditional, so they can't be unconditionally sunk. But it may
2567 // be profitable to speculatively sink the stores into one merged store at the
2568 // end, and predicate the merged store on the union of the two conditions of
2569 // PBI and QBI.
2570 //
2571 // This can reduce the number of stores executed if both of the conditions are
2572 // true, and can allow the blocks to become small enough to be if-converted.
2573 // This optimization will also chain, so that ladders of test-and-set
2574 // sequences can be if-converted away.
2575 //
2576 // We only deal with simple diamonds or triangles:
2577 //
2578 // PBI or PBI or a combination of the two
2579 // / \ | \
2580 // PTB PFB | PFB
2581 // \ / | /
2582 // QBI QBI
2583 // / \ | \
2584 // QTB QFB | QFB
2585 // \ / | /
2586 // PostBB PostBB
2587 //
2588 // We model triangles as a type of diamond with a nullptr "true" block.
2589 // Triangles are canonicalized so that the fallthrough edge is represented by
2590 // a true condition, as in the diagram above.
2591 //
2592 BasicBlock *PTB = PBI->getSuccessor(0);
2593 BasicBlock *PFB = PBI->getSuccessor(1);
2594 BasicBlock *QTB = QBI->getSuccessor(0);
2595 BasicBlock *QFB = QBI->getSuccessor(1);
2596 BasicBlock *PostBB = QFB->getSingleSuccessor();
2597
2598 bool InvertPCond = false, InvertQCond = false;
2599 // Canonicalize fallthroughs to the true branches.
2600 if (PFB == QBI->getParent()) {
2601 std::swap(PFB, PTB);
2602 InvertPCond = true;
2603 }
2604 if (QFB == PostBB) {
2605 std::swap(QFB, QTB);
2606 InvertQCond = true;
2607 }
2608
2609 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
2610 // and QFB may not. Model fallthroughs as a nullptr block.
2611 if (PTB == QBI->getParent())
2612 PTB = nullptr;
2613 if (QTB == PostBB)
2614 QTB = nullptr;
2615
2616 // Legality bailouts. We must have at least the non-fallthrough blocks and
2617 // the post-dominating block, and the non-fallthroughs must only have one
2618 // predecessor.
2619 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
2620 return BB->getSinglePredecessor() == P &&
2621 BB->getSingleSuccessor() == S;
2622 };
2623 if (!PostBB ||
2624 !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
2625 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
2626 return false;
2627 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
2628 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
2629 return false;
2630 if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2)
2631 return false;
2632
2633 // OK, this is a sequence of two diamonds or triangles.
2634 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
2635 SmallPtrSet<Value *,4> PStoreAddresses, QStoreAddresses;
2636 for (auto *BB : {PTB, PFB}) {
2637 if (!BB)
2638 continue;
2639 for (auto &I : *BB)
2640 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2641 PStoreAddresses.insert(SI->getPointerOperand());
2642 }
2643 for (auto *BB : {QTB, QFB}) {
2644 if (!BB)
2645 continue;
2646 for (auto &I : *BB)
2647 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2648 QStoreAddresses.insert(SI->getPointerOperand());
2649 }
2650
2651 set_intersect(PStoreAddresses, QStoreAddresses);
2652 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
2653 // clear what it contains.
2654 auto &CommonAddresses = PStoreAddresses;
2655
2656 bool Changed = false;
2657 for (auto *Address : CommonAddresses)
2658 Changed |= mergeConditionalStoreToAddress(
2659 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond);
2660 return Changed;
2661}
2662
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002663/// If we have a conditional branch as a predecessor of another block,
2664/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00002665/// that PBI and BI are both conditional branches, and BI is in one of the
2666/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00002667static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
2668 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00002669 assert(PBI->isConditional() && BI->isConditional());
2670 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002671
Chris Lattner9aada1d2008-07-13 21:53:26 +00002672 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002673 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002674 // this conditional branch redundant.
2675 if (PBI->getCondition() == BI->getCondition() &&
2676 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2677 // Okay, the outcome of this conditional branch is statically
2678 // knowable. If this block had a single pred, handle specially.
2679 if (BB->getSinglePredecessor()) {
2680 // Turn this into a branch on constant.
2681 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002682 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002683 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002684 return true; // Nuke the branch on constant.
2685 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002686
Chris Lattner9aada1d2008-07-13 21:53:26 +00002687 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2688 // in the constant and simplify the block result. Subsequent passes of
2689 // simplifycfg will thread the block.
2690 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002691 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002692 PHINode *NewPN = PHINode::Create(
2693 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
2694 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00002695 // Okay, we're going to insert the PHI node. Since PBI is not the only
2696 // predecessor, compute the PHI'd conditional value for all of the preds.
2697 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002698 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002699 BasicBlock *P = *PI;
2700 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002701 PBI != BI && PBI->isConditional() &&
2702 PBI->getCondition() == BI->getCondition() &&
2703 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2704 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002705 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002706 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002707 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002708 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002709 }
Gabor Greif8629f122010-07-12 10:59:23 +00002710 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002711
Chris Lattner9aada1d2008-07-13 21:53:26 +00002712 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002713 return true;
2714 }
2715 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002716
Philip Reamesb42db212015-10-14 22:46:19 +00002717 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2718 if (CE->canTrap())
2719 return false;
2720
Philip Reames846e3e42015-10-29 03:11:49 +00002721 // If BI is reached from the true path of PBI and PBI's condition implies
2722 // BI's condition, we know the direction of the BI branch.
2723 if (PBI->getSuccessor(0) == BI->getParent() &&
Sanjoy Das55ea67c2015-11-06 19:01:08 +00002724 isImpliedCondition(PBI->getCondition(), BI->getCondition(), DL) &&
Philip Reames846e3e42015-10-29 03:11:49 +00002725 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
2726 BB->getSinglePredecessor()) {
2727 // Turn this into a branch on constant.
2728 auto *OldCond = BI->getCondition();
2729 BI->setCondition(ConstantInt::getTrue(BB->getContext()));
2730 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
2731 return true; // Nuke the branch on constant.
2732 }
2733
James Molloy4de84dd2015-11-04 15:28:04 +00002734 // If both branches are conditional and both contain stores to the same
2735 // address, remove the stores from the conditionals and create a conditional
2736 // merged store at the end.
2737 if (MergeCondStores && mergeConditionalStores(PBI, BI))
2738 return true;
2739
Chris Lattner9aada1d2008-07-13 21:53:26 +00002740 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002741 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002742 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002743 BasicBlock::iterator BBI = BB->begin();
2744 // Ignore dbg intrinsics.
2745 while (isa<DbgInfoIntrinsic>(BBI))
2746 ++BBI;
2747 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002748 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002749
Chris Lattner834ab4e2008-07-13 22:04:41 +00002750 int PBIOp, BIOp;
Richard Trieu7a083812016-02-18 22:09:30 +00002751 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
2752 PBIOp = 0;
2753 BIOp = 0;
2754 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
2755 PBIOp = 0;
2756 BIOp = 1;
2757 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
2758 PBIOp = 1;
2759 BIOp = 0;
2760 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
2761 PBIOp = 1;
2762 BIOp = 1;
2763 } else {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002764 return false;
Richard Trieu7a083812016-02-18 22:09:30 +00002765 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002766
Chris Lattner834ab4e2008-07-13 22:04:41 +00002767 // Check to make sure that the other destination of this branch
2768 // isn't BB itself. If so, this is an infinite loop that will
2769 // keep getting unwound.
2770 if (PBI->getSuccessor(PBIOp) == BB)
2771 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002772
2773 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002774 // insertion of a large number of select instructions. For targets
2775 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002776
Sanjay Patela932da82014-07-07 21:19:00 +00002777 // Also do not perform this transformation if any phi node in the common
2778 // destination block can trap when reached by BB or PBB (PR17073). In that
2779 // case, it would be unsafe to hoist the operation into a select instruction.
2780
2781 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002782 unsigned NumPhis = 0;
2783 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002784 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002785 if (NumPhis > 2) // Disable this xform.
2786 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002787
Sanjay Patela932da82014-07-07 21:19:00 +00002788 PHINode *PN = cast<PHINode>(II);
2789 Value *BIV = PN->getIncomingValueForBlock(BB);
2790 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2791 if (CE->canTrap())
2792 return false;
2793
2794 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2795 Value *PBIV = PN->getIncomingValue(PBBIdx);
2796 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2797 if (CE->canTrap())
2798 return false;
2799 }
2800
Chris Lattner834ab4e2008-07-13 22:04:41 +00002801 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002802 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002803
David Greene725c7c32010-01-05 01:26:52 +00002804 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002805 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002806
2807
Chris Lattner80b03a12008-07-13 22:23:11 +00002808 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2809 // branch in it, where one edge (OtherDest) goes back to itself but the other
2810 // exits. We don't *know* that the program avoids the infinite loop
2811 // (even though that seems likely). If we do this xform naively, we'll end up
2812 // recursively unpeeling the loop. Since we know that (after the xform is
2813 // done) that the block *is* infinite if reached, we just make it an obviously
2814 // infinite loop with no cond branch.
2815 if (OtherDest == BB) {
2816 // Insert it at the end of the function, because it's either code,
2817 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002818 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2819 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002820 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2821 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002822 }
2823
David Greene725c7c32010-01-05 01:26:52 +00002824 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002825
Chris Lattner834ab4e2008-07-13 22:04:41 +00002826 // BI may have other predecessors. Because of this, we leave
2827 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002828
Chris Lattner834ab4e2008-07-13 22:04:41 +00002829 // Make sure we get to CommonDest on True&True directions.
2830 Value *PBICond = PBI->getCondition();
Eric Christopher35abd052016-03-12 01:47:22 +00002831 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002832 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002833 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2834
Chris Lattner834ab4e2008-07-13 22:04:41 +00002835 Value *BICond = BI->getCondition();
2836 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002837 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2838
Chris Lattner834ab4e2008-07-13 22:04:41 +00002839 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002840 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002841
Chris Lattner834ab4e2008-07-13 22:04:41 +00002842 // Modify PBI to branch on the new condition to the new dests.
2843 PBI->setCondition(Cond);
2844 PBI->setSuccessor(0, CommonDest);
2845 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002846
Manman Ren2d4c10f2012-09-17 21:30:40 +00002847 // Update branch weight for PBI.
2848 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002849 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2850 PredFalseWeight);
2851 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2852 SuccFalseWeight);
Manman Ren2d4c10f2012-09-17 21:30:40 +00002853 if (PredHasWeights && SuccHasWeights) {
2854 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2855 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2856 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2857 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2858 // The weight to CommonDest should be PredCommon * SuccTotal +
2859 // PredOther * SuccCommon.
2860 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00002861 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2862 PredOther * SuccCommon,
2863 PredOther * SuccOther};
Manman Ren2d4c10f2012-09-17 21:30:40 +00002864 // Halve the weights if any of them cannot fit in an uint32_t
2865 FitWeights(NewWeights);
2866
Manman Ren2d4c10f2012-09-17 21:30:40 +00002867 PBI->setMetadata(LLVMContext::MD_prof,
Benjamin Kramerea68a942015-02-19 15:26:17 +00002868 MDBuilder(BI->getContext())
2869 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00002870 }
2871
Chris Lattner834ab4e2008-07-13 22:04:41 +00002872 // OtherDest may have phi nodes. If so, add an entry from PBI's
2873 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002874 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002875
Chris Lattner834ab4e2008-07-13 22:04:41 +00002876 // We know that the CommonDest already had an edge from PBI to
2877 // it. If it has PHIs though, the PHIs may have different
2878 // entries for BB and PBI's BB. If so, insert a select to make
2879 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002880 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002881 for (BasicBlock::iterator II = CommonDest->begin();
2882 (PN = dyn_cast<PHINode>(II)); ++II) {
2883 Value *BIV = PN->getIncomingValueForBlock(BB);
2884 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2885 Value *PBIV = PN->getIncomingValue(PBBIdx);
2886 if (BIV != PBIV) {
2887 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002888 Value *NV = cast<SelectInst>
Sanjay Patel2e002772016-03-12 18:05:53 +00002889 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002890 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002891 }
2892 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002893
David Greene725c7c32010-01-05 01:26:52 +00002894 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2895 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002896
Chris Lattner834ab4e2008-07-13 22:04:41 +00002897 // This basic block is probably dead. We know it has at least
2898 // one fewer predecessor.
2899 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002900}
2901
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002902// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2903// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00002904// Takes care of updating the successors and removing the old terminator.
2905// Also makes sure not to introduce new successors by assuming that edges to
2906// non-successor TrueBBs and FalseBBs aren't reachable.
2907static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002908 BasicBlock *TrueBB, BasicBlock *FalseBB,
2909 uint32_t TrueWeight,
2910 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002911 // Remove any superfluous successor edges from the CFG.
2912 // First, figure out which successors to preserve.
2913 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2914 // successor.
2915 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002916 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002917
2918 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00002919 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002920 // Make sure only to keep exactly one copy of each edge.
2921 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002922 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002923 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002924 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002925 else
David Majnemerdc3b67b2015-10-21 18:22:24 +00002926 Succ->removePredecessor(OldTerm->getParent(),
2927 /*DontDeleteUselessPHIs=*/true);
Frits van Bommel8e158492011-01-11 12:52:11 +00002928 }
2929
Devang Patel2c2ea222011-05-18 18:43:31 +00002930 IRBuilder<> Builder(OldTerm);
2931 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2932
Frits van Bommel8e158492011-01-11 12:52:11 +00002933 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002934 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002935 if (TrueBB == FalseBB)
2936 // We were only looking for one successor, and it was present.
2937 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002938 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002939 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002940 // We found both of the successors we were looking for.
2941 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002942 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2943 if (TrueWeight != FalseWeight)
2944 NewBI->setMetadata(LLVMContext::MD_prof,
2945 MDBuilder(OldTerm->getContext()).
2946 createBranchWeights(TrueWeight, FalseWeight));
2947 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002948 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2949 // Neither of the selected blocks were successors, so this
2950 // terminator must be unreachable.
2951 new UnreachableInst(OldTerm->getContext(), OldTerm);
2952 } else {
2953 // One of the selected values was a successor, but the other wasn't.
2954 // Insert an unconditional branch to the one that was found;
2955 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002956 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002957 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002958 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002959 else
2960 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002961 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002962 }
2963
2964 EraseTerminatorInstAndDCECond(OldTerm);
2965 return true;
2966}
2967
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002968// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00002969// (switch (select cond, X, Y)) on constant X, Y
2970// with a branch - conditional if X and Y lead to distinct BBs,
2971// unconditional otherwise.
2972static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2973 // Check for constant integer values in the select.
2974 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2975 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2976 if (!TrueVal || !FalseVal)
2977 return false;
2978
2979 // Find the relevant condition and destinations.
2980 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002981 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2982 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002983
Manman Ren774246a2012-09-17 22:28:55 +00002984 // Get weight for TrueBB and FalseBB.
2985 uint32_t TrueWeight = 0, FalseWeight = 0;
2986 SmallVector<uint64_t, 8> Weights;
2987 bool HasWeights = HasBranchWeights(SI);
2988 if (HasWeights) {
2989 GetBranchWeights(SI, Weights);
2990 if (Weights.size() == 1 + SI->getNumCases()) {
2991 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2992 getSuccessorIndex()];
2993 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2994 getSuccessorIndex()];
2995 }
2996 }
2997
Frits van Bommel8ae07992011-02-28 09:44:07 +00002998 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002999 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
3000 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00003001}
3002
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003003// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003004// (indirectbr (select cond, blockaddress(@fn, BlockA),
3005// blockaddress(@fn, BlockB)))
3006// with
3007// (br cond, BlockA, BlockB).
3008static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
3009 // Check that both operands of the select are block addresses.
3010 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3011 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3012 if (!TBA || !FBA)
3013 return false;
3014
3015 // Extract the actual blocks.
3016 BasicBlock *TrueBB = TBA->getBasicBlock();
3017 BasicBlock *FalseBB = FBA->getBasicBlock();
3018
Frits van Bommel8e158492011-01-11 12:52:11 +00003019 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00003020 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
3021 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003022}
3023
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003024/// This is called when we find an icmp instruction
3025/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003026/// block that ends with an uncond branch. We are looking for a very specific
3027/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3028/// this case, we merge the first two "or's of icmp" into a switch, but then the
3029/// default value goes to an uncond block with a seteq in it, we get something
3030/// like:
3031///
3032/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3033/// DEFAULT:
3034/// %tmp = icmp eq i8 %A, 92
3035/// br label %end
3036/// end:
3037/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00003038///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003039/// We prefer to split the edge to 'end' so that there is a true/false entry to
3040/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003041static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003042 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
3043 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
3044 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003045 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00003046
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003047 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3048 // complex.
3049 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
3050
3051 Value *V = ICI->getOperand(0);
3052 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00003053
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003054 // The pattern we're looking for is where our only predecessor is a switch on
3055 // 'V' and this block is the default case for the switch. In this case we can
3056 // fold the compared value into the switch to simplify things.
3057 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00003058 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003059
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003060 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3061 if (SI->getCondition() != V)
3062 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003063
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003064 // If BB is reachable on a non-default case, then we simply know the value of
3065 // V in this block. Substitute it and constant fold the icmp instruction
3066 // away.
3067 if (SI->getDefaultDest() != BB) {
3068 ConstantInt *VVal = SI->findCaseDest(BB);
3069 assert(VVal && "Should have a unique destination value");
3070 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003071
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003072 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00003073 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003074 ICI->eraseFromParent();
3075 }
3076 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003077 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003078 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003079
Chris Lattner62cc76e2010-12-13 03:43:57 +00003080 // Ok, the block is reachable from the default dest. If the constant we're
3081 // comparing exists in one of the other edges, then we can constant fold ICI
3082 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003083 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00003084 Value *V;
3085 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3086 V = ConstantInt::getFalse(BB->getContext());
3087 else
3088 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003089
Chris Lattner62cc76e2010-12-13 03:43:57 +00003090 ICI->replaceAllUsesWith(V);
3091 ICI->eraseFromParent();
3092 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003093 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00003094 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003095
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003096 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3097 // the block.
3098 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003099 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00003100 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003101 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3102 return false;
3103
3104 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3105 // true in the PHI.
3106 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3107 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3108
3109 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3110 std::swap(DefaultCst, NewCst);
3111
3112 // Replace ICI (which is used by the PHI for the default value) with true or
3113 // false depending on if it is EQ or NE.
3114 ICI->replaceAllUsesWith(DefaultCst);
3115 ICI->eraseFromParent();
3116
3117 // Okay, the switch goes to this block on a default value. Add an edge from
3118 // the switch to the merge point on the compared value.
3119 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
3120 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00003121 SmallVector<uint64_t, 8> Weights;
3122 bool HasWeights = HasBranchWeights(SI);
3123 if (HasWeights) {
3124 GetBranchWeights(SI, Weights);
3125 if (Weights.size() == 1 + SI->getNumCases()) {
3126 // Split weight for default case to case for "Cst".
3127 Weights[0] = (Weights[0]+1) >> 1;
3128 Weights.push_back(Weights[0]);
3129
3130 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3131 SI->setMetadata(LLVMContext::MD_prof,
3132 MDBuilder(SI->getContext()).
3133 createBranchWeights(MDWeights));
3134 }
3135 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003136 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003137
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003138 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00003139 Builder.SetInsertPoint(NewBB);
3140 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3141 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003142 PHIUse->addIncoming(NewCst, NewBB);
3143 return true;
3144}
3145
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003146/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003147/// Check to see if it is branching on an or/and chain of icmp instructions, and
3148/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003149static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3150 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003151 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00003152 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003153
Chris Lattnera69c4432010-12-13 05:03:41 +00003154 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3155 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3156 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003157
Mehdi Amini9a25cb82014-11-19 20:09:11 +00003158 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00003159 ConstantComparesGatherer ConstantCompare(Cond, DL);
3160 // Unpack the result
3161 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
3162 Value *CompVal = ConstantCompare.CompValue;
3163 unsigned UsedICmps = ConstantCompare.UsedICmps;
3164 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003165
Chris Lattnera69c4432010-12-13 05:03:41 +00003166 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00003167 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00003168
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003169 // Avoid turning single icmps into a switch.
3170 if (UsedICmps <= 1)
3171 return false;
3172
Mehdi Aminiffd01002014-11-20 22:40:25 +00003173 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3174
Chris Lattnera69c4432010-12-13 05:03:41 +00003175 // There might be duplicate constants in the list, which the switch
3176 // instruction can't handle, remove them now.
3177 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3178 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003179
Chris Lattnera69c4432010-12-13 05:03:41 +00003180 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00003181 // transformation. A switch with one value is just a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003182 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003183
Andrew Trick3051aa12012-08-29 21:46:38 +00003184 // TODO: Preserve branch weight metadata, similarly to how
3185 // FoldValueComparisonIntoPredecessors preserves it.
3186
Chris Lattnera69c4432010-12-13 05:03:41 +00003187 // Figure out which block is which destination.
3188 BasicBlock *DefaultBB = BI->getSuccessor(1);
3189 BasicBlock *EdgeBB = BI->getSuccessor(0);
3190 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003191
Chris Lattnera69c4432010-12-13 05:03:41 +00003192 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003193
Chris Lattnerd7beca32010-12-14 06:17:25 +00003194 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003195 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003196
Chris Lattnera69c4432010-12-13 05:03:41 +00003197 // If there are any extra values that couldn't be folded into the switch
3198 // then we evaluate them with an explicit branch first. Split the block
3199 // right before the condbr to handle it.
3200 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003201 BasicBlock *NewBB =
3202 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00003203 // Remove the uncond branch added to the old block.
3204 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00003205 Builder.SetInsertPoint(OldTI);
3206
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003207 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00003208 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003209 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00003210 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003211
Chris Lattnera69c4432010-12-13 05:03:41 +00003212 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003213
Chris Lattnercb570f82010-12-13 05:34:18 +00003214 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3215 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003216 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003217
Chris Lattnerd7beca32010-12-14 06:17:25 +00003218 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
3219 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00003220 BB = NewBB;
3221 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00003222
3223 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00003224 // Convert pointer to int before we switch.
3225 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003226 CompVal = Builder.CreatePtrToInt(
3227 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00003228 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003229
Chris Lattnera69c4432010-12-13 05:03:41 +00003230 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00003231 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00003232
Chris Lattnera69c4432010-12-13 05:03:41 +00003233 // Add all of the 'cases' to the switch instruction.
3234 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3235 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003236
Chris Lattnera69c4432010-12-13 05:03:41 +00003237 // We added edges from PI to the EdgeBB. As such, if there were any
3238 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3239 // the number of edges added.
3240 for (BasicBlock::iterator BBI = EdgeBB->begin();
3241 isa<PHINode>(BBI); ++BBI) {
3242 PHINode *PN = cast<PHINode>(BBI);
3243 Value *InVal = PN->getIncomingValueForBlock(BB);
3244 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
3245 PN->addIncoming(InVal, BB);
3246 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003247
Chris Lattnera69c4432010-12-13 05:03:41 +00003248 // Erase the old branch instruction.
3249 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003250
Chris Lattnerd7beca32010-12-14 06:17:25 +00003251 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00003252 return true;
3253}
3254
Duncan Sands29192d02011-09-05 12:57:57 +00003255bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
Chen Li1689c2f2016-01-10 05:48:01 +00003256 if (isa<PHINode>(RI->getValue()))
3257 return SimplifyCommonResume(RI);
3258 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3259 RI->getValue() == RI->getParent()->getFirstNonPHI())
3260 // The resume must unwind the exception that caused control to branch here.
3261 return SimplifySingleResume(RI);
Chen Li509ff212016-01-11 19:20:53 +00003262
3263 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003264}
3265
3266// Simplify resume that is shared by several landing pads (phi of landing pad).
3267bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3268 BasicBlock *BB = RI->getParent();
3269
3270 // Check that there are no other instructions except for debug intrinsics
3271 // between the phi of landing pads (RI->getValue()) and resume instruction.
3272 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
3273 E = RI->getIterator();
3274 while (++I != E)
3275 if (!isa<DbgInfoIntrinsic>(I))
3276 return false;
3277
3278 SmallSet<BasicBlock *, 4> TrivialUnwindBlocks;
3279 auto *PhiLPInst = cast<PHINode>(RI->getValue());
3280
3281 // Check incoming blocks to see if any of them are trivial.
3282 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues();
3283 Idx != End; Idx++) {
3284 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3285 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3286
3287 // If the block has other successors, we can not delete it because
3288 // it has other dependents.
3289 if (IncomingBB->getUniqueSuccessor() != BB)
3290 continue;
3291
3292 auto *LandingPad =
3293 dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
3294 // Not the landing pad that caused the control to branch here.
3295 if (IncomingValue != LandingPad)
3296 continue;
3297
3298 bool isTrivial = true;
3299
3300 I = IncomingBB->getFirstNonPHI()->getIterator();
3301 E = IncomingBB->getTerminator()->getIterator();
3302 while (++I != E)
3303 if (!isa<DbgInfoIntrinsic>(I)) {
3304 isTrivial = false;
3305 break;
3306 }
3307
3308 if (isTrivial)
3309 TrivialUnwindBlocks.insert(IncomingBB);
3310 }
3311
3312 // If no trivial unwind blocks, don't do any simplifications.
3313 if (TrivialUnwindBlocks.empty()) return false;
3314
3315 // Turn all invokes that unwind here into calls.
3316 for (auto *TrivialBB : TrivialUnwindBlocks) {
3317 // Blocks that will be simplified should be removed from the phi node.
3318 // Note there could be multiple edges to the resume block, and we need
3319 // to remove them all.
3320 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3321 BB->removePredecessor(TrivialBB, true);
3322
3323 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3324 PI != PE;) {
3325 BasicBlock *Pred = *PI++;
3326 removeUnwindEdge(Pred);
3327 }
3328
3329 // In each SimplifyCFG run, only the current processed block can be erased.
3330 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3331 // of erasing TrivialBB, we only remove the branch to the common resume
3332 // block so that we can later erase the resume block since it has no
3333 // predecessors.
3334 TrivialBB->getTerminator()->eraseFromParent();
3335 new UnreachableInst(RI->getContext(), TrivialBB);
3336 }
3337
3338 // Delete the resume block if all its predecessors have been removed.
3339 if (pred_empty(BB))
3340 BB->eraseFromParent();
3341
3342 return !TrivialUnwindBlocks.empty();
3343}
3344
3345// Simplify resume that is only used by a single (non-phi) landing pad.
3346bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
Duncan Sands29192d02011-09-05 12:57:57 +00003347 BasicBlock *BB = RI->getParent();
3348 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
Chen Li1689c2f2016-01-10 05:48:01 +00003349 assert (RI->getValue() == LPInst &&
3350 "Resume must unwind the exception that caused control to here");
Duncan Sands29192d02011-09-05 12:57:57 +00003351
Chen Li7009cd32015-10-23 21:13:01 +00003352 // Check that there are no other instructions except for debug intrinsics.
3353 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
Duncan Sands29192d02011-09-05 12:57:57 +00003354 while (++I != E)
3355 if (!isa<DbgInfoIntrinsic>(I))
3356 return false;
3357
Chen Lic6e28782015-10-22 20:48:38 +00003358 // Turn all invokes that unwind here into calls and delete the basic block.
Chen Li7009cd32015-10-23 21:13:01 +00003359 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3360 BasicBlock *Pred = *PI++;
3361 removeUnwindEdge(Pred);
Chen Lic6e28782015-10-22 20:48:38 +00003362 }
3363
Chen Li7009cd32015-10-23 21:13:01 +00003364 // The landingpad is now unreachable. Zap it.
3365 BB->eraseFromParent();
3366 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00003367}
3368
David Majnemer1efa23d2016-02-20 01:07:45 +00003369static bool removeEmptyCleanup(CleanupReturnInst *RI) {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003370 // If this is a trivial cleanup pad that executes no instructions, it can be
3371 // eliminated. If the cleanup pad continues to the caller, any predecessor
3372 // that is an EH pad will be updated to continue to the caller and any
3373 // predecessor that terminates with an invoke instruction will have its invoke
3374 // instruction converted to a call instruction. If the cleanup pad being
3375 // simplified does not continue to the caller, each predecessor will be
3376 // updated to continue to the unwind destination of the cleanup pad being
3377 // simplified.
3378 BasicBlock *BB = RI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003379 CleanupPadInst *CPInst = RI->getCleanupPad();
3380 if (CPInst->getParent() != BB)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003381 // This isn't an empty cleanup.
3382 return false;
3383
3384 // Check that there are no other instructions except for debug intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003385 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003386 while (++I != E)
3387 if (!isa<DbgInfoIntrinsic>(I))
3388 return false;
3389
David Majnemer8a1c45d2015-12-12 05:38:55 +00003390 // If the cleanup return we are simplifying unwinds to the caller, this will
3391 // set UnwindDest to nullptr.
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003392 BasicBlock *UnwindDest = RI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003393 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003394
3395 // We're about to remove BB from the control flow. Before we do, sink any
3396 // PHINodes into the unwind destination. Doing this before changing the
3397 // control flow avoids some potentially slow checks, since we can currently
3398 // be certain that UnwindDest and BB have no common predecessors (since they
3399 // are both EH pads).
3400 if (UnwindDest) {
3401 // First, go through the PHI nodes in UnwindDest and update any nodes that
3402 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003403 for (BasicBlock::iterator I = UnwindDest->begin(),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003404 IE = DestEHPad->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003405 I != IE; ++I) {
3406 PHINode *DestPN = cast<PHINode>(I);
James Molloy4de84dd2015-11-04 15:28:04 +00003407
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003408 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003409 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003410 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003411 // This PHI node has an incoming value that corresponds to a control
3412 // path through the cleanup pad we are removing. If the incoming
3413 // value is in the cleanup pad, it must be a PHINode (because we
3414 // verified above that the block is otherwise empty). Otherwise, the
3415 // value is either a constant or a value that dominates the cleanup
3416 // pad being removed.
3417 //
3418 // Because BB and UnwindDest are both EH pads, all of their
3419 // predecessors must unwind to these blocks, and since no instruction
3420 // can have multiple unwind destinations, there will be no overlap in
3421 // incoming blocks between SrcPN and DestPN.
3422 Value *SrcVal = DestPN->getIncomingValue(Idx);
3423 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3424
3425 // Remove the entry for the block we are deleting.
3426 DestPN->removeIncomingValue(Idx, false);
3427
3428 if (SrcPN && SrcPN->getParent() == BB) {
3429 // If the incoming value was a PHI node in the cleanup pad we are
3430 // removing, we need to merge that PHI node's incoming values into
3431 // DestPN.
James Molloy4de84dd2015-11-04 15:28:04 +00003432 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003433 SrcIdx != SrcE; ++SrcIdx) {
3434 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3435 SrcPN->getIncomingBlock(SrcIdx));
3436 }
3437 } else {
3438 // Otherwise, the incoming value came from above BB and
3439 // so we can just reuse it. We must associate all of BB's
3440 // predecessors with this value.
3441 for (auto *pred : predecessors(BB)) {
3442 DestPN->addIncoming(SrcVal, pred);
3443 }
3444 }
3445 }
3446
3447 // Sink any remaining PHI nodes directly into UnwindDest.
David Majnemer8a1c45d2015-12-12 05:38:55 +00003448 Instruction *InsertPt = DestEHPad;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003449 for (BasicBlock::iterator I = BB->begin(),
3450 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003451 I != IE;) {
3452 // The iterator must be incremented here because the instructions are
3453 // being moved to another block.
3454 PHINode *PN = cast<PHINode>(I++);
3455 if (PN->use_empty())
3456 // If the PHI node has no uses, just leave it. It will be erased
3457 // when we erase BB below.
3458 continue;
3459
3460 // Otherwise, sink this PHI node into UnwindDest.
3461 // Any predecessors to UnwindDest which are not already represented
3462 // must be back edges which inherit the value from the path through
3463 // BB. In this case, the PHI value must reference itself.
3464 for (auto *pred : predecessors(UnwindDest))
3465 if (pred != BB)
3466 PN->addIncoming(PN, pred);
3467 PN->moveBefore(InsertPt);
3468 }
3469 }
3470
3471 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3472 // The iterator must be updated here because we are removing this pred.
3473 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003474 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003475 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003476 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003477 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003478 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003479 }
3480 }
3481
3482 // The cleanup pad is now unreachable. Zap it.
3483 BB->eraseFromParent();
3484 return true;
3485}
3486
David Majnemer1efa23d2016-02-20 01:07:45 +00003487// Try to merge two cleanuppads together.
3488static bool mergeCleanupPad(CleanupReturnInst *RI) {
3489 // Skip any cleanuprets which unwind to caller, there is nothing to merge
3490 // with.
3491 BasicBlock *UnwindDest = RI->getUnwindDest();
3492 if (!UnwindDest)
3493 return false;
3494
3495 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
3496 // be safe to merge without code duplication.
3497 if (UnwindDest->getSinglePredecessor() != RI->getParent())
3498 return false;
3499
3500 // Verify that our cleanuppad's unwind destination is another cleanuppad.
3501 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
3502 if (!SuccessorCleanupPad)
3503 return false;
3504
3505 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
3506 // Replace any uses of the successor cleanupad with the predecessor pad
3507 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
3508 // funclet bundle operands.
3509 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
3510 // Remove the old cleanuppad.
3511 SuccessorCleanupPad->eraseFromParent();
3512 // Now, we simply replace the cleanupret with a branch to the unwind
3513 // destination.
3514 BranchInst::Create(UnwindDest, RI->getParent());
3515 RI->eraseFromParent();
3516
3517 return true;
3518}
3519
3520bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00003521 // It is possible to transiantly have an undef cleanuppad operand because we
3522 // have deleted some, but not all, dead blocks.
3523 // Eventually, this block will be deleted.
3524 if (isa<UndefValue>(RI->getOperand(0)))
3525 return false;
3526
David Majnemer1efa23d2016-02-20 01:07:45 +00003527 if (removeEmptyCleanup(RI))
3528 return true;
3529
3530 if (mergeCleanupPad(RI))
3531 return true;
3532
3533 return false;
3534}
3535
Devang Pateldd14e0f2011-05-18 21:33:11 +00003536bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003537 BasicBlock *BB = RI->getParent();
3538 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003539
Chris Lattner25c3af32010-12-13 06:25:44 +00003540 // Find predecessors that end with branches.
3541 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3542 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003543 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3544 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003545 TerminatorInst *PTI = P->getTerminator();
3546 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3547 if (BI->isUnconditional())
3548 UncondBranchPreds.push_back(P);
3549 else
3550 CondBranchPreds.push_back(BI);
3551 }
3552 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003553
Chris Lattner25c3af32010-12-13 06:25:44 +00003554 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00003555 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003556 while (!UncondBranchPreds.empty()) {
3557 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3558 DEBUG(dbgs() << "FOLDING: " << *BB
3559 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00003560 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00003561 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003562
Chris Lattner25c3af32010-12-13 06:25:44 +00003563 // If we eliminated all predecessors of the block, delete the block now.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003564 if (pred_empty(BB))
Chris Lattner25c3af32010-12-13 06:25:44 +00003565 // We know there are no successors, so just nuke the block.
3566 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003567
Chris Lattner25c3af32010-12-13 06:25:44 +00003568 return true;
3569 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003570
Chris Lattner25c3af32010-12-13 06:25:44 +00003571 // Check out all of the conditional branches going to this return
3572 // instruction. If any of them just select between returns, change the
3573 // branch itself into a select/return pair.
3574 while (!CondBranchPreds.empty()) {
3575 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003576
Chris Lattner25c3af32010-12-13 06:25:44 +00003577 // Check to see if the non-BB successor is also a return block.
3578 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3579 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003580 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003581 return true;
3582 }
3583 return false;
3584}
3585
Chris Lattner25c3af32010-12-13 06:25:44 +00003586bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3587 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003588
Chris Lattner25c3af32010-12-13 06:25:44 +00003589 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003590
Chris Lattner25c3af32010-12-13 06:25:44 +00003591 // If there are any instructions immediately before the unreachable that can
3592 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003593 while (UI->getIterator() != BB->begin()) {
3594 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00003595 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003596 // Do not delete instructions that can have side effects which might cause
3597 // the unreachable to not be reachable; specifically, calls and volatile
3598 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003599 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003600
3601 if (BBI->mayHaveSideEffects()) {
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003602 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003603 if (SI->isVolatile())
3604 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003605 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003606 if (LI->isVolatile())
3607 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003608 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003609 if (RMWI->isVolatile())
3610 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003611 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003612 if (CXI->isVolatile())
3613 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003614 } else if (isa<CatchPadInst>(BBI)) {
3615 // A catchpad may invoke exception object constructors and such, which
3616 // in some languages can be arbitrary code, so be conservative by
3617 // default.
3618 // For CoreCLR, it just involves a type test, so can be removed.
3619 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
3620 EHPersonality::CoreCLR)
3621 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003622 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3623 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003624 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003625 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003626 // Note that deleting LandingPad's here is in fact okay, although it
3627 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3628 // all the predecessors of this block will be the unwind edges of Invokes,
3629 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003630 }
3631
Eli Friedmanaac35b32011-03-09 00:48:33 +00003632 // Delete this instruction (any uses are guaranteed to be dead)
3633 if (!BBI->use_empty())
3634 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003635 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003636 Changed = true;
3637 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003638
Chris Lattner25c3af32010-12-13 06:25:44 +00003639 // If the unreachable instruction is the first in the block, take a gander
3640 // at all of the predecessors of this instruction, and simplify them.
3641 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003642
Chris Lattner25c3af32010-12-13 06:25:44 +00003643 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3644 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3645 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003646 IRBuilder<> Builder(TI);
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003647 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003648 if (BI->isUnconditional()) {
3649 if (BI->getSuccessor(0) == BB) {
3650 new UnreachableInst(TI->getContext(), TI);
3651 TI->eraseFromParent();
3652 Changed = true;
3653 }
3654 } else {
3655 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003656 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003657 EraseTerminatorInstAndDCECond(BI);
3658 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003659 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003660 EraseTerminatorInstAndDCECond(BI);
3661 Changed = true;
3662 }
3663 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003664 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003665 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003666 i != e; ++i)
3667 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003668 BB->removePredecessor(SI->getParent());
3669 SI->removeCase(i);
3670 --i; --e;
3671 Changed = true;
3672 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003673 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
3674 if (II->getUnwindDest() == BB) {
3675 removeUnwindEdge(TI->getParent());
3676 Changed = true;
3677 }
3678 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3679 if (CSI->getUnwindDest() == BB) {
3680 removeUnwindEdge(TI->getParent());
3681 Changed = true;
3682 continue;
3683 }
3684
3685 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
3686 E = CSI->handler_end();
3687 I != E; ++I) {
3688 if (*I == BB) {
3689 CSI->removeHandler(I);
3690 --I;
3691 --E;
3692 Changed = true;
3693 }
3694 }
3695 if (CSI->getNumHandlers() == 0) {
3696 BasicBlock *CatchSwitchBB = CSI->getParent();
3697 if (CSI->hasUnwindDest()) {
3698 // Redirect preds to the unwind dest
3699 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
3700 } else {
3701 // Rewrite all preds to unwind to caller (or from invoke to call).
3702 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
3703 for (BasicBlock *EHPred : EHPreds)
3704 removeUnwindEdge(EHPred);
3705 }
3706 // The catchswitch is no longer reachable.
3707 new UnreachableInst(CSI->getContext(), CSI);
3708 CSI->eraseFromParent();
3709 Changed = true;
3710 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003711 } else if (isa<CleanupReturnInst>(TI)) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003712 new UnreachableInst(TI->getContext(), TI);
3713 TI->eraseFromParent();
3714 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00003715 }
3716 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003717
Chris Lattner25c3af32010-12-13 06:25:44 +00003718 // If this block is now dead, remove it.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003719 if (pred_empty(BB) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00003720 BB != &BB->getParent()->getEntryBlock()) {
3721 // We know there are no successors, so just nuke the block.
3722 BB->eraseFromParent();
3723 return true;
3724 }
3725
3726 return Changed;
3727}
3728
Hans Wennborg68000082015-01-26 19:52:32 +00003729static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3730 assert(Cases.size() >= 1);
3731
3732 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3733 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3734 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3735 return false;
3736 }
3737 return true;
3738}
3739
3740/// Turn a switch with two reachable destinations into an integer range
3741/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003742static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003743 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003744
Hans Wennborg68000082015-01-26 19:52:32 +00003745 bool HasDefault =
3746 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003747
Hans Wennborg68000082015-01-26 19:52:32 +00003748 // Partition the cases into two sets with different destinations.
3749 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3750 BasicBlock *DestB = nullptr;
3751 SmallVector <ConstantInt *, 16> CasesA;
3752 SmallVector <ConstantInt *, 16> CasesB;
3753
3754 for (SwitchInst::CaseIt I : SI->cases()) {
3755 BasicBlock *Dest = I.getCaseSuccessor();
3756 if (!DestA) DestA = Dest;
3757 if (Dest == DestA) {
3758 CasesA.push_back(I.getCaseValue());
3759 continue;
3760 }
3761 if (!DestB) DestB = Dest;
3762 if (Dest == DestB) {
3763 CasesB.push_back(I.getCaseValue());
3764 continue;
3765 }
3766 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003767 }
3768
Hans Wennborg68000082015-01-26 19:52:32 +00003769 assert(DestA && DestB && "Single-destination switch should have been folded.");
3770 assert(DestA != DestB);
3771 assert(DestB != SI->getDefaultDest());
3772 assert(!CasesB.empty() && "There must be non-default cases.");
3773 assert(!CasesA.empty() || HasDefault);
3774
3775 // Figure out if one of the sets of cases form a contiguous range.
3776 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3777 BasicBlock *ContiguousDest = nullptr;
3778 BasicBlock *OtherDest = nullptr;
3779 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3780 ContiguousCases = &CasesA;
3781 ContiguousDest = DestA;
3782 OtherDest = DestB;
3783 } else if (CasesAreContiguous(CasesB)) {
3784 ContiguousCases = &CasesB;
3785 ContiguousDest = DestB;
3786 OtherDest = DestA;
3787 } else
3788 return false;
3789
3790 // Start building the compare and branch.
3791
3792 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3793 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003794
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003795 Value *Sub = SI->getCondition();
3796 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00003797 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3798
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003799 Value *Cmp;
3800 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00003801 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003802 Cmp = ConstantInt::getTrue(SI->getContext());
3803 else
3804 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00003805 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003806
Manman Ren56575552012-09-18 00:47:33 +00003807 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00003808 if (HasBranchWeights(SI)) {
3809 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00003810 GetBranchWeights(SI, Weights);
3811 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00003812 uint64_t TrueWeight = 0;
3813 uint64_t FalseWeight = 0;
3814 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3815 if (SI->getSuccessor(I) == ContiguousDest)
3816 TrueWeight += Weights[I];
3817 else
3818 FalseWeight += Weights[I];
3819 }
3820 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3821 TrueWeight /= 2;
3822 FalseWeight /= 2;
3823 }
Manman Ren56575552012-09-18 00:47:33 +00003824 NewBI->setMetadata(LLVMContext::MD_prof,
Hans Wennborg68000082015-01-26 19:52:32 +00003825 MDBuilder(SI->getContext()).createBranchWeights(
3826 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00003827 }
3828 }
3829
Hans Wennborg68000082015-01-26 19:52:32 +00003830 // Prune obsolete incoming values off the successors' PHI nodes.
3831 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3832 unsigned PreviousEdges = ContiguousCases->size();
3833 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3834 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003835 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3836 }
Hans Wennborg68000082015-01-26 19:52:32 +00003837 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3838 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3839 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3840 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3841 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3842 }
3843
3844 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003845 SI->eraseFromParent();
3846
3847 return true;
3848}
Chris Lattner25c3af32010-12-13 06:25:44 +00003849
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003850/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003851/// and use it to remove dead cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003852static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3853 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003854 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003855 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003856 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003857 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003858
3859 // Gather dead cases.
3860 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003861 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003862 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3863 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3864 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003865 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003866 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003867 }
3868 }
3869
Philip Reames98a2dab2015-08-26 23:56:46 +00003870 // If we can prove that the cases must cover all possible values, the
Philip Reames05370132015-09-10 17:44:47 +00003871 // default destination becomes dead and we can remove it. If we know some
3872 // of the bits in the value, we can use that to more precisely compute the
3873 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00003874 bool HasDefault =
3875 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Philip Reames05370132015-09-10 17:44:47 +00003876 const unsigned NumUnknownBits = Bits -
3877 (KnownZero.Or(KnownOne)).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00003878 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00003879 if (HasDefault && DeadCases.empty() &&
3880 NumUnknownBits < 64 /* avoid overflow */ &&
3881 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00003882 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
3883 BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(),
3884 SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003885 SI->setDefaultDest(&*NewDefault);
3886 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00003887 auto *OldTI = NewDefault->getTerminator();
3888 new UnreachableInst(SI->getContext(), OldTI);
3889 EraseTerminatorInstAndDCECond(OldTI);
3890 return true;
3891 }
3892
Manman Ren56575552012-09-18 00:47:33 +00003893 SmallVector<uint64_t, 8> Weights;
3894 bool HasWeight = HasBranchWeights(SI);
3895 if (HasWeight) {
3896 GetBranchWeights(SI, Weights);
3897 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3898 }
3899
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003900 // Remove dead cases from the switch.
3901 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003902 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003903 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003904 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003905 if (HasWeight) {
3906 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3907 Weights.pop_back();
3908 }
3909
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003910 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003911 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003912 SI->removeCase(Case);
3913 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003914 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003915 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3916 SI->setMetadata(LLVMContext::MD_prof,
3917 MDBuilder(SI->getParent()->getContext()).
3918 createBranchWeights(MDWeights));
3919 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003920
3921 return !DeadCases.empty();
3922}
3923
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003924/// If BB would be eligible for simplification by
3925/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003926/// by an unconditional branch), look at the phi node for BB in the successor
3927/// block and see if the incoming value is equal to CaseValue. If so, return
3928/// the phi node, and set PhiIndex to BB's index in the phi node.
3929static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3930 BasicBlock *BB,
3931 int *PhiIndex) {
3932 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003933 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003934 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003935 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003936
3937 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3938 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003939 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003940
3941 BasicBlock *Succ = Branch->getSuccessor(0);
3942
3943 BasicBlock::iterator I = Succ->begin();
3944 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3945 int Idx = PHI->getBasicBlockIndex(BB);
3946 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3947
3948 Value *InValue = PHI->getIncomingValue(Idx);
3949 if (InValue != CaseValue) continue;
3950
3951 *PhiIndex = Idx;
3952 return PHI;
3953 }
3954
Craig Topperf40110f2014-04-25 05:29:35 +00003955 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003956}
3957
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003958/// Try to forward the condition of a switch instruction to a phi node
3959/// dominated by the switch, if that would mean that some of the destination
3960/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003961/// Returns true if a change is made.
3962static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3963 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3964 ForwardingNodesMap ForwardingNodes;
3965
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003966 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003967 ConstantInt *CaseValue = I.getCaseValue();
3968 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003969
3970 int PhiIndex;
3971 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3972 &PhiIndex);
3973 if (!PHI) continue;
3974
3975 ForwardingNodes[PHI].push_back(PhiIndex);
3976 }
3977
3978 bool Changed = false;
3979
3980 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3981 E = ForwardingNodes.end(); I != E; ++I) {
3982 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003983 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003984
3985 if (Indexes.size() < 2) continue;
3986
3987 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3988 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3989 Changed = true;
3990 }
3991
3992 return Changed;
3993}
3994
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003995/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003996/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003997static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003998 if (C->isThreadDependent())
3999 return false;
4000 if (C->isDLLImportDependent())
4001 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004002
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00004003 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
4004 return CE->isGEPWithNoNotionalOverIndexing();
4005
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004006 return isa<ConstantFP>(C) ||
4007 isa<ConstantInt>(C) ||
4008 isa<ConstantPointerNull>(C) ||
4009 isa<GlobalValue>(C) ||
4010 isa<UndefValue>(C);
4011}
4012
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004013/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004014/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00004015static Constant *LookupConstant(Value *V,
4016 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
4017 if (Constant *C = dyn_cast<Constant>(V))
4018 return C;
4019 return ConstantPool.lookup(V);
4020}
4021
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004022/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004023/// simple instructions such as binary operations where both operands are
4024/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004025/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00004026static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004027ConstantFold(Instruction *I, const DataLayout &DL,
4028 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004029 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00004030 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
4031 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00004032 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00004033 if (A->isAllOnesValue())
4034 return LookupConstant(Select->getTrueValue(), ConstantPool);
4035 if (A->isNullValue())
4036 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00004037 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004038 }
4039
Benjamin Kramer7c302602013-11-12 12:24:36 +00004040 SmallVector<Constant *, 4> COps;
4041 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
4042 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
4043 COps.push_back(A);
4044 else
Craig Topperf40110f2014-04-25 05:29:35 +00004045 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004046 }
4047
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004048 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00004049 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4050 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004051 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00004052
Manuel Jacobe9024592016-01-21 06:33:22 +00004053 return ConstantFoldInstOperands(I, COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004054}
4055
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004056/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004057/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004058/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004059/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00004060static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004061GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00004062 BasicBlock **CommonDest,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004063 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
4064 const DataLayout &DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004065 // The block from which we enter the common destination.
4066 BasicBlock *Pred = SI->getParent();
4067
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004068 // If CaseDest is empty except for some side-effect free instructions through
4069 // which we can constant-propagate the CaseVal, continue to its successor.
4070 SmallDenseMap<Value*, Constant*> ConstantPool;
4071 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4072 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4073 ++I) {
4074 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4075 // If the terminator is a simple branch, continue to the next block.
4076 if (T->getNumSuccessors() != 1)
4077 return false;
4078 Pred = CaseDest;
4079 CaseDest = T->getSuccessor(0);
4080 } else if (isa<DbgInfoIntrinsic>(I)) {
4081 // Skip debug intrinsic.
4082 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004083 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004084 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00004085
4086 // If the instruction has uses outside this block or a phi node slot for
4087 // the block, it is not safe to bypass the instruction since it would then
4088 // no longer dominate all its uses.
4089 for (auto &Use : I->uses()) {
4090 User *User = Use.getUser();
4091 if (Instruction *I = dyn_cast<Instruction>(User))
4092 if (I->getParent() == CaseDest)
4093 continue;
4094 if (PHINode *Phi = dyn_cast<PHINode>(User))
4095 if (Phi->getIncomingBlock(Use) == CaseDest)
4096 continue;
4097 return false;
4098 }
4099
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004100 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004101 } else {
4102 break;
4103 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004104 }
4105
4106 // If we did not have a CommonDest before, use the current one.
4107 if (!*CommonDest)
4108 *CommonDest = CaseDest;
4109 // If the destination isn't the common one, abort.
4110 if (CaseDest != *CommonDest)
4111 return false;
4112
4113 // Get the values for this case from phi nodes in the destination block.
4114 BasicBlock::iterator I = (*CommonDest)->begin();
4115 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4116 int Idx = PHI->getBasicBlockIndex(Pred);
4117 if (Idx == -1)
4118 continue;
4119
Hans Wennborg09acdb92012-10-31 15:14:39 +00004120 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
4121 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004122 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004123 return false;
4124
4125 // Be conservative about which kinds of constants we support.
4126 if (!ValidLookupTableConstant(ConstVal))
4127 return false;
4128
4129 Res.push_back(std::make_pair(PHI, ConstVal));
4130 }
4131
Hans Wennborgac114a32014-01-12 00:44:41 +00004132 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004133}
4134
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004135// Helper function used to add CaseVal to the list of cases that generate
4136// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004137static void MapCaseToResult(ConstantInt *CaseVal,
4138 SwitchCaseResultVectorTy &UniqueResults,
4139 Constant *Result) {
4140 for (auto &I : UniqueResults) {
4141 if (I.first == Result) {
4142 I.second.push_back(CaseVal);
4143 return;
4144 }
4145 }
4146 UniqueResults.push_back(std::make_pair(Result,
4147 SmallVector<ConstantInt*, 4>(1, CaseVal)));
4148}
4149
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004150// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004151// results for the PHI node of the common destination block for a switch
4152// instruction. Returns false if multiple PHI nodes have been found or if
4153// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004154static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4155 BasicBlock *&CommonDest,
4156 SwitchCaseResultVectorTy &UniqueResults,
4157 Constant *&DefaultResult,
4158 const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004159 for (auto &I : SI->cases()) {
4160 ConstantInt *CaseVal = I.getCaseValue();
4161
4162 // Resulting value at phi nodes for this case value.
4163 SwitchCaseResultsTy Results;
4164 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4165 DL))
4166 return false;
4167
4168 // Only one value per case is permitted
4169 if (Results.size() > 1)
4170 return false;
4171 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4172
4173 // Check the PHI consistency.
4174 if (!PHI)
4175 PHI = Results[0].first;
4176 else if (PHI != Results[0].first)
4177 return false;
4178 }
4179 // Find the default result value.
4180 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4181 BasicBlock *DefaultDest = SI->getDefaultDest();
4182 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4183 DL);
4184 // If the default value is not found abort unless the default destination
4185 // is unreachable.
4186 DefaultResult =
4187 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4188 if ((!DefaultResult &&
4189 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
4190 return false;
4191
4192 return true;
4193}
4194
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004195// Helper function that checks if it is possible to transform a switch with only
4196// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004197// Example:
4198// switch (a) {
4199// case 10: %0 = icmp eq i32 %a, 10
4200// return 10; %1 = select i1 %0, i32 10, i32 4
4201// case 20: ----> %2 = icmp eq i32 %a, 20
4202// return 2; %3 = select i1 %2, i32 2, i32 %1
4203// default:
4204// return 4;
4205// }
4206static Value *
4207ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4208 Constant *DefaultResult, Value *Condition,
4209 IRBuilder<> &Builder) {
4210 assert(ResultVector.size() == 2 &&
4211 "We should have exactly two unique results at this point");
4212 // If we are selecting between only two cases transform into a simple
4213 // select or a two-way select if default is possible.
4214 if (ResultVector[0].second.size() == 1 &&
4215 ResultVector[1].second.size() == 1) {
4216 ConstantInt *const FirstCase = ResultVector[0].second[0];
4217 ConstantInt *const SecondCase = ResultVector[1].second[0];
4218
4219 bool DefaultCanTrigger = DefaultResult;
4220 Value *SelectValue = ResultVector[1].first;
4221 if (DefaultCanTrigger) {
4222 Value *const ValueCompare =
4223 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4224 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4225 DefaultResult, "switch.select");
4226 }
4227 Value *const ValueCompare =
4228 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
4229 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
4230 "switch.select");
4231 }
4232
4233 return nullptr;
4234}
4235
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004236// Helper function to cleanup a switch instruction that has been converted into
4237// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004238static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4239 Value *SelectValue,
4240 IRBuilder<> &Builder) {
4241 BasicBlock *SelectBB = SI->getParent();
4242 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4243 PHI->removeIncomingValue(SelectBB);
4244 PHI->addIncoming(SelectValue, SelectBB);
4245
4246 Builder.CreateBr(PHI->getParent());
4247
4248 // Remove the switch.
4249 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4250 BasicBlock *Succ = SI->getSuccessor(i);
4251
4252 if (Succ == PHI->getParent())
4253 continue;
4254 Succ->removePredecessor(SelectBB);
4255 }
4256 SI->eraseFromParent();
4257}
4258
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004259/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004260/// phi nodes in a common successor block with only two different
4261/// constant values, replace the switch with select.
4262static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004263 AssumptionCache *AC, const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004264 Value *const Cond = SI->getCondition();
4265 PHINode *PHI = nullptr;
4266 BasicBlock *CommonDest = nullptr;
4267 Constant *DefaultResult;
4268 SwitchCaseResultVectorTy UniqueResults;
4269 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004270 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4271 DL))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004272 return false;
4273 // Selects choose between maximum two values.
4274 if (UniqueResults.size() != 2)
4275 return false;
4276 assert(PHI != nullptr && "PHI for value select not found");
4277
4278 Builder.SetInsertPoint(SI);
4279 Value *SelectValue = ConvertTwoCaseSwitch(
4280 UniqueResults,
4281 DefaultResult, Cond, Builder);
4282 if (SelectValue) {
4283 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4284 return true;
4285 }
4286 // The switch couldn't be converted into a select.
4287 return false;
4288}
4289
Hans Wennborg776d7122012-09-26 09:34:53 +00004290namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004291 /// This class represents a lookup table that can be used to replace a switch.
Hans Wennborg776d7122012-09-26 09:34:53 +00004292 class SwitchLookupTable {
4293 public:
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004294 /// Create a lookup table to use as a switch replacement with the contents
4295 /// of Values, using DefaultValue to fill any holes in the table.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004296 SwitchLookupTable(
4297 Module &M, uint64_t TableSize, ConstantInt *Offset,
4298 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4299 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004300
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004301 /// Build instructions with Builder to retrieve the value at
Hans Wennborg776d7122012-09-26 09:34:53 +00004302 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00004303 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00004304
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004305 /// Return true if a table with TableSize elements of
Hans Wennborg39583b82012-09-26 09:44:49 +00004306 /// type ElementType would fit in a target-legal register.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004307 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004308 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004309
Hans Wennborg776d7122012-09-26 09:34:53 +00004310 private:
4311 // Depending on the contents of the table, it can be represented in
4312 // different ways.
4313 enum {
4314 // For tables where each element contains the same value, we just have to
4315 // store that single value and return it for each lookup.
4316 SingleValueKind,
4317
Erik Eckstein105374f2014-11-17 09:13:57 +00004318 // For tables where there is a linear relationship between table index
4319 // and values. We calculate the result with a simple multiplication
4320 // and addition instead of a table lookup.
4321 LinearMapKind,
4322
Hans Wennborg39583b82012-09-26 09:44:49 +00004323 // For small tables with integer elements, we can pack them into a bitmap
4324 // that fits into a target-legal register. Values are retrieved by
4325 // shift and mask operations.
4326 BitMapKind,
4327
Hans Wennborg776d7122012-09-26 09:34:53 +00004328 // The table is stored as an array of values. Values are retrieved by load
4329 // instructions from the table.
4330 ArrayKind
4331 } Kind;
4332
4333 // For SingleValueKind, this is the single value.
4334 Constant *SingleValue;
4335
Hans Wennborg39583b82012-09-26 09:44:49 +00004336 // For BitMapKind, this is the bitmap.
4337 ConstantInt *BitMap;
4338 IntegerType *BitMapElementTy;
4339
Erik Eckstein105374f2014-11-17 09:13:57 +00004340 // For LinearMapKind, these are the constants used to derive the value.
4341 ConstantInt *LinearOffset;
4342 ConstantInt *LinearMultiplier;
4343
Hans Wennborg776d7122012-09-26 09:34:53 +00004344 // For ArrayKind, this is the array.
4345 GlobalVariable *Array;
4346 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +00004347}
Hans Wennborg776d7122012-09-26 09:34:53 +00004348
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004349SwitchLookupTable::SwitchLookupTable(
4350 Module &M, uint64_t TableSize, ConstantInt *Offset,
4351 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4352 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00004353 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00004354 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004355 assert(Values.size() && "Can't build lookup table without values!");
4356 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004357
4358 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00004359 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004360
Hans Wennborgac114a32014-01-12 00:44:41 +00004361 Type *ValueType = Values.begin()->second->getType();
4362
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004363 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00004364 SmallVector<Constant*, 64> TableContents(TableSize);
4365 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4366 ConstantInt *CaseVal = Values[I].first;
4367 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00004368 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004369
Hans Wennborg776d7122012-09-26 09:34:53 +00004370 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
4371 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004372 TableContents[Idx] = CaseRes;
4373
Hans Wennborg776d7122012-09-26 09:34:53 +00004374 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004375 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004376 }
4377
4378 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00004379 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00004380 assert(DefaultValue &&
4381 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00004382 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00004383 for (uint64_t I = 0; I < TableSize; ++I) {
4384 if (!TableContents[I])
4385 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004386 }
4387
Hans Wennborg776d7122012-09-26 09:34:53 +00004388 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004389 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004390 }
4391
Hans Wennborg776d7122012-09-26 09:34:53 +00004392 // If each element in the table contains the same value, we only need to store
4393 // that single value.
4394 if (SingleValue) {
4395 Kind = SingleValueKind;
4396 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004397 }
4398
Erik Eckstein105374f2014-11-17 09:13:57 +00004399 // Check if we can derive the value with a linear transformation from the
4400 // table index.
4401 if (isa<IntegerType>(ValueType)) {
4402 bool LinearMappingPossible = true;
4403 APInt PrevVal;
4404 APInt DistToPrev;
4405 assert(TableSize >= 2 && "Should be a SingleValue table.");
4406 // Check if there is the same distance between two consecutive values.
4407 for (uint64_t I = 0; I < TableSize; ++I) {
4408 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4409 if (!ConstVal) {
4410 // This is an undef. We could deal with it, but undefs in lookup tables
4411 // are very seldom. It's probably not worth the additional complexity.
4412 LinearMappingPossible = false;
4413 break;
4414 }
4415 APInt Val = ConstVal->getValue();
4416 if (I != 0) {
4417 APInt Dist = Val - PrevVal;
4418 if (I == 1) {
4419 DistToPrev = Dist;
4420 } else if (Dist != DistToPrev) {
4421 LinearMappingPossible = false;
4422 break;
4423 }
4424 }
4425 PrevVal = Val;
4426 }
4427 if (LinearMappingPossible) {
4428 LinearOffset = cast<ConstantInt>(TableContents[0]);
4429 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4430 Kind = LinearMapKind;
4431 ++NumLinearMaps;
4432 return;
4433 }
4434 }
4435
Hans Wennborg39583b82012-09-26 09:44:49 +00004436 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004437 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004438 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004439 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4440 for (uint64_t I = TableSize; I > 0; --I) {
4441 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00004442 // Insert values into the bitmap. Undef values are set to zero.
4443 if (!isa<UndefValue>(TableContents[I - 1])) {
4444 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4445 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4446 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004447 }
4448 BitMap = ConstantInt::get(M.getContext(), TableInt);
4449 BitMapElementTy = IT;
4450 Kind = BitMapKind;
4451 ++NumBitMaps;
4452 return;
4453 }
4454
Hans Wennborg776d7122012-09-26 09:34:53 +00004455 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004456 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004457 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4458
Hans Wennborg776d7122012-09-26 09:34:53 +00004459 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
4460 GlobalVariable::PrivateLinkage,
4461 Initializer,
4462 "switch.table");
4463 Array->setUnnamedAddr(true);
4464 Kind = ArrayKind;
4465}
4466
Manman Ren4d189fb2014-07-24 21:13:20 +00004467Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004468 switch (Kind) {
4469 case SingleValueKind:
4470 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00004471 case LinearMapKind: {
4472 // Derive the result value from the input value.
4473 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4474 false, "switch.idx.cast");
4475 if (!LinearMultiplier->isOne())
4476 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4477 if (!LinearOffset->isZero())
4478 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4479 return Result;
4480 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004481 case BitMapKind: {
4482 // Type of the bitmap (e.g. i59).
4483 IntegerType *MapTy = BitMap->getType();
4484
4485 // Cast Index to the same type as the bitmap.
4486 // Note: The Index is <= the number of elements in the table, so
4487 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00004488 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004489
4490 // Multiply the shift amount by the element width.
4491 ShiftAmt = Builder.CreateMul(ShiftAmt,
4492 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4493 "switch.shiftamt");
4494
4495 // Shift down.
4496 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
4497 "switch.downshift");
4498 // Mask off.
4499 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
4500 "switch.masked");
4501 }
Hans Wennborg776d7122012-09-26 09:34:53 +00004502 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00004503 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00004504 IntegerType *IT = cast<IntegerType>(Index->getType());
4505 uint64_t TableSize = Array->getInitializer()->getType()
4506 ->getArrayNumElements();
4507 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4508 Index = Builder.CreateZExt(Index,
4509 IntegerType::get(IT->getContext(),
4510 IT->getBitWidth() + 1),
4511 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00004512
Hans Wennborg776d7122012-09-26 09:34:53 +00004513 Value *GEPIndices[] = { Builder.getInt32(0), Index };
David Blaikieaa41cd52015-04-03 21:33:42 +00004514 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4515 GEPIndices, "switch.gep");
Hans Wennborg776d7122012-09-26 09:34:53 +00004516 return Builder.CreateLoad(GEP, "switch.load");
4517 }
4518 }
4519 llvm_unreachable("Unknown lookup table kind!");
4520}
4521
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004522bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00004523 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004524 Type *ElementType) {
4525 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004526 if (!IT)
4527 return false;
4528 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4529 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004530
4531 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4532 if (TableSize >= UINT_MAX/IT->getBitWidth())
4533 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004534 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00004535}
4536
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004537/// Determine whether a lookup table should be built for this switch, based on
4538/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004539static bool
4540ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4541 const TargetTransformInfo &TTI, const DataLayout &DL,
4542 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004543 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4544 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00004545
Chandler Carruth77d433d2012-11-30 09:26:25 +00004546 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00004547 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00004548 for (const auto &I : ResultTypes) {
4549 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004550
4551 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004552 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004553
4554 // Saturate this flag to false.
4555 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004556 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004557
4558 // If both flags saturate, we're done. NOTE: This *only* works with
4559 // saturating flags, and all flags have to saturate first due to the
4560 // non-deterministic behavior of iterating over a dense map.
4561 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00004562 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00004563 }
Evan Cheng65df8082012-11-30 02:02:42 +00004564
Chandler Carruth77d433d2012-11-30 09:26:25 +00004565 // If each table would fit in a register, we should build it anyway.
4566 if (AllTablesFitInRegister)
4567 return true;
4568
4569 // Don't build a table that doesn't fit in-register if it has illegal types.
4570 if (HasIllegalType)
4571 return false;
4572
4573 // The table density should be at least 40%. This is the same criterion as for
4574 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4575 // FIXME: Find the best cut-off.
4576 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004577}
4578
Erik Eckstein0d86c762014-11-27 15:13:14 +00004579/// Try to reuse the switch table index compare. Following pattern:
4580/// \code
4581/// if (idx < tablesize)
4582/// r = table[idx]; // table does not contain default_value
4583/// else
4584/// r = default_value;
4585/// if (r != default_value)
4586/// ...
4587/// \endcode
4588/// Is optimized to:
4589/// \code
4590/// cond = idx < tablesize;
4591/// if (cond)
4592/// r = table[idx];
4593/// else
4594/// r = default_value;
4595/// if (cond)
4596/// ...
4597/// \endcode
4598/// Jump threading will then eliminate the second if(cond).
4599static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4600 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4601 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4602
4603 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4604 if (!CmpInst)
4605 return;
4606
4607 // We require that the compare is in the same block as the phi so that jump
4608 // threading can do its work afterwards.
4609 if (CmpInst->getParent() != PhiBlock)
4610 return;
4611
4612 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4613 if (!CmpOp1)
4614 return;
4615
4616 Value *RangeCmp = RangeCheckBranch->getCondition();
4617 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4618 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4619
4620 // Check if the compare with the default value is constant true or false.
4621 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4622 DefaultValue, CmpOp1, true);
4623 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4624 return;
4625
4626 // Check if the compare with the case values is distinct from the default
4627 // compare result.
4628 for (auto ValuePair : Values) {
4629 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4630 ValuePair.second, CmpOp1, true);
4631 if (!CaseConst || CaseConst == DefaultConst)
4632 return;
4633 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4634 "Expect true or false as compare result.");
4635 }
James Molloy4de84dd2015-11-04 15:28:04 +00004636
Erik Eckstein0d86c762014-11-27 15:13:14 +00004637 // Check if the branch instruction dominates the phi node. It's a simple
4638 // dominance check, but sufficient for our needs.
4639 // Although this check is invariant in the calling loops, it's better to do it
4640 // at this late stage. Practically we do it at most once for a switch.
4641 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4642 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4643 BasicBlock *Pred = *PI;
4644 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4645 return;
4646 }
4647
4648 if (DefaultConst == FalseConst) {
4649 // The compare yields the same result. We can replace it.
4650 CmpInst->replaceAllUsesWith(RangeCmp);
4651 ++NumTableCmpReuses;
4652 } else {
4653 // The compare yields the same result, just inverted. We can replace it.
4654 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4655 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4656 RangeCheckBranch);
4657 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4658 ++NumTableCmpReuses;
4659 }
4660}
4661
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004662/// If the switch is only used to initialize one or more phi nodes in a common
4663/// successor block with different constant values, replace the switch with
4664/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004665static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4666 const DataLayout &DL,
4667 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004668 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004669
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004670 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004671 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004672 return false;
4673
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004674 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4675 // split off a dense part and build a lookup table for that.
4676
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004677 // FIXME: This creates arrays of GEPs to constant strings, which means each
4678 // GEP needs a runtime relocation in PIC code. We should just build one big
4679 // string and lookup indices into that.
4680
Hans Wennborg4744ac12014-01-15 05:00:27 +00004681 // Ignore switches with less than three cases. Lookup tables will not make them
4682 // faster, so we don't analyze them.
4683 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004684 return false;
4685
4686 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00004687 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004688 assert(SI->case_begin() != SI->case_end());
4689 SwitchInst::CaseIt CI = SI->case_begin();
4690 ConstantInt *MinCaseVal = CI.getCaseValue();
4691 ConstantInt *MaxCaseVal = CI.getCaseValue();
4692
Craig Topperf40110f2014-04-25 05:29:35 +00004693 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004694 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004695 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4696 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4697 SmallDenseMap<PHINode*, Type*> ResultTypes;
4698 SmallVector<PHINode*, 4> PHIs;
4699
4700 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4701 ConstantInt *CaseVal = CI.getCaseValue();
4702 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4703 MinCaseVal = CaseVal;
4704 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4705 MaxCaseVal = CaseVal;
4706
4707 // Resulting value at phi nodes for this case value.
4708 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4709 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004710 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004711 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004712 return false;
4713
4714 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004715 for (const auto &I : Results) {
4716 PHINode *PHI = I.first;
4717 Constant *Value = I.second;
4718 if (!ResultLists.count(PHI))
4719 PHIs.push_back(PHI);
4720 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004721 }
4722 }
4723
Hans Wennborgac114a32014-01-12 00:44:41 +00004724 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004725 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004726 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4727 }
4728
4729 uint64_t NumResults = ResultLists[PHIs[0]].size();
4730 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4731 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4732 bool TableHasHoles = (NumResults < TableSize);
4733
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004734 // If the table has holes, we need a constant result for the default case
4735 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004736 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00004737 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004738 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00004739
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004740 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4741 if (NeedMask) {
4742 // As an extra penalty for the validity test we require more cases.
4743 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4744 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004745 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004746 return false;
4747 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004748
Hans Wennborga6a11a92014-11-18 02:37:11 +00004749 for (const auto &I : DefaultResultsList) {
4750 PHINode *PHI = I.first;
4751 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004752 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004753 }
4754
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004755 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004756 return false;
4757
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004758 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004759 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004760 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4761 "switch.lookup",
4762 CommonDest->getParent(),
4763 CommonDest);
4764
Michael Gottesmanc024f322013-10-20 07:04:37 +00004765 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004766 Builder.SetInsertPoint(SI);
4767 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4768 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004769
4770 // Compute the maximum table size representable by the integer type we are
4771 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004772 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004773 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004774 assert(MaxTableSize >= TableSize &&
4775 "It is impossible for a switch to have more entries than the max "
4776 "representable value of its input integer type's size.");
4777
Hans Wennborgb64cb272015-01-26 19:52:34 +00004778 // If the default destination is unreachable, or if the lookup table covers
4779 // all values of the conditional variable, branch directly to the lookup table
4780 // BB. Otherwise, check that the condition is within the case range.
4781 const bool DefaultIsReachable =
4782 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4783 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004784 BranchInst *RangeCheckBranch = nullptr;
4785
Hans Wennborgb64cb272015-01-26 19:52:34 +00004786 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00004787 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00004788 // Note: We call removeProdecessor later since we need to be able to get the
4789 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00004790 } else {
4791 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004792 MinCaseVal->getType(), TableSize));
Erik Eckstein0d86c762014-11-27 15:13:14 +00004793 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00004794 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004795
4796 // Populate the BB that does the lookups.
4797 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004798
4799 if (NeedMask) {
4800 // Before doing the lookup we do the hole check.
4801 // The LookupBB is therefore re-purposed to do the hole check
4802 // and we create a new LookupBB.
4803 BasicBlock *MaskBB = LookupBB;
4804 MaskBB->setName("switch.hole_check");
4805 LookupBB = BasicBlock::Create(Mod.getContext(),
4806 "switch.lookup",
4807 CommonDest->getParent(),
4808 CommonDest);
4809
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004810 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4811 // unnecessary illegal types.
4812 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4813 APInt MaskInt(TableSizePowOf2, 0);
4814 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004815 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004816 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4817 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4818 uint64_t Idx = (ResultList[I].first->getValue() -
4819 MinCaseVal->getValue()).getLimitedValue();
4820 MaskInt |= One << Idx;
4821 }
4822 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4823
4824 // Get the TableIndex'th bit of the bitmask.
4825 // If this bit is 0 (meaning hole) jump to the default destination,
4826 // else continue with table lookup.
4827 IntegerType *MapTy = TableMask->getType();
4828 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4829 "switch.maskindex");
4830 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4831 "switch.shifted");
4832 Value *LoBit = Builder.CreateTrunc(Shifted,
4833 Type::getInt1Ty(Mod.getContext()),
4834 "switch.lobit");
4835 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4836
4837 Builder.SetInsertPoint(LookupBB);
4838 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4839 }
4840
Hans Wennborg86ac6302015-04-24 20:57:56 +00004841 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4842 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4843 // do not delete PHINodes here.
4844 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4845 /*DontDeleteUselessPHIs=*/true);
4846 }
4847
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004848 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004849 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4850 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004851 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004852
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004853 // If using a bitmask, use any value to fill the lookup table holes.
4854 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004855 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004856
Manman Ren4d189fb2014-07-24 21:13:20 +00004857 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004858
Hans Wennborgf744fa92012-09-19 14:24:21 +00004859 // If the result is used to return immediately from the function, we want to
4860 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004861 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4862 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004863 Builder.CreateRet(Result);
4864 ReturnedEarly = true;
4865 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004866 }
4867
Erik Eckstein0d86c762014-11-27 15:13:14 +00004868 // Do a small peephole optimization: re-use the switch table compare if
4869 // possible.
4870 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4871 BasicBlock *PhiBlock = PHI->getParent();
4872 // Search for compare instructions which use the phi.
4873 for (auto *User : PHI->users()) {
4874 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4875 }
4876 }
4877
Hans Wennborgf744fa92012-09-19 14:24:21 +00004878 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004879 }
4880
4881 if (!ReturnedEarly)
4882 Builder.CreateBr(CommonDest);
4883
4884 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004885 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004886 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004887
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004888 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004889 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004890 Succ->removePredecessor(SI->getParent());
4891 }
4892 SI->eraseFromParent();
4893
4894 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004895 if (NeedMask)
4896 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004897 return true;
4898}
4899
Devang Patela7ec47d2011-05-18 20:35:38 +00004900bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004901 BasicBlock *BB = SI->getParent();
4902
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004903 if (isValueEqualityComparison(SI)) {
4904 // If we only have one predecessor, and if it is a branch on this value,
4905 // see if that predecessor totally determines the outcome of this switch.
4906 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4907 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004908 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004909
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004910 Value *Cond = SI->getCondition();
4911 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4912 if (SimplifySwitchOnSelect(SI, Select))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004913 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004914
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004915 // If the block only contains the switch, see if we can fold the block
4916 // away into any preds.
4917 BasicBlock::iterator BBI = BB->begin();
4918 // Ignore dbg intrinsics.
4919 while (isa<DbgInfoIntrinsic>(BBI))
4920 ++BBI;
4921 if (SI == &*BBI)
4922 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004923 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004924 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004925
4926 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004927 if (TurnSwitchRangeIntoICmp(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004928 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004929
4930 // Remove unreachable cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004931 if (EliminateDeadSwitchCases(SI, AC, DL))
4932 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004933
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004934 if (SwitchToSelect(SI, Builder, AC, DL))
4935 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004936
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004937 if (ForwardSwitchConditionToPHI(SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004938 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004939
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004940 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4941 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004942
Chris Lattner25c3af32010-12-13 06:25:44 +00004943 return false;
4944}
4945
4946bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4947 BasicBlock *BB = IBI->getParent();
4948 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004949
Chris Lattner25c3af32010-12-13 06:25:44 +00004950 // Eliminate redundant destinations.
4951 SmallPtrSet<Value *, 8> Succs;
4952 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4953 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004954 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004955 Dest->removePredecessor(BB);
4956 IBI->removeDestination(i);
4957 --i; --e;
4958 Changed = true;
4959 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004960 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004961
4962 if (IBI->getNumDestinations() == 0) {
4963 // If the indirectbr has no successors, change it to unreachable.
4964 new UnreachableInst(IBI->getContext(), IBI);
4965 EraseTerminatorInstAndDCECond(IBI);
4966 return true;
4967 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004968
Chris Lattner25c3af32010-12-13 06:25:44 +00004969 if (IBI->getNumDestinations() == 1) {
4970 // If the indirectbr has one successor, change it to a direct branch.
4971 BranchInst::Create(IBI->getDestination(0), IBI);
4972 EraseTerminatorInstAndDCECond(IBI);
4973 return true;
4974 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004975
Chris Lattner25c3af32010-12-13 06:25:44 +00004976 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4977 if (SimplifyIndirectBrOnSelect(IBI, SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004978 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004979 }
4980 return Changed;
4981}
4982
Philip Reames2b969d72015-03-24 22:28:45 +00004983/// Given an block with only a single landing pad and a unconditional branch
4984/// try to find another basic block which this one can be merged with. This
4985/// handles cases where we have multiple invokes with unique landing pads, but
4986/// a shared handler.
4987///
4988/// We specifically choose to not worry about merging non-empty blocks
4989/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4990/// practice, the optimizer produces empty landing pad blocks quite frequently
4991/// when dealing with exception dense code. (see: instcombine, gvn, if-else
4992/// sinking in this file)
4993///
4994/// This is primarily a code size optimization. We need to avoid performing
4995/// any transform which might inhibit optimization (such as our ability to
4996/// specialize a particular handler via tail commoning). We do this by not
4997/// merging any blocks which require us to introduce a phi. Since the same
4998/// values are flowing through both blocks, we don't loose any ability to
4999/// specialize. If anything, we make such specialization more likely.
5000///
5001/// TODO - This transformation could remove entries from a phi in the target
5002/// block when the inputs in the phi are the same for the two blocks being
5003/// merged. In some cases, this could result in removal of the PHI entirely.
5004static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
5005 BasicBlock *BB) {
5006 auto Succ = BB->getUniqueSuccessor();
5007 assert(Succ);
5008 // If there's a phi in the successor block, we'd likely have to introduce
5009 // a phi into the merged landing pad block.
5010 if (isa<PHINode>(*Succ->begin()))
5011 return false;
5012
5013 for (BasicBlock *OtherPred : predecessors(Succ)) {
5014 if (BB == OtherPred)
5015 continue;
5016 BasicBlock::iterator I = OtherPred->begin();
5017 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
5018 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
5019 continue;
5020 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
5021 BranchInst *BI2 = dyn_cast<BranchInst>(I);
5022 if (!BI2 || !BI2->isIdenticalTo(BI))
5023 continue;
5024
David Majnemer1efa23d2016-02-20 01:07:45 +00005025 // We've found an identical block. Update our predecessors to take that
Philip Reames2b969d72015-03-24 22:28:45 +00005026 // path instead and make ourselves dead.
5027 SmallSet<BasicBlock *, 16> Preds;
5028 Preds.insert(pred_begin(BB), pred_end(BB));
5029 for (BasicBlock *Pred : Preds) {
5030 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
5031 assert(II->getNormalDest() != BB &&
5032 II->getUnwindDest() == BB && "unexpected successor");
5033 II->setUnwindDest(OtherPred);
5034 }
5035
5036 // The debug info in OtherPred doesn't cover the merged control flow that
5037 // used to go through BB. We need to delete it or update it.
5038 for (auto I = OtherPred->begin(), E = OtherPred->end();
5039 I != E;) {
5040 Instruction &Inst = *I; I++;
5041 if (isa<DbgInfoIntrinsic>(Inst))
5042 Inst.eraseFromParent();
5043 }
5044
5045 SmallSet<BasicBlock *, 16> Succs;
5046 Succs.insert(succ_begin(BB), succ_end(BB));
5047 for (BasicBlock *Succ : Succs) {
5048 Succ->removePredecessor(BB);
5049 }
5050
5051 IRBuilder<> Builder(BI);
5052 Builder.CreateUnreachable();
5053 BI->eraseFromParent();
5054 return true;
5055 }
5056 return false;
5057}
5058
Devang Patel767f6932011-05-18 18:28:48 +00005059bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00005060 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005061
Manman Ren93ab6492012-09-20 22:37:36 +00005062 if (SinkCommon && SinkThenElseCodeToEnd(BI))
5063 return true;
5064
Chris Lattner25c3af32010-12-13 06:25:44 +00005065 // If the Terminator is the only non-phi instruction, simplify the block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00005066 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00005067 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
5068 TryToSimplifyUncondBranchFromEmptyBlock(BB))
5069 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005070
Chris Lattner25c3af32010-12-13 06:25:44 +00005071 // If the only instruction in the block is a seteq/setne comparison
5072 // against a constant, try to simplify the block.
5073 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5074 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5075 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5076 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005077 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005078 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
5079 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00005080 return true;
5081 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005082
Philip Reames2b969d72015-03-24 22:28:45 +00005083 // See if we can merge an empty landing pad block with another which is
5084 // equivalent.
5085 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
5086 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
5087 if (I->isTerminator() &&
5088 TryToMergeLandingPad(LPad, BI, BB))
5089 return true;
5090 }
5091
Manman Rend33f4ef2012-06-13 05:43:29 +00005092 // If this basic block is ONLY a compare and a branch, and if a predecessor
5093 // branches to us and our successor, fold the comparison into the
5094 // predecessor and use logical operations to update the incoming value
5095 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005096 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5097 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005098 return false;
5099}
5100
James Molloy4de84dd2015-11-04 15:28:04 +00005101static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5102 BasicBlock *PredPred = nullptr;
5103 for (auto *P : predecessors(BB)) {
5104 BasicBlock *PPred = P->getSinglePredecessor();
5105 if (!PPred || (PredPred && PredPred != PPred))
5106 return nullptr;
5107 PredPred = PPred;
5108 }
5109 return PredPred;
5110}
Chris Lattner25c3af32010-12-13 06:25:44 +00005111
Devang Patela7ec47d2011-05-18 20:35:38 +00005112bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005113 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005114
Chris Lattner25c3af32010-12-13 06:25:44 +00005115 // Conditional branch
5116 if (isValueEqualityComparison(BI)) {
5117 // If we only have one predecessor, and if it is a branch on this value,
5118 // see if that predecessor totally determines the outcome of this
5119 // switch.
5120 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00005121 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005122 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005123
Chris Lattner25c3af32010-12-13 06:25:44 +00005124 // This block must be empty, except for the setcond inst, if it exists.
5125 // Ignore dbg intrinsics.
5126 BasicBlock::iterator I = BB->begin();
5127 // Ignore dbg intrinsics.
5128 while (isa<DbgInfoIntrinsic>(I))
5129 ++I;
5130 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00005131 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005132 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005133 } else if (&*I == cast<Instruction>(BI->getCondition())){
5134 ++I;
5135 // Ignore dbg intrinsics.
5136 while (isa<DbgInfoIntrinsic>(I))
5137 ++I;
Devang Patel58380552011-05-18 20:53:17 +00005138 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005139 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005140 }
5141 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005142
Chris Lattner25c3af32010-12-13 06:25:44 +00005143 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005144 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00005145 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005146
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00005147 // If this basic block is ONLY a compare and a branch, and if a predecessor
5148 // branches to us and one of our successors, fold the comparison into the
5149 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005150 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5151 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005152
Chris Lattner25c3af32010-12-13 06:25:44 +00005153 // We have a conditional branch to two blocks that are only reachable
5154 // from BI. We know that the condbr dominates the two blocks, so see if
5155 // there is any identical code in the "then" and "else" blocks. If so, we
5156 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00005157 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5158 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005159 if (HoistThenElseCodeToIf(BI, TTI))
5160 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005161 } else {
5162 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005163 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00005164 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5165 if (Succ0TI->getNumSuccessors() == 1 &&
5166 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005167 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
5168 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005169 }
Craig Topperf40110f2014-04-25 05:29:35 +00005170 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005171 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005172 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00005173 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5174 if (Succ1TI->getNumSuccessors() == 1 &&
5175 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005176 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
5177 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005178 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005179
Chris Lattner25c3af32010-12-13 06:25:44 +00005180 // If this is a branch on a phi node in the current block, thread control
5181 // through this block if any PHI node entries are constants.
5182 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5183 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005184 if (FoldCondBranchOnPHI(BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005185 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005186
Chris Lattner25c3af32010-12-13 06:25:44 +00005187 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00005188 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5189 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00005190 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00005191 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005192 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005193
James Molloy4de84dd2015-11-04 15:28:04 +00005194 // Look for diamond patterns.
5195 if (MergeCondStores)
5196 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5197 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5198 if (PBI != BI && PBI->isConditional())
5199 if (mergeConditionalStores(PBI, BI))
5200 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5201
Chris Lattner25c3af32010-12-13 06:25:44 +00005202 return false;
5203}
5204
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005205/// Check if passing a value to an instruction will cause undefined behavior.
5206static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5207 Constant *C = dyn_cast<Constant>(V);
5208 if (!C)
5209 return false;
5210
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005211 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005212 return false;
5213
5214 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005215 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00005216 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005217
5218 // Now make sure that there are no instructions in between that can alter
5219 // control flow (eg. calls)
5220 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00005221 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005222 return false;
5223
5224 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5225 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5226 if (GEP->getPointerOperand() == I)
5227 return passingValueIsAlwaysUndefined(V, GEP);
5228
5229 // Look through bitcasts.
5230 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5231 return passingValueIsAlwaysUndefined(V, BC);
5232
Benjamin Kramer0655b782011-08-26 02:25:55 +00005233 // Load from null is undefined.
5234 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005235 if (!LI->isVolatile())
5236 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005237
Benjamin Kramer0655b782011-08-26 02:25:55 +00005238 // Store to null is undefined.
5239 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005240 if (!SI->isVolatile())
5241 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005242 }
5243 return false;
5244}
5245
5246/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005247/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005248static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5249 for (BasicBlock::iterator i = BB->begin();
5250 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5251 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5252 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5253 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5254 IRBuilder<> Builder(T);
5255 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5256 BB->removePredecessor(PHI->getIncomingBlock(i));
5257 // Turn uncoditional branches into unreachables and remove the dead
5258 // destination from conditional branches.
5259 if (BI->isUnconditional())
5260 Builder.CreateUnreachable();
5261 else
5262 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
5263 BI->getSuccessor(0));
5264 BI->eraseFromParent();
5265 return true;
5266 }
5267 // TODO: SwitchInst.
5268 }
5269
5270 return false;
5271}
5272
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005273bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00005274 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00005275
Chris Lattnerd7beca32010-12-14 06:17:25 +00005276 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00005277 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00005278
Dan Gohman4a63fad2010-08-14 00:29:42 +00005279 // Remove basic blocks that have no predecessors (except the entry block)...
5280 // or that just have themself as a predecessor. These are unreachable.
Ramkumar Ramachandra181233b2015-01-13 04:17:47 +00005281 if ((pred_empty(BB) &&
Chris Lattnerd7beca32010-12-14 06:17:25 +00005282 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00005283 BB->getSinglePredecessor() == BB) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00005284 DEBUG(dbgs() << "Removing BB: \n" << *BB);
5285 DeleteDeadBlock(BB);
5286 return true;
Chris Lattner466a0492002-05-21 20:50:24 +00005287 }
5288
Chris Lattner031340a2003-08-17 19:41:53 +00005289 // Check to see if we can constant propagate this terminator instruction
5290 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00005291 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00005292
Dan Gohman1a951062009-10-30 22:39:04 +00005293 // Check for and eliminate duplicate PHI nodes in this block.
5294 Changed |= EliminateDuplicatePHINodes(BB);
5295
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005296 // Check for and remove branches that will always cause undefined behavior.
5297 Changed |= removeUndefIntroducingPredecessor(BB);
5298
Chris Lattner2e3832d2010-12-13 05:10:48 +00005299 // Merge basic blocks into their predecessor if there is only one distinct
5300 // pred, and if there is only one distinct successor of the predecessor, and
5301 // if there are no PHI nodes.
5302 //
5303 if (MergeBlockIntoPredecessor(BB))
5304 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005305
Devang Patel15ad6762011-05-18 18:01:27 +00005306 IRBuilder<> Builder(BB);
5307
Dan Gohman20af5a02008-03-11 21:53:06 +00005308 // If there is a trivial two-entry PHI node in this basic block, and we can
5309 // eliminate it, do so now.
5310 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5311 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005312 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00005313
Devang Patela7ec47d2011-05-18 20:35:38 +00005314 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00005315 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00005316 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00005317 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005318 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00005319 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005320 }
5321 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00005322 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00005323 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
5324 if (SimplifyResume(RI, Builder)) return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00005325 } else if (CleanupReturnInst *RI =
5326 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5327 if (SimplifyCleanupReturn(RI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005328 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00005329 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005330 } else if (UnreachableInst *UI =
5331 dyn_cast<UnreachableInst>(BB->getTerminator())) {
5332 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005333 } else if (IndirectBrInst *IBI =
5334 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
5335 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00005336 }
5337
Chris Lattner031340a2003-08-17 19:41:53 +00005338 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00005339}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005340
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005341/// This function is used to do simplification of a CFG.
5342/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005343/// eliminates unreachable basic blocks, and does other "peephole" optimization
5344/// of the CFG. It returns true if a modification was made.
5345///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005346bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005347 unsigned BonusInstThreshold, AssumptionCache *AC) {
5348 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
5349 BonusInstThreshold, AC).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005350}