blob: dc499ce78b8ff022a79a611936af61e6ca27f3b8 [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"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000021#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000025#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000026#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/MDBuilder.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000038#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Type.h"
Evan Chengd983eba2011-01-29 04:46:23 +000042#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Rafael Espindolaea46c322014-08-15 15:46:38 +000046#include "llvm/Transforms/Utils/Local.h"
Jingyue Wufc029672014-09-30 22:23:38 +000047#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000048#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000049#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000051using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000052using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000053
Chandler Carruth964daaa2014-04-22 02:55:47 +000054#define DEBUG_TYPE "simplifycfg"
55
James Molloy1b6207e2015-02-13 10:48:30 +000056// Chosen as 2 so as to be cheap, but still to have enough power to fold
57// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
58// To catch this, we need to fold a compare and a select, hence '2' being the
59// minimum reasonable default.
Peter Collingbourne616044a2011-04-29 18:47:38 +000060static cl::opt<unsigned>
James Molloy1b6207e2015-02-13 10:48:30 +000061PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
62 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
Peter Collingbourne616044a2011-04-29 18:47:38 +000063
Evan Chengd983eba2011-01-29 04:46:23 +000064static cl::opt<bool>
65DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
66 cl::desc("Duplicate return instructions into unconditional branches"));
67
Manman Ren93ab6492012-09-20 22:37:36 +000068static cl::opt<bool>
69SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
70 cl::desc("Sink common instructions down to the end block"));
71
Alp Tokercb402912014-01-24 17:20:08 +000072static cl::opt<bool> HoistCondStores(
73 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
74 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000075
Philip Reamesb42db212015-10-14 22:46:19 +000076static cl::opt<unsigned> SpeculativeFlattenBias(
77 "speculative-flatten-bias", cl::Hidden, cl::init(100),
78 cl::desc("Control how biased a branch needs to be to be considered rarely"
79 " failing for speculative flattening (default = 100)"));
80
81static cl::opt<unsigned> SpeculativeFlattenThreshold(
82 "speculative-flatten-threshold", cl::Hidden, cl::init(10),
83 cl::desc("Control how much speculation happens due to speculative"
84 " flattening (default = 10)"));
85
86
Hans Wennborg39583b82012-09-26 09:44:49 +000087STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000088STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000089STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +000090STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +000091STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Manman Ren93ab6492012-09-20 22:37:36 +000092STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000093STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +000094
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000095namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +000096 // The first field contains the value that the switch produces when a certain
Sanjay Patel9361d352015-09-10 16:31:19 +000097 // case group is selected, and the second field is a vector containing the
98 // cases composing the case group.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +000099 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
100 SwitchCaseResultVectorTy;
101 // The first field contains the phi node that generates a result of the switch
Sanjay Patel9361d352015-09-10 16:31:19 +0000102 // and the second field contains the value generated for a certain case in the
103 // switch for that PHI.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000104 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
105
Eric Christopherb65acc62012-07-02 23:22:21 +0000106 /// ValueEqualityComparisonCase - Represents a case of a switch.
107 struct ValueEqualityComparisonCase {
108 ConstantInt *Value;
109 BasicBlock *Dest;
110
111 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
112 : Value(Value), Dest(Dest) {}
113
114 bool operator<(ValueEqualityComparisonCase RHS) const {
115 // Comparing pointers is ok as we only rely on the order for uniquing.
116 return Value < RHS.Value;
117 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000118
119 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000120 };
121
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000122class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000123 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000124 const DataLayout &DL;
Jingyue Wufc029672014-09-30 22:23:38 +0000125 unsigned BonusInstThreshold;
Chandler Carruth66b31302015-01-04 12:03:27 +0000126 AssumptionCache *AC;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000127 Value *isValueEqualityComparison(TerminatorInst *TI);
128 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000129 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000130 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000131 BasicBlock *Pred,
132 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000133 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
134 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000135
Devang Pateldd14e0f2011-05-18 21:33:11 +0000136 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000137 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000138 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000139 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000140 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000141 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000142 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000143 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000144
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000145public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000146 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
147 unsigned BonusInstThreshold, AssumptionCache *AC)
148 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000149 bool run(BasicBlock *BB);
150};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000151}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000152
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000153/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000154/// terminator instructions together.
Chris Lattner76dc2042005-08-03 00:19:45 +0000155static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
156 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000157
Chris Lattner76dc2042005-08-03 00:19:45 +0000158 // It is not safe to merge these two switch instructions if they have a common
159 // successor, and if that successor has a PHI node, and if *that* PHI node has
160 // conflicting incoming values from the two switch blocks.
161 BasicBlock *SI1BB = SI1->getParent();
162 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000163 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000164
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000165 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
166 if (SI1Succs.count(*I))
167 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000168 isa<PHINode>(BBI); ++BBI) {
169 PHINode *PN = cast<PHINode>(BBI);
170 if (PN->getIncomingValueForBlock(SI1BB) !=
171 PN->getIncomingValueForBlock(SI2BB))
172 return false;
173 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000174
Chris Lattner76dc2042005-08-03 00:19:45 +0000175 return true;
176}
177
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000178/// Return true if it is safe and profitable to merge these two terminator
179/// instructions together, where SI1 is an unconditional branch. PhiNodes will
180/// store all PHI nodes in common successors.
Manman Rend33f4ef2012-06-13 05:43:29 +0000181static bool isProfitableToFoldUnconditional(BranchInst *SI1,
182 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000183 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000184 SmallVectorImpl<PHINode*> &PhiNodes) {
185 if (SI1 == SI2) return false; // Can't merge with self!
186 assert(SI1->isUnconditional() && SI2->isConditional());
187
188 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000189 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000190 // 1> We have a constant incoming value for the conditional branch;
191 // 2> We have "Cond" as the incoming value for the unconditional branch;
192 // 3> SI2->getCondition() and Cond have same operands.
193 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
194 if (!Ci2) return false;
195 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
196 Cond->getOperand(1) == Ci2->getOperand(1)) &&
197 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
198 Cond->getOperand(1) == Ci2->getOperand(0)))
199 return false;
200
201 BasicBlock *SI1BB = SI1->getParent();
202 BasicBlock *SI2BB = SI2->getParent();
203 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000204 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
205 if (SI1Succs.count(*I))
206 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000207 isa<PHINode>(BBI); ++BBI) {
208 PHINode *PN = cast<PHINode>(BBI);
209 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000210 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000211 return false;
212 PhiNodes.push_back(PN);
213 }
214 return true;
215}
216
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000217/// Update PHI nodes in Succ to indicate that there will now be entries in it
218/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
219/// will be the same as those coming in from ExistPred, an existing predecessor
220/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000221static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
222 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000223 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000224
Chris Lattner80b03a12008-07-13 22:23:11 +0000225 PHINode *PN;
226 for (BasicBlock::iterator I = Succ->begin();
227 (PN = dyn_cast<PHINode>(I)); ++I)
228 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000229}
230
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000231/// Compute an abstract "cost" of speculating the given instruction,
232/// which is assumed to be safe to speculate. TCC_Free means cheap,
233/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000234/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000235static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000236 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000237 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000238 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000239 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000240}
Sanjay Patelf9b77632015-09-15 15:24:42 +0000241
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000242/// If we have a merge point of an "if condition" as accepted above,
243/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000244/// don't handle the true generality of domination here, just a special case
245/// which works well enough for us.
246///
247/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000248/// see if V (which must be an instruction) and its recursive operands
249/// that do not dominate BB have a combined cost lower than CostRemaining and
250/// are non-trapping. If both are true, the instruction is inserted into the
251/// set and true is returned.
252///
253/// The cost for most non-trapping instructions is defined as 1 except for
254/// Select whose cost is 2.
255///
256/// After this function returns, CostRemaining is decreased by the cost of
257/// V plus its non-dominating operands. If that cost is greater than
258/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000259static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000260 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000261 unsigned &CostRemaining,
James Molloy7c336572015-02-11 12:15:41 +0000262 const TargetTransformInfo &TTI) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000263 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000264 if (!I) {
265 // Non-instructions all dominate instructions, but not all constantexprs
266 // can be executed unconditionally.
267 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
268 if (C->canTrap())
269 return false;
270 return true;
271 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000272 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000273
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000274 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000275 // the bottom of this block.
276 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000277
Chris Lattner0aa56562004-04-09 22:50:22 +0000278 // If this instruction is defined in a block that contains an unconditional
279 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000280 // statement". If not, it definitely dominates the region.
281 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000282 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000283 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000284
Chris Lattner9ac168d2010-12-14 07:41:39 +0000285 // If we aren't allowing aggressive promotion anymore, then don't consider
286 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000287 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000288
Peter Collingbournee3511e12011-04-29 18:47:31 +0000289 // If we have seen this instruction before, don't count it again.
290 if (AggressiveInsts->count(I)) return true;
291
Chris Lattner9ac168d2010-12-14 07:41:39 +0000292 // Okay, it looks like the instruction IS in the "condition". Check to
293 // see if it's a cheap instruction to unconditionally compute, and if it
294 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000295 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000296 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000297
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000298 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000299
Peter Collingbournee3511e12011-04-29 18:47:31 +0000300 if (Cost > CostRemaining)
301 return false;
302
303 CostRemaining -= Cost;
304
305 // Okay, we can only really hoist these out if their operands do
306 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000307 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000308 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000309 return false;
310 // Okay, it's safe to do this! Remember this instruction.
311 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000312 return true;
313}
Chris Lattner466a0492002-05-21 20:50:24 +0000314
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000315/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000316/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000317static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000318 // Normal constant int.
319 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000320 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000321 return CI;
322
323 // This is some kind of pointer constant. Turn it into a pointer-sized
324 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000325 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000326
327 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
328 if (isa<ConstantPointerNull>(V))
329 return ConstantInt::get(PtrTy, 0);
330
331 // IntToPtr const int.
332 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
333 if (CE->getOpcode() == Instruction::IntToPtr)
334 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
335 // The constant is very likely to have the right type already.
336 if (CI->getType() == PtrTy)
337 return CI;
338 else
339 return cast<ConstantInt>
340 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
341 }
Craig Topperf40110f2014-04-25 05:29:35 +0000342 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000343}
344
Mehdi Aminiffd01002014-11-20 22:40:25 +0000345namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000346
Mehdi Aminiffd01002014-11-20 22:40:25 +0000347/// Given a chain of or (||) or and (&&) comparison of a value against a
348/// constant, this will try to recover the information required for a switch
349/// structure.
350/// It will depth-first traverse the chain of comparison, seeking for patterns
351/// like %a == 12 or %a < 4 and combine them to produce a set of integer
352/// representing the different cases for the switch.
353/// Note that if the chain is composed of '||' it will build the set of elements
354/// that matches the comparisons (i.e. any of this value validate the chain)
355/// while for a chain of '&&' it will build the set elements that make the test
356/// fail.
357struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000358 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000359 Value *CompValue; /// Value found for the switch comparison
360 Value *Extra; /// Extra clause to be checked before the switch
361 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
362 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000363
Mehdi Aminiffd01002014-11-20 22:40:25 +0000364 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000365 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
366 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
367 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000368 }
369
Mehdi Aminiffd01002014-11-20 22:40:25 +0000370 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000371 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000372 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000373 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000374
Mehdi Aminiffd01002014-11-20 22:40:25 +0000375private:
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000376
Mehdi Aminiffd01002014-11-20 22:40:25 +0000377 /// Try to set the current value used for the comparison, it succeeds only if
378 /// it wasn't set before or if the new value is the same as the old one
379 bool setValueOnce(Value *NewVal) {
380 if(CompValue && CompValue != NewVal) return false;
381 CompValue = NewVal;
382 return (CompValue != nullptr);
383 }
384
385 /// Try to match Instruction "I" as a comparison against a constant and
386 /// populates the array Vals with the set of values that match (or do not
387 /// match depending on isEQ).
388 /// Return false on failure. On success, the Value the comparison matched
389 /// against is placed in CompValue.
390 /// If CompValue is already set, the function is expected to fail if a match
391 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000392 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000393 // If this is an icmp against a constant, handle this as one of the cases.
394 ICmpInst *ICI;
395 ConstantInt *C;
396 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
397 (C = GetConstantInt(I->getOperand(1), DL)))) {
398 return false;
399 }
400
401 Value *RHSVal;
402 ConstantInt *RHSC;
403
404 // Pattern match a special case
405 // (x & ~2^x) == y --> x == y || x == y|2^x
406 // This undoes a transformation done by instcombine to fuse 2 compares.
407 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
408 if (match(ICI->getOperand(0),
409 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
410 APInt Not = ~RHSC->getValue();
411 if (Not.isPowerOf2()) {
412 // If we already have a value for the switch, it has to match!
413 if(!setValueOnce(RHSVal))
414 return false;
415
416 Vals.push_back(C);
417 Vals.push_back(ConstantInt::get(C->getContext(),
418 C->getValue() | Not));
419 UsedICmps++;
420 return true;
421 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000422 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000423
424 // If we already have a value for the switch, it has to match!
425 if(!setValueOnce(ICI->getOperand(0)))
426 return false;
427
428 UsedICmps++;
429 Vals.push_back(C);
430 return ICI->getOperand(0);
431 }
432
433 // 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 +0000434 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
435 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000436
437 // Shift the range if the compare is fed by an add. This is the range
438 // compare idiom as emitted by instcombine.
439 Value *CandidateVal = I->getOperand(0);
440 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
441 Span = Span.subtract(RHSC->getValue());
442 CandidateVal = RHSVal;
443 }
444
445 // If this is an and/!= check, then we are looking to build the set of
446 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
447 // x != 0 && x != 1.
448 if (!isEQ)
449 Span = Span.inverse();
450
451 // If there are a ton of values, we don't want to make a ginormous switch.
452 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
453 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000454 }
455
456 // If we already have a value for the switch, it has to match!
Mehdi Aminiffd01002014-11-20 22:40:25 +0000457 if(!setValueOnce(CandidateVal))
458 return false;
459
460 // Add all values from the range to the set
461 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
462 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000463
464 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000465 return true;
466
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000467 }
468
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000469 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000470 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
471 /// the value being compared, and stick the list constants into the Vals
472 /// vector.
473 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000474 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000475 Instruction *I = dyn_cast<Instruction>(V);
476 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000477
Mehdi Aminiffd01002014-11-20 22:40:25 +0000478 // Keep a stack (SmallVector for efficiency) for depth-first traversal
479 SmallVector<Value *, 8> DFT;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000480
Mehdi Aminiffd01002014-11-20 22:40:25 +0000481 // Initialize
482 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000483
Mehdi Aminiffd01002014-11-20 22:40:25 +0000484 while(!DFT.empty()) {
485 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000486
Mehdi Aminiffd01002014-11-20 22:40:25 +0000487 if (Instruction *I = dyn_cast<Instruction>(V)) {
488 // If it is a || (or && depending on isEQ), process the operands.
489 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
490 DFT.push_back(I->getOperand(1));
491 DFT.push_back(I->getOperand(0));
492 continue;
493 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000494
Mehdi Aminiffd01002014-11-20 22:40:25 +0000495 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000496 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000497 // Match succeed, continue the loop
498 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000499 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000500
Mehdi Aminiffd01002014-11-20 22:40:25 +0000501 // One element of the sequence of || (or &&) could not be match as a
502 // comparison against the same value as the others.
503 // We allow only one "Extra" case to be checked before the switch
504 if (!Extra) {
505 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000506 continue;
507 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000508 // Failed to parse a proper sequence, abort now
509 CompValue = nullptr;
510 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000511 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000512 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000513};
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000514
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000515}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000516
Eli Friedmancb61afb2008-12-16 20:54:32 +0000517static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000518 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000519 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
520 Cond = dyn_cast<Instruction>(SI->getCondition());
521 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
522 if (BI->isConditional())
523 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000524 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
525 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000526 }
527
528 TI->eraseFromParent();
529 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
530}
531
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000532/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000533/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000534Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000535 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000536 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
537 // Do not permit merging of large switch instructions into their
538 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000539 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
540 pred_end(SI->getParent())) <= 128)
541 CV = SI->getCondition();
542 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000543 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000544 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000545 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000546 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000547 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000548
549 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000550 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000551 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
552 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000553 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000554 CV = Ptr;
555 }
556 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000557 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000558}
559
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000560/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000561/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000562BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000563GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000564 std::vector<ValueEqualityComparisonCase>
565 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000566 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000567 Cases.reserve(SI->getNumCases());
568 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
569 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
570 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000571 return SI->getDefaultDest();
572 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000573
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000574 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000575 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000576 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
577 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000578 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000579 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000580 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000581}
582
Eric Christopherb65acc62012-07-02 23:22:21 +0000583
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000584/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000585/// in the list that match the specified block.
586static void EliminateBlockCases(BasicBlock *BB,
587 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000588 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000589}
590
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000591/// Return true if there are any keys in C1 that exist in C2 as well.
Eric Christopherb65acc62012-07-02 23:22:21 +0000592static bool
593ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
594 std::vector<ValueEqualityComparisonCase > &C2) {
595 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
596
597 // Make V1 be smaller than V2.
598 if (V1->size() > V2->size())
599 std::swap(V1, V2);
600
601 if (V1->size() == 0) return false;
602 if (V1->size() == 1) {
603 // Just scan V2.
604 ConstantInt *TheVal = (*V1)[0].Value;
605 for (unsigned i = 0, e = V2->size(); i != e; ++i)
606 if (TheVal == (*V2)[i].Value)
607 return true;
608 }
609
610 // Otherwise, just sort both lists and compare element by element.
611 array_pod_sort(V1->begin(), V1->end());
612 array_pod_sort(V2->begin(), V2->end());
613 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
614 while (i1 != e1 && i2 != e2) {
615 if ((*V1)[i1].Value == (*V2)[i2].Value)
616 return true;
617 if ((*V1)[i1].Value < (*V2)[i2].Value)
618 ++i1;
619 else
620 ++i2;
621 }
622 return false;
623}
624
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000625/// If TI is known to be a terminator instruction and its block is known to
626/// only have a single predecessor block, check to see if that predecessor is
627/// also a value comparison with the same value, and if that comparison
628/// determines the outcome of this comparison. If so, simplify TI. This does a
629/// very limited form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000630bool SimplifyCFGOpt::
631SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000632 BasicBlock *Pred,
633 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000634 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
635 if (!PredVal) return false; // Not a value comparison in predecessor.
636
637 Value *ThisVal = isValueEqualityComparison(TI);
638 assert(ThisVal && "This isn't a value comparison!!");
639 if (ThisVal != PredVal) return false; // Different predicates.
640
Andrew Trick3051aa12012-08-29 21:46:38 +0000641 // TODO: Preserve branch weight metadata, similarly to how
642 // FoldValueComparisonIntoPredecessors preserves it.
643
Chris Lattner1cca9592005-02-24 06:17:52 +0000644 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000645 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000646 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
647 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000648 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000649
Chris Lattner1cca9592005-02-24 06:17:52 +0000650 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000651 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000652 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000653 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000654
655 // If TI's block is the default block from Pred's comparison, potentially
656 // simplify TI based on this knowledge.
657 if (PredDef == TI->getParent()) {
658 // If we are here, we know that the value is none of those cases listed in
659 // PredCases. If there are any cases in ThisCases that are in PredCases, we
660 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000661 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000662 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000663
Chris Lattner4088e2b2010-12-13 01:47:07 +0000664 if (isa<BranchInst>(TI)) {
665 // Okay, one of the successors of this condbr is dead. Convert it to a
666 // uncond br.
667 assert(ThisCases.size() == 1 && "Branch can only have one case!");
668 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000669 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000670 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000671
Chris Lattner4088e2b2010-12-13 01:47:07 +0000672 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000673 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000674
Chris Lattner4088e2b2010-12-13 01:47:07 +0000675 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
676 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000677
Chris Lattner4088e2b2010-12-13 01:47:07 +0000678 EraseTerminatorInstAndDCECond(TI);
679 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000680 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000681
Chris Lattner4088e2b2010-12-13 01:47:07 +0000682 SwitchInst *SI = cast<SwitchInst>(TI);
683 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000684 SmallPtrSet<Constant*, 16> DeadCases;
685 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
686 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000687
David Greene725c7c32010-01-05 01:26:52 +0000688 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000689 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000690
Manman Ren8691e522012-09-14 21:53:06 +0000691 // Collect branch weights into a vector.
692 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000693 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000694 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
695 if (HasWeight)
696 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
697 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000698 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000699 Weights.push_back(CI->getValue().getZExtValue());
700 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000701 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
702 --i;
703 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000704 if (HasWeight) {
705 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
706 Weights.pop_back();
707 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000708 i.getCaseSuccessor()->removePredecessor(TI->getParent());
709 SI->removeCase(i);
710 }
711 }
Manman Ren97c18762012-10-11 22:28:34 +0000712 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000713 SI->setMetadata(LLVMContext::MD_prof,
714 MDBuilder(SI->getParent()->getContext()).
715 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000716
717 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000718 return true;
719 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000720
Chris Lattner4088e2b2010-12-13 01:47:07 +0000721 // Otherwise, TI's block must correspond to some matched value. Find out
722 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000723 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000724 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000725 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
726 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000727 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000728 return false; // Cannot handle multiple values coming to this block.
729 TIV = PredCases[i].Value;
730 }
731 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000732
733 // Okay, we found the one constant that our value can be if we get into TI's
734 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000735 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000736 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
737 if (ThisCases[i].Value == TIV) {
738 TheRealDest = ThisCases[i].Dest;
739 break;
740 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000741
742 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000743 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000744
745 // Remove PHI node entries for dead edges.
746 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000747 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
748 if (*SI != CheckEdge)
749 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000750 else
Craig Topperf40110f2014-04-25 05:29:35 +0000751 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000752
753 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000754 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000755 (void) NI;
756
757 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
758 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
759
760 EraseTerminatorInstAndDCECond(TI);
761 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000762}
763
Dale Johannesen7f99d222009-03-12 21:01:11 +0000764namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000765 /// This class implements a stable ordering of constant
Dale Johannesen7f99d222009-03-12 21:01:11 +0000766 /// integers that does not depend on their address. This is important for
767 /// applications that sort ConstantInt's to ensure uniqueness.
768 struct ConstantIntOrdering {
769 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
770 return LHS->getValue().ult(RHS->getValue());
771 }
772 };
773}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000774
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000775static int ConstantIntSortPredicate(ConstantInt *const *P1,
776 ConstantInt *const *P2) {
777 const ConstantInt *LHS = *P1;
778 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000779 if (LHS->getValue().ult(RHS->getValue()))
780 return 1;
781 if (LHS->getValue() == RHS->getValue())
782 return 0;
783 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000784}
785
Andrew Trick3051aa12012-08-29 21:46:38 +0000786static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000787 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000788 if (ProfMD && ProfMD->getOperand(0))
789 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
790 return MDS->getString().equals("branch_weights");
791
792 return false;
793}
794
Manman Ren571d9e42012-09-11 17:43:35 +0000795/// Get Weights of a given TerminatorInst, the default weight is at the front
796/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
797/// metadata.
798static void GetBranchWeights(TerminatorInst *TI,
799 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000800 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000801 assert(MD);
802 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000803 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000804 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000805 }
806
Manman Ren571d9e42012-09-11 17:43:35 +0000807 // If TI is a conditional eq, the default case is the false case,
808 // and the corresponding branch-weight data is at index 2. We swap the
809 // default weight to be the first entry.
810 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
811 assert(Weights.size() == 2);
812 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
813 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
814 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000815 }
816}
817
Manman Renf1cb16e2014-01-27 23:39:03 +0000818/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000819static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000820 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
821 if (Max > UINT_MAX) {
822 unsigned Offset = 32 - countLeadingZeros(Max);
823 for (uint64_t &I : Weights)
824 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000825 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000826}
827
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000828/// The specified terminator is a value equality comparison instruction
829/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000830/// See if any of the predecessors of the terminator block are value comparisons
831/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000832bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
833 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000834 BasicBlock *BB = TI->getParent();
835 Value *CV = isValueEqualityComparison(TI); // CondVal
836 assert(CV && "Not a comparison?");
837 bool Changed = false;
838
Chris Lattner6b39cb92008-02-18 07:42:56 +0000839 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000840 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000841 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000842
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000843 // See if the predecessor is a comparison with the same value.
844 TerminatorInst *PTI = Pred->getTerminator();
845 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
846
847 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
848 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000849 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000850 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
851
Eric Christopherb65acc62012-07-02 23:22:21 +0000852 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000853 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
854
855 // Based on whether the default edge from PTI goes to BB or not, fill in
856 // PredCases and PredDefault with the new switch cases we would like to
857 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000858 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000859
Andrew Trick3051aa12012-08-29 21:46:38 +0000860 // Update the branch weight metadata along the way
861 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000862 bool PredHasWeights = HasBranchWeights(PTI);
863 bool SuccHasWeights = HasBranchWeights(TI);
864
Manman Ren5e5049d2012-09-14 19:05:19 +0000865 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000866 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000867 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000868 if (Weights.size() != 1 + PredCases.size())
869 PredHasWeights = SuccHasWeights = false;
870 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000871 // If there are no predecessor weights but there are successor weights,
872 // populate Weights with 1, which will later be scaled to the sum of
873 // successor's weights
874 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000875
Manman Ren571d9e42012-09-11 17:43:35 +0000876 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000877 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000878 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000879 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000880 if (SuccWeights.size() != 1 + BBCases.size())
881 PredHasWeights = SuccHasWeights = false;
882 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000883 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000884
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000885 if (PredDefault == BB) {
886 // If this is the default destination from PTI, only the edges in TI
887 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000888 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
889 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
890 if (PredCases[i].Dest != BB)
891 PTIHandled.insert(PredCases[i].Value);
892 else {
893 // The default destination is BB, we don't need explicit targets.
894 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000895
Manman Ren571d9e42012-09-11 17:43:35 +0000896 if (PredHasWeights || SuccHasWeights) {
897 // Increase weight for the default case.
898 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000899 std::swap(Weights[i+1], Weights.back());
900 Weights.pop_back();
901 }
902
Eric Christopherb65acc62012-07-02 23:22:21 +0000903 PredCases.pop_back();
904 --i; --e;
905 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000906
Eric Christopherb65acc62012-07-02 23:22:21 +0000907 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000908 if (PredDefault != BBDefault) {
909 PredDefault->removePredecessor(Pred);
910 PredDefault = BBDefault;
911 NewSuccessors.push_back(BBDefault);
912 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000913
Manman Ren571d9e42012-09-11 17:43:35 +0000914 unsigned CasesFromPred = Weights.size();
915 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000916 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
917 if (!PTIHandled.count(BBCases[i].Value) &&
918 BBCases[i].Dest != BBDefault) {
919 PredCases.push_back(BBCases[i]);
920 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000921 if (SuccHasWeights || PredHasWeights) {
922 // The default weight is at index 0, so weight for the ith case
923 // should be at index i+1. Scale the cases from successor by
924 // PredDefaultWeight (Weights[0]).
925 Weights.push_back(Weights[0] * SuccWeights[i+1]);
926 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000927 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000928 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000929
Manman Ren571d9e42012-09-11 17:43:35 +0000930 if (SuccHasWeights || PredHasWeights) {
931 ValidTotalSuccWeight += SuccWeights[0];
932 // Scale the cases from predecessor by ValidTotalSuccWeight.
933 for (unsigned i = 1; i < CasesFromPred; ++i)
934 Weights[i] *= ValidTotalSuccWeight;
935 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
936 Weights[0] *= SuccWeights[0];
937 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000938 } else {
939 // If this is not the default destination from PSI, only the edges
940 // in SI that occur in PSI with a destination of BB will be
941 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000942 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000943 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000944 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
945 if (PredCases[i].Dest == BB) {
946 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000947
948 if (PredHasWeights || SuccHasWeights) {
949 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
950 std::swap(Weights[i+1], Weights.back());
951 Weights.pop_back();
952 }
953
Eric Christopherb65acc62012-07-02 23:22:21 +0000954 std::swap(PredCases[i], PredCases.back());
955 PredCases.pop_back();
956 --i; --e;
957 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000958
959 // Okay, now we know which constants were sent to BB from the
960 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000961 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
962 if (PTIHandled.count(BBCases[i].Value)) {
963 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000964 if (PredHasWeights || SuccHasWeights)
965 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000966 PredCases.push_back(BBCases[i]);
967 NewSuccessors.push_back(BBCases[i].Dest);
968 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
969 }
970
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000971 // If there are any constants vectored to BB that TI doesn't handle,
972 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000973 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000974 PTIHandled.begin(),
975 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000976 if (PredHasWeights || SuccHasWeights)
977 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000978 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000979 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000980 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000981 }
982
983 // Okay, at this point, we know which new successor Pred will get. Make
984 // sure we update the number of entries in the PHI nodes for these
985 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +0000986 for (BasicBlock *NewSuccessor : NewSuccessors)
987 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000988
Devang Patel58380552011-05-18 20:53:17 +0000989 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000990 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +0000991 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000992 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +0000993 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000994 }
995
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000996 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +0000997 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
998 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +0000999 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +00001000 for (ValueEqualityComparisonCase &V : PredCases)
1001 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001002
Andrew Trick3051aa12012-08-29 21:46:38 +00001003 if (PredHasWeights || SuccHasWeights) {
1004 // Halve the weights if any of them cannot fit in an uint32_t
1005 FitWeights(Weights);
1006
1007 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1008
1009 NewSI->setMetadata(LLVMContext::MD_prof,
1010 MDBuilder(BB->getContext()).
1011 createBranchWeights(MDWeights));
1012 }
1013
Eli Friedmancb61afb2008-12-16 20:54:32 +00001014 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001015
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001016 // Okay, last check. If BB is still a successor of PSI, then we must
1017 // have an infinite loop case. If so, add an infinitely looping block
1018 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001019 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001020 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1021 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001022 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001023 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001024 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001025 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1026 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001027 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001028 }
1029 NewSI->setSuccessor(i, InfLoopBlock);
1030 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001031
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001032 Changed = true;
1033 }
1034 }
1035 return Changed;
1036}
1037
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001038// If we would need to insert a select that uses the value of this invoke
1039// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1040// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001041static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1042 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001043 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001044 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001045 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001046 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1047 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1048 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1049 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1050 return false;
1051 }
1052 }
1053 }
1054 return true;
1055}
1056
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001057static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1058
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001059/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1060/// in the two blocks up into the branch block. The caller of this function
1061/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001062static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001063 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001064 // This does very trivial matching, with limited scanning, to find identical
1065 // instructions in the two blocks. In particular, we don't want to get into
1066 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1067 // such, we currently just scan for obviously identical instructions in an
1068 // identical order.
1069 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1070 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1071
Devang Patelf10e2872009-02-04 00:03:08 +00001072 BasicBlock::iterator BB1_Itr = BB1->begin();
1073 BasicBlock::iterator BB2_Itr = BB2->begin();
1074
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001075 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001076 // Skip debug info if it is not identical.
1077 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1078 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1079 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1080 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001081 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001082 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001083 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001084 }
Devang Patele48ddf82011-04-07 00:30:15 +00001085 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001086 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001087 return false;
1088
Chris Lattner389cfac2004-11-30 00:29:14 +00001089 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001090
David Majnemerc82f27a2013-06-03 20:43:12 +00001091 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001092 do {
1093 // If we are hoisting the terminator instruction, don't move one (making a
1094 // broken BB), instead clone it, and remove BI.
1095 if (isa<TerminatorInst>(I1))
1096 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001097
Chad Rosier54390052015-02-23 19:15:16 +00001098 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1099 return Changed;
1100
Chris Lattner389cfac2004-11-30 00:29:14 +00001101 // For a normal instruction, we just move one to right before the branch,
1102 // then replace all uses of the other with the first. Finally, we remove
1103 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001104 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001105 if (!I2->use_empty())
1106 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001107 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001108 unsigned KnownIDs[] = {
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001109 LLVMContext::MD_tbaa, LLVMContext::MD_range,
1110 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1111 LLVMContext::MD_nonnull, LLVMContext::MD_invariant_group};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001112 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001113 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001114 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001115
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001116 I1 = &*BB1_Itr++;
1117 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001118 // Skip debug info if it is not identical.
1119 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1120 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1121 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1122 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001123 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001124 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001125 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001126 }
Devang Patele48ddf82011-04-07 00:30:15 +00001127 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001128
1129 return true;
1130
1131HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001132 // It may not be possible to hoist an invoke.
1133 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001134 return Changed;
1135
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001136 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001137 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001138 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001139 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1140 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1141 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1142 if (BB1V == BB2V)
1143 continue;
1144
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001145 // Check for passingValueIsAlwaysUndefined here because we would rather
1146 // eliminate undefined control flow then converting it to a select.
1147 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1148 passingValueIsAlwaysUndefined(BB2V, PN))
1149 return Changed;
1150
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001151 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001152 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001153 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001154 return Changed;
1155 }
1156 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001157
Chris Lattner389cfac2004-11-30 00:29:14 +00001158 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001159 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001160 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001161 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001162 I1->replaceAllUsesWith(NT);
1163 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001164 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001165 }
1166
Devang Patel1407fb42011-05-19 20:52:46 +00001167 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001168 // Hoisting one of the terminators from our successor is a great thing.
1169 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1170 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1171 // nodes, so we insert select instruction to compute the final result.
1172 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001173 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001174 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001175 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001176 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001177 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1178 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001179 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001180
Chris Lattner4088e2b2010-12-13 01:47:07 +00001181 // These values do not agree. Insert a select instruction before NT
1182 // that determines the right value.
1183 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001184 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001185 SI = cast<SelectInst>
1186 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1187 BB1V->getName()+"."+BB2V->getName()));
1188
Chris Lattner4088e2b2010-12-13 01:47:07 +00001189 // Make the PHI node use the select for all incoming values for BB1/BB2
1190 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1191 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1192 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001193 }
1194 }
1195
1196 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001197 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1198 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001199
Eli Friedmancb61afb2008-12-16 20:54:32 +00001200 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001201 return true;
1202}
1203
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001204/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001205/// check whether BBEnd has only two predecessors and the other predecessor
1206/// ends with an unconditional branch. If it is true, sink any common code
1207/// in the two predecessors to BBEnd.
1208static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1209 assert(BI1->isUnconditional());
1210 BasicBlock *BB1 = BI1->getParent();
1211 BasicBlock *BBEnd = BI1->getSuccessor(0);
1212
1213 // Check that BBEnd has two predecessors and the other predecessor ends with
1214 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001215 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1216 BasicBlock *Pred0 = *PI++;
1217 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001218 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001219 BasicBlock *Pred1 = *PI++;
1220 if (PI != PE) // More than two predecessors.
1221 return false;
1222 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001223 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1224 if (!BI2 || !BI2->isUnconditional())
1225 return false;
1226
1227 // Gather the PHI nodes in BBEnd.
Michael Liao5313da32014-12-23 08:26:55 +00001228 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
Craig Topperf40110f2014-04-25 05:29:35 +00001229 Instruction *FirstNonPhiInBBEnd = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001230 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
Manman Ren93ab6492012-09-20 22:37:36 +00001231 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1232 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001233 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Michael Liao5313da32014-12-23 08:26:55 +00001234 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
Manman Ren93ab6492012-09-20 22:37:36 +00001235 } else {
1236 FirstNonPhiInBBEnd = &*I;
1237 break;
1238 }
1239 }
1240 if (!FirstNonPhiInBBEnd)
1241 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001242
Manman Ren93ab6492012-09-20 22:37:36 +00001243 // This does very trivial matching, with limited scanning, to find identical
1244 // instructions in the two blocks. We scan backward for obviously identical
1245 // instructions in an identical order.
1246 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
Michael Liao5313da32014-12-23 08:26:55 +00001247 RE1 = BB1->getInstList().rend(),
1248 RI2 = BB2->getInstList().rbegin(),
1249 RE2 = BB2->getInstList().rend();
Manman Ren93ab6492012-09-20 22:37:36 +00001250 // Skip debug info.
1251 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1252 if (RI1 == RE1)
1253 return false;
1254 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1255 if (RI2 == RE2)
1256 return false;
1257 // Skip the unconditional branches.
1258 ++RI1;
1259 ++RI2;
1260
1261 bool Changed = false;
1262 while (RI1 != RE1 && RI2 != RE2) {
1263 // Skip debug info.
1264 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1265 if (RI1 == RE1)
1266 return Changed;
1267 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1268 if (RI2 == RE2)
1269 return Changed;
1270
1271 Instruction *I1 = &*RI1, *I2 = &*RI2;
Michael Liao5313da32014-12-23 08:26:55 +00001272 auto InstPair = std::make_pair(I1, I2);
Manman Ren93ab6492012-09-20 22:37:36 +00001273 // I1 and I2 should have a single use in the same PHI node, and they
1274 // perform the same operation.
1275 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1276 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1277 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
David Majnemerba275f92015-08-19 19:54:02 +00001278 I1->isEHPad() || I2->isEHPad() ||
Manman Ren93ab6492012-09-20 22:37:36 +00001279 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1280 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1281 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1282 !I1->hasOneUse() || !I2->hasOneUse() ||
Michael Liao5313da32014-12-23 08:26:55 +00001283 !JointValueMap.count(InstPair))
Manman Ren93ab6492012-09-20 22:37:36 +00001284 return Changed;
1285
1286 // Check whether we should swap the operands of ICmpInst.
Michael Liao5313da32014-12-23 08:26:55 +00001287 // TODO: Add support of communativity.
Manman Ren93ab6492012-09-20 22:37:36 +00001288 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1289 bool SwapOpnds = false;
1290 if (ICmp1 && ICmp2 &&
1291 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1292 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1293 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1294 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1295 ICmp2->swapOperands();
1296 SwapOpnds = true;
1297 }
1298 if (!I1->isSameOperationAs(I2)) {
1299 if (SwapOpnds)
1300 ICmp2->swapOperands();
1301 return Changed;
1302 }
1303
1304 // The operands should be either the same or they need to be generated
1305 // with a PHI node after sinking. We only handle the case where there is
1306 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001307 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001308 unsigned Op1Idx = ~0U;
Manman Ren93ab6492012-09-20 22:37:36 +00001309 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1310 if (I1->getOperand(I) == I2->getOperand(I))
1311 continue;
Michael Liao5313da32014-12-23 08:26:55 +00001312 // Early exit if we have more-than one pair of different operands or if
1313 // we need a PHI node to replace a constant.
1314 if (Op1Idx != ~0U ||
Manman Ren93ab6492012-09-20 22:37:36 +00001315 isa<Constant>(I1->getOperand(I)) ||
1316 isa<Constant>(I2->getOperand(I))) {
1317 // If we can't sink the instructions, undo the swapping.
1318 if (SwapOpnds)
1319 ICmp2->swapOperands();
1320 return Changed;
1321 }
1322 DifferentOp1 = I1->getOperand(I);
1323 Op1Idx = I;
1324 DifferentOp2 = I2->getOperand(I);
1325 }
1326
Michael Liao5313da32014-12-23 08:26:55 +00001327 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1328 DEBUG(dbgs() << " " << *I2 << "\n");
1329
1330 // We insert the pair of different operands to JointValueMap and
1331 // remove (I1, I2) from JointValueMap.
1332 if (Op1Idx != ~0U) {
1333 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1334 if (!NewPN) {
1335 NewPN =
1336 PHINode::Create(DifferentOp1->getType(), 2,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001337 DifferentOp1->getName() + ".sink", &BBEnd->front());
Michael Liao5313da32014-12-23 08:26:55 +00001338 NewPN->addIncoming(DifferentOp1, BB1);
1339 NewPN->addIncoming(DifferentOp2, BB2);
1340 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1341 }
Manman Ren93ab6492012-09-20 22:37:36 +00001342 // I1 should use NewPN instead of DifferentOp1.
1343 I1->setOperand(Op1Idx, NewPN);
Manman Ren93ab6492012-09-20 22:37:36 +00001344 }
Michael Liao5313da32014-12-23 08:26:55 +00001345 PHINode *OldPN = JointValueMap[InstPair];
1346 JointValueMap.erase(InstPair);
Manman Ren93ab6492012-09-20 22:37:36 +00001347
Manman Ren93ab6492012-09-20 22:37:36 +00001348 // We need to update RE1 and RE2 if we are going to sink the first
1349 // instruction in the basic block down.
1350 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1351 // Sink the instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001352 BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(),
1353 BB1->getInstList(), I1);
Manman Ren93ab6492012-09-20 22:37:36 +00001354 if (!OldPN->use_empty())
1355 OldPN->replaceAllUsesWith(I1);
1356 OldPN->eraseFromParent();
1357
1358 if (!I2->use_empty())
1359 I2->replaceAllUsesWith(I1);
1360 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001361 // TODO: Use combineMetadata here to preserve what metadata we can
1362 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001363 I2->eraseFromParent();
1364
1365 if (UpdateRE1)
1366 RE1 = BB1->getInstList().rend();
1367 if (UpdateRE2)
1368 RE2 = BB2->getInstList().rend();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001369 FirstNonPhiInBBEnd = &*I1;
Manman Ren93ab6492012-09-20 22:37:36 +00001370 NumSinkCommons++;
1371 Changed = true;
1372 }
1373 return Changed;
1374}
1375
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001376/// \brief Determine if we can hoist sink a sole store instruction out of a
1377/// conditional block.
1378///
1379/// We are looking for code like the following:
1380/// BrBB:
1381/// store i32 %add, i32* %arrayidx2
1382/// ... // No other stores or function calls (we could be calling a memory
1383/// ... // function).
1384/// %cmp = icmp ult %x, %y
1385/// br i1 %cmp, label %EndBB, label %ThenBB
1386/// ThenBB:
1387/// store i32 %add5, i32* %arrayidx2
1388/// br label EndBB
1389/// EndBB:
1390/// ...
1391/// We are going to transform this into:
1392/// BrBB:
1393/// store i32 %add, i32* %arrayidx2
1394/// ... //
1395/// %cmp = icmp ult %x, %y
1396/// %add.add5 = select i1 %cmp, i32 %add, %add5
1397/// store i32 %add.add5, i32* %arrayidx2
1398/// ...
1399///
1400/// \return The pointer to the value of the previous store if the store can be
1401/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001402static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1403 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001404 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1405 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001406 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001407
1408 // Volatile or atomic.
1409 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001410 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001411
1412 Value *StorePtr = StoreToHoist->getPointerOperand();
1413
1414 // Look for a store to the same pointer in BrBB.
1415 unsigned MaxNumInstToLookAt = 10;
1416 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1417 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1418 Instruction *CurI = &*RI;
1419
1420 // Could be calling an instruction that effects memory like free().
1421 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001422 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001423
1424 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1425 // Found the previous store make sure it stores to the same location.
1426 if (SI && SI->getPointerOperand() == StorePtr)
1427 // Found the previous store, return its value operand.
1428 return SI->getValueOperand();
1429 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001430 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001431 }
1432
Craig Topperf40110f2014-04-25 05:29:35 +00001433 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001434}
1435
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001436/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001437///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001438/// Note that this is a very risky transform currently. Speculating
1439/// instructions like this is most often not desirable. Instead, there is an MI
1440/// pass which can do it with full awareness of the resource constraints.
1441/// However, some cases are "obvious" and we should do directly. An example of
1442/// this is speculating a single, reasonably cheap instruction.
1443///
1444/// There is only one distinct advantage to flattening the CFG at the IR level:
1445/// it makes very common but simplistic optimizations such as are common in
1446/// instcombine and the DAG combiner more powerful by removing CFG edges and
1447/// modeling their effects with easier to reason about SSA value graphs.
1448///
1449///
1450/// An illustration of this transform is turning this IR:
1451/// \code
1452/// BB:
1453/// %cmp = icmp ult %x, %y
1454/// br i1 %cmp, label %EndBB, label %ThenBB
1455/// ThenBB:
1456/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001457/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001458/// EndBB:
1459/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1460/// ...
1461/// \endcode
1462///
1463/// Into this IR:
1464/// \code
1465/// BB:
1466/// %cmp = icmp ult %x, %y
1467/// %sub = sub %x, %y
1468/// %cond = select i1 %cmp, 0, %sub
1469/// ...
1470/// \endcode
1471///
1472/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001473static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001474 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001475 // Be conservative for now. FP select instruction can often be expensive.
1476 Value *BrCond = BI->getCondition();
1477 if (isa<FCmpInst>(BrCond))
1478 return false;
1479
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001480 BasicBlock *BB = BI->getParent();
1481 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1482
1483 // If ThenBB is actually on the false edge of the conditional branch, remember
1484 // to swap the select operands later.
1485 bool Invert = false;
1486 if (ThenBB != BI->getSuccessor(0)) {
1487 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1488 Invert = true;
1489 }
1490 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1491
Chandler Carruthceff2222013-01-25 05:40:09 +00001492 // Keep a count of how many times instructions are used within CondBB when
1493 // they are candidates for sinking into CondBB. Specifically:
1494 // - They are defined in BB, and
1495 // - They have no side effects, and
1496 // - All of their uses are in CondBB.
1497 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1498
Chandler Carruth7481ca82013-01-24 11:52:58 +00001499 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001500 Value *SpeculatedStoreValue = nullptr;
1501 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001502 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001503 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001504 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001505 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001506 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001507 if (isa<DbgInfoIntrinsic>(I))
1508 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001509
Mark Lacey274f48b2015-04-12 18:18:51 +00001510 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001511 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001512 ++SpeculationCost;
1513 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001514 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001515
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001516 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001517 if (!isSafeToSpeculativelyExecute(I) &&
1518 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1519 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001520 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001521 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001522 ComputeSpeculationCost(I, TTI) >
1523 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001524 return false;
1525
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001526 // Store the store speculation candidate.
1527 if (SpeculatedStoreValue)
1528 SpeculatedStore = cast<StoreInst>(I);
1529
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001530 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001531 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001532 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001533 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001534 i != e; ++i) {
1535 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001536 if (!OpI || OpI->getParent() != BB ||
1537 OpI->mayHaveSideEffects())
1538 continue; // Not a candidate for sinking.
1539
1540 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001541 }
1542 }
Evan Cheng89200c92008-06-07 08:52:29 +00001543
Chandler Carruthceff2222013-01-25 05:40:09 +00001544 // Consider any sink candidates which are only used in CondBB as costs for
1545 // speculation. Note, while we iterate over a DenseMap here, we are summing
1546 // and so iteration order isn't significant.
1547 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1548 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1549 I != E; ++I)
1550 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001551 ++SpeculationCost;
1552 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001553 return false;
1554 }
1555
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001556 // Check that the PHI nodes can be converted to selects.
1557 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001558 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001559 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001560 Value *OrigV = PN->getIncomingValueForBlock(BB);
1561 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001562
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001563 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001564 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001565 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001566 continue;
1567
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001568 // Don't convert to selects if we could remove undefined behavior instead.
1569 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1570 passingValueIsAlwaysUndefined(ThenV, PN))
1571 return false;
1572
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001573 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001574 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1575 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1576 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001577 continue; // Known safe and cheap.
1578
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001579 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1580 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001581 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001582 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1583 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
James Molloy7c336572015-02-11 12:15:41 +00001584 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1585 TargetTransformInfo::TCC_Basic;
1586 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00001587 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001588
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001589 // Account for the cost of an unfolded ConstantExpr which could end up
1590 // getting expanded into Instructions.
1591 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001592 // constant expression.
1593 ++SpeculationCost;
1594 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001595 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001596 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001597
1598 // If there are no PHIs to process, bail early. This helps ensure idempotence
1599 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001600 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001601 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001602
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001603 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001604 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001605
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001606 // Insert a select of the value of the speculated store.
1607 if (SpeculatedStoreValue) {
1608 IRBuilder<true, NoFolder> Builder(BI);
1609 Value *TrueV = SpeculatedStore->getValueOperand();
1610 Value *FalseV = SpeculatedStoreValue;
1611 if (Invert)
1612 std::swap(TrueV, FalseV);
1613 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1614 "." + FalseV->getName());
1615 SpeculatedStore->setOperand(0, S);
1616 }
1617
Chandler Carruth7481ca82013-01-24 11:52:58 +00001618 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001619 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
1620 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001621
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001622 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001623 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001624 for (BasicBlock::iterator I = EndBB->begin();
1625 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1626 unsigned OrigI = PN->getBasicBlockIndex(BB);
1627 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1628 Value *OrigV = PN->getIncomingValue(OrigI);
1629 Value *ThenV = PN->getIncomingValue(ThenI);
1630
1631 // Skip PHIs which are trivial.
1632 if (OrigV == ThenV)
1633 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001634
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001635 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001636 // false value is the preexisting value. Swap them if the branch
1637 // destinations were inverted.
1638 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001639 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001640 std::swap(TrueV, FalseV);
1641 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1642 TrueV->getName() + "." + FalseV->getName());
1643 PN->setIncomingValue(OrigI, V);
1644 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001645 }
1646
Evan Cheng89553cc2008-06-12 21:15:59 +00001647 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001648 return true;
1649}
1650
Tom Stellarde1631dd2013-10-21 20:07:30 +00001651/// \returns True if this block contains a CallInst with the NoDuplicate
1652/// attribute.
1653static bool HasNoDuplicateCall(const BasicBlock *BB) {
1654 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1655 const CallInst *CI = dyn_cast<CallInst>(I);
1656 if (!CI)
1657 continue;
1658 if (CI->cannotDuplicate())
1659 return true;
1660 }
1661 return false;
1662}
1663
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001664/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001665static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1666 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001667 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001668
Devang Patel84fceff2009-03-10 18:00:05 +00001669 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001670 if (isa<DbgInfoIntrinsic>(BBI))
1671 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001672 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001673 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001674
Dale Johannesened6f5a82009-03-12 23:18:09 +00001675 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001676 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001677 for (User *U : BBI->users()) {
1678 Instruction *UI = cast<Instruction>(U);
1679 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001680 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001681
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001682 // Looks ok, continue checking.
1683 }
Chris Lattner6c701062005-09-20 01:48:40 +00001684
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001685 return true;
1686}
1687
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001688/// If we have a conditional branch on a PHI node value that is defined in the
1689/// same block as the branch and if any PHI entries are constants, thread edges
1690/// corresponding to that entry to be branches to their ultimate destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001691static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001692 BasicBlock *BB = BI->getParent();
1693 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001694 // NOTE: we currently cannot transform this case if the PHI node is used
1695 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001696 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1697 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001698
Chris Lattner748f9032005-09-19 23:49:37 +00001699 // Degenerate case of a single entry PHI.
1700 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001701 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001702 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001703 }
1704
1705 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001706 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001707
Tom Stellarde1631dd2013-10-21 20:07:30 +00001708 if (HasNoDuplicateCall(BB)) return false;
1709
Chris Lattner748f9032005-09-19 23:49:37 +00001710 // Okay, this is a simple enough basic block. See if any phi values are
1711 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001712 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001713 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001714 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001715
Chris Lattner4088e2b2010-12-13 01:47:07 +00001716 // Okay, we now know that all edges from PredBB should be revectored to
1717 // branch to RealDest.
1718 BasicBlock *PredBB = PN->getIncomingBlock(i);
1719 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001720
Chris Lattner4088e2b2010-12-13 01:47:07 +00001721 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001722 // Skip if the predecessor's terminator is an indirect branch.
1723 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001724
Chris Lattner4088e2b2010-12-13 01:47:07 +00001725 // The dest block might have PHI nodes, other predecessors and other
1726 // difficult cases. Instead of being smart about this, just insert a new
1727 // block that jumps to the destination block, effectively splitting
1728 // the edge we are about to create.
1729 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1730 RealDest->getName()+".critedge",
1731 RealDest->getParent(), RealDest);
1732 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001733
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001734 // Update PHI nodes.
1735 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001736
1737 // BB may have instructions that are being threaded over. Clone these
1738 // instructions into EdgeBB. We know that there will be no uses of the
1739 // cloned instructions outside of EdgeBB.
1740 BasicBlock::iterator InsertPt = EdgeBB->begin();
1741 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1742 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1743 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1744 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1745 continue;
1746 }
1747 // Clone the instruction.
1748 Instruction *N = BBI->clone();
1749 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001750
Chris Lattner4088e2b2010-12-13 01:47:07 +00001751 // Update operands due to translation.
1752 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1753 i != e; ++i) {
1754 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1755 if (PI != TranslateMap.end())
1756 *i = PI->second;
1757 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001758
Chris Lattner4088e2b2010-12-13 01:47:07 +00001759 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001760 if (Value *V = SimplifyInstruction(N, DL)) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001761 TranslateMap[&*BBI] = V;
Chris Lattnerd7beca32010-12-14 06:17:25 +00001762 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001763 } else {
1764 // Insert the new instruction into its new home.
1765 EdgeBB->getInstList().insert(InsertPt, N);
1766 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001767 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001768 }
1769 }
1770
1771 // Loop over all of the edges from PredBB to BB, changing them to branch
1772 // to EdgeBB instead.
1773 TerminatorInst *PredBBTI = PredBB->getTerminator();
1774 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1775 if (PredBBTI->getSuccessor(i) == BB) {
1776 BB->removePredecessor(PredBB);
1777 PredBBTI->setSuccessor(i, EdgeBB);
1778 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001779
Chris Lattner4088e2b2010-12-13 01:47:07 +00001780 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001781 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001782 }
Chris Lattner748f9032005-09-19 23:49:37 +00001783
1784 return false;
1785}
1786
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001787/// Given a BB that starts with the specified two-entry PHI node,
1788/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001789static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1790 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001791 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1792 // statement", which has a very simple dominance structure. Basically, we
1793 // are trying to find the condition that is being branched on, which
1794 // subsequently causes this merge to happen. We really want control
1795 // dependence information for this check, but simplifycfg can't keep it up
1796 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001797 BasicBlock *BB = PN->getParent();
1798 BasicBlock *IfTrue, *IfFalse;
1799 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001800 if (!IfCond ||
1801 // Don't bother if the branch will be constant folded trivially.
1802 isa<ConstantInt>(IfCond))
1803 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001804
Chris Lattner95adf8f12006-11-18 19:19:36 +00001805 // Okay, we found that we can merge this two-entry phi node into a select.
1806 // Doing so would require us to fold *all* two entry phi nodes in this block.
1807 // At some point this becomes non-profitable (particularly if the target
1808 // doesn't support cmov's). Only do this transformation if there are two or
1809 // fewer PHI nodes in this block.
1810 unsigned NumPhis = 0;
1811 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1812 if (NumPhis > 2)
1813 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001814
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001815 // Loop over the PHI's seeing if we can promote them all to select
1816 // instructions. While we are at it, keep track of the instructions
1817 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001818 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001819 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1820 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00001821 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1822 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001823
Chris Lattner7499b452010-12-14 08:46:09 +00001824 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1825 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001826 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001827 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001828 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001829 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001830 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001831
Peter Collingbournee3511e12011-04-29 18:47:31 +00001832 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001833 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001834 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001835 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001836 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001837 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001838
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001839 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001840 // we ran out of PHIs then we simplified them all.
1841 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001842 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001843
Chris Lattner7499b452010-12-14 08:46:09 +00001844 // Don't fold i1 branches on PHIs which contain binary operators. These can
1845 // often be turned into switches and other things.
1846 if (PN->getType()->isIntegerTy(1) &&
1847 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1848 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1849 isa<BinaryOperator>(IfCond)))
1850 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001851
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001852 // If we all PHI nodes are promotable, check to make sure that all
1853 // instructions in the predecessor blocks can be promoted as well. If
1854 // not, we won't be able to get rid of the control flow, so it's not
1855 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001856 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001857 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1858 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1859 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001860 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001861 } else {
1862 DomBlock = *pred_begin(IfBlock1);
1863 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001864 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001865 // This is not an aggressive instruction that we can promote.
1866 // Because of this, we won't be able to get rid of the control
1867 // flow, so the xform is not worth it.
1868 return false;
1869 }
1870 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001871
Chris Lattner9ac168d2010-12-14 07:41:39 +00001872 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001873 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001874 } else {
1875 DomBlock = *pred_begin(IfBlock2);
1876 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001877 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001878 // This is not an aggressive instruction that we can promote.
1879 // Because of this, we won't be able to get rid of the control
1880 // flow, so the xform is not worth it.
1881 return false;
1882 }
1883 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001884
Chris Lattner9fd838d2010-12-14 07:23:10 +00001885 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001886 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001887
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001888 // If we can still promote the PHI nodes after this gauntlet of tests,
1889 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001890 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001891 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001892
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001893 // Move all 'aggressive' instructions, which are defined in the
1894 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001895 if (IfBlock1)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001896 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001897 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001898 IfBlock1->getTerminator()->getIterator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001899 if (IfBlock2)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001900 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001901 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001902 IfBlock2->getTerminator()->getIterator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001903
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001904 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1905 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001906 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1907 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001908
1909 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001910 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001911 PN->replaceAllUsesWith(NV);
1912 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001913 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001914 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001915
Chris Lattner335f0e42010-12-14 08:01:53 +00001916 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1917 // has been flattened. Change DomBlock to jump directly to our new block to
1918 // avoid other simplifycfg's kicking in on the diamond.
1919 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001920 Builder.SetInsertPoint(OldTI);
1921 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001922 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001923 return true;
1924}
Chris Lattner748f9032005-09-19 23:49:37 +00001925
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001926/// If we found a conditional branch that goes to two returning blocks,
1927/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00001928/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001929static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001930 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001931 assert(BI->isConditional() && "Must be a conditional branch");
1932 BasicBlock *TrueSucc = BI->getSuccessor(0);
1933 BasicBlock *FalseSucc = BI->getSuccessor(1);
1934 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1935 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001936
Chris Lattner86bbf332008-04-24 00:01:19 +00001937 // Check to ensure both blocks are empty (just a return) or optionally empty
1938 // with PHI nodes. If there are other instructions, merging would cause extra
1939 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001940 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001941 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001942 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001943 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001944
Devang Pateldd14e0f2011-05-18 21:33:11 +00001945 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001946 // Okay, we found a branch that is going to two return nodes. If
1947 // there is no return value for this function, just change the
1948 // branch into a return.
1949 if (FalseRet->getNumOperands() == 0) {
1950 TrueSucc->removePredecessor(BI->getParent());
1951 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001952 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001953 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001954 return true;
1955 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001956
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001957 // Otherwise, figure out what the true and false return values are
1958 // so we can insert a new select instruction.
1959 Value *TrueValue = TrueRet->getReturnValue();
1960 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001961
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001962 // Unwrap any PHI nodes in the return blocks.
1963 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1964 if (TVPN->getParent() == TrueSucc)
1965 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1966 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1967 if (FVPN->getParent() == FalseSucc)
1968 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001969
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001970 // In order for this transformation to be safe, we must be able to
1971 // unconditionally execute both operands to the return. This is
1972 // normally the case, but we could have a potentially-trapping
1973 // constant expression that prevents this transformation from being
1974 // safe.
1975 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1976 if (TCV->canTrap())
1977 return false;
1978 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1979 if (FCV->canTrap())
1980 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001981
Chris Lattner86bbf332008-04-24 00:01:19 +00001982 // Okay, we collected all the mapped values and checked them for sanity, and
1983 // defined to really do this transformation. First, update the CFG.
1984 TrueSucc->removePredecessor(BI->getParent());
1985 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001986
Chris Lattner86bbf332008-04-24 00:01:19 +00001987 // Insert select instructions where needed.
1988 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001989 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001990 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001991 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1992 } else if (isa<UndefValue>(TrueValue)) {
1993 TrueValue = FalseValue;
1994 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00001995 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1996 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00001997 }
Chris Lattner86bbf332008-04-24 00:01:19 +00001998 }
1999
Andrew Trickf3cf1932012-08-29 21:46:36 +00002000 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00002001 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2002
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00002003 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002004
David Greene725c7c32010-01-05 01:26:52 +00002005 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002006 << "\n " << *BI << "NewRet = " << *RI
2007 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002008
Eli Friedmancb61afb2008-12-16 20:54:32 +00002009 EraseTerminatorInstAndDCECond(BI);
2010
Chris Lattner86bbf332008-04-24 00:01:19 +00002011 return true;
2012}
2013
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002014/// Given a conditional BranchInstruction, retrieve the probabilities of the
2015/// branch taking each edge. Fills in the two APInt parameters and returns true,
2016/// or returns false if no or invalid metadata was found.
Juergen Ributzka194350a2014-12-09 17:32:12 +00002017static bool ExtractBranchMetadata(BranchInst *BI,
2018 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2019 assert(BI->isConditional() &&
2020 "Looking for probabilities on unconditional branch?");
2021 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2022 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002023 ConstantInt *CITrue =
2024 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2025 ConstantInt *CIFalse =
2026 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00002027 if (!CITrue || !CIFalse) return false;
2028 ProbTrue = CITrue->getValue().getZExtValue();
2029 ProbFalse = CIFalse->getValue().getZExtValue();
2030 return true;
2031}
2032
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002033/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002034/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002035static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002036 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2037 return false;
2038 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2039 Instruction *PBI = &*I;
2040 // Check whether Inst and PBI generate the same value.
2041 if (Inst->isIdenticalTo(PBI)) {
2042 Inst->replaceAllUsesWith(PBI);
2043 Inst->eraseFromParent();
2044 return true;
2045 }
2046 }
2047 return false;
2048}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002049
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002050/// If this basic block is simple enough, and if a predecessor branches to us
2051/// and one of our successors, fold the block into the predecessor and use
2052/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002053bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002054 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002055
Craig Topperf40110f2014-04-25 05:29:35 +00002056 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002057 if (BI->isConditional())
2058 Cond = dyn_cast<Instruction>(BI->getCondition());
2059 else {
2060 // For unconditional branch, check for a simple CFG pattern, where
2061 // BB has a single predecessor and BB's successor is also its predecessor's
2062 // successor. If such pattern exisits, check for CSE between BB and its
2063 // predecessor.
2064 if (BasicBlock *PB = BB->getSinglePredecessor())
2065 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2066 if (PBI->isConditional() &&
2067 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2068 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2069 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2070 I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002071 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002072 if (isa<CmpInst>(Curr)) {
2073 Cond = Curr;
2074 break;
2075 }
2076 // Quit if we can't remove this instruction.
2077 if (!checkCSEInPredecessor(Curr, PB))
2078 return false;
2079 }
2080 }
2081
Craig Topperf40110f2014-04-25 05:29:35 +00002082 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002083 return false;
2084 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002085
Craig Topperf40110f2014-04-25 05:29:35 +00002086 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2087 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002088 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002089
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002090 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002091 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002092
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002093 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002094 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002095
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002096 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002097 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002098
Jingyue Wufc029672014-09-30 22:23:38 +00002099 // Only allow this transformation if computing the condition doesn't involve
2100 // too many instructions and these involved instructions can be executed
2101 // unconditionally. We denote all involved instructions except the condition
2102 // as "bonus instructions", and only allow this transformation when the
2103 // number of the bonus instructions does not exceed a certain threshold.
2104 unsigned NumBonusInsts = 0;
2105 for (auto I = BB->begin(); Cond != I; ++I) {
2106 // Ignore dbg intrinsics.
2107 if (isa<DbgInfoIntrinsic>(I))
2108 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002109 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002110 return false;
2111 // I has only one use and can be executed unconditionally.
2112 Instruction *User = dyn_cast<Instruction>(I->user_back());
2113 if (User == nullptr || User->getParent() != BB)
2114 return false;
2115 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2116 // to use any other instruction, User must be an instruction between next(I)
2117 // and Cond.
2118 ++NumBonusInsts;
2119 // Early exits once we reach the limit.
2120 if (NumBonusInsts > BonusInstThreshold)
2121 return false;
2122 }
2123
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002124 // Cond is known to be a compare or binary operator. Check to make sure that
2125 // neither operand is a potentially-trapping constant expression.
2126 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2127 if (CE->canTrap())
2128 return false;
2129 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2130 if (CE->canTrap())
2131 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002132
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002133 // Finally, don't infinitely unroll conditional loops.
2134 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002135 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002136 if (TrueDest == BB || FalseDest == BB)
2137 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002138
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002139 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2140 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002141 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002142
Chris Lattner80b03a12008-07-13 22:23:11 +00002143 // Check that we have two conditional branches. If there is a PHI node in
2144 // the common successor, verify that the same value flows in from both
2145 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002146 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002147 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002148 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002149 !SafeToMergeTerminators(BI, PBI)) ||
2150 (!BI->isConditional() &&
2151 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002152 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002153
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002154 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002155 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002156 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002157
Manman Rend33f4ef2012-06-13 05:43:29 +00002158 if (BI->isConditional()) {
2159 if (PBI->getSuccessor(0) == TrueDest)
2160 Opc = Instruction::Or;
2161 else if (PBI->getSuccessor(1) == FalseDest)
2162 Opc = Instruction::And;
2163 else if (PBI->getSuccessor(0) == FalseDest)
2164 Opc = Instruction::And, InvertPredCond = true;
2165 else if (PBI->getSuccessor(1) == TrueDest)
2166 Opc = Instruction::Or, InvertPredCond = true;
2167 else
2168 continue;
2169 } else {
2170 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2171 continue;
2172 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002173
David Greene725c7c32010-01-05 01:26:52 +00002174 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002175 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002176
Chris Lattner55eaae12008-07-13 21:20:19 +00002177 // If we need to invert the condition in the pred block to match, do so now.
2178 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002179 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002180
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002181 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2182 CmpInst *CI = cast<CmpInst>(NewCond);
2183 CI->setPredicate(CI->getInversePredicate());
2184 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002185 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002186 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002187 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002188
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002189 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002190 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002191 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002192
Jingyue Wufc029672014-09-30 22:23:38 +00002193 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002194 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002195 // bonus instructions to a predecessor block.
2196 ValueToValueMapTy VMap; // maps original values to cloned values
2197 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002198 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002199 // instructions.
2200 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2201 if (isa<DbgInfoIntrinsic>(BonusInst))
2202 continue;
2203 Instruction *NewBonusInst = BonusInst->clone();
2204 RemapInstruction(NewBonusInst, VMap,
2205 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002206 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002207
2208 // If we moved a load, we cannot any longer claim any knowledge about
2209 // its potential value. The previous information might have been valid
2210 // only given the branch precondition.
2211 // For an analogous reason, we must also drop all the metadata whose
2212 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002213 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002214
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002215 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2216 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002217 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002218 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002219
Chris Lattner55eaae12008-07-13 21:20:19 +00002220 // Clone Cond into the predecessor basic block, and or/and the
2221 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002222 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002223 RemapInstruction(New, VMap,
2224 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002225 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002226 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002227 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002228
Manman Rend33f4ef2012-06-13 05:43:29 +00002229 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002230 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002231 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002232 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002233 PBI->setCondition(NewCond);
2234
Manman Renbfb9d432012-09-15 00:39:57 +00002235 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002236 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2237 PredFalseWeight);
2238 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2239 SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002240 SmallVector<uint64_t, 8> NewWeights;
2241
Manman Rend33f4ef2012-06-13 05:43:29 +00002242 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002243 if (PredHasWeights && SuccHasWeights) {
2244 // PBI: br i1 %x, BB, FalseDest
2245 // BI: br i1 %y, TrueDest, FalseDest
2246 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2247 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2248 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2249 // TrueWeight for PBI * FalseWeight for BI.
2250 // We assume that total weights of a BranchInst can fit into 32 bits.
2251 // Therefore, we will not have overflow using 64-bit arithmetic.
2252 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2253 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2254 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002255 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2256 PBI->setSuccessor(0, TrueDest);
2257 }
2258 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002259 if (PredHasWeights && SuccHasWeights) {
2260 // PBI: br i1 %x, TrueDest, BB
2261 // BI: br i1 %y, TrueDest, FalseDest
2262 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2263 // FalseWeight for PBI * TrueWeight for BI.
2264 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2265 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2266 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2267 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2268 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002269 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2270 PBI->setSuccessor(1, FalseDest);
2271 }
Manman Renbfb9d432012-09-15 00:39:57 +00002272 if (NewWeights.size() == 2) {
2273 // Halve the weights if any of them cannot fit in an uint32_t
2274 FitWeights(NewWeights);
2275
2276 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2277 PBI->setMetadata(LLVMContext::MD_prof,
2278 MDBuilder(BI->getContext()).
2279 createBranchWeights(MDWeights));
2280 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002281 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002282 } else {
2283 // Update PHI nodes in the common successors.
2284 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002285 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002286 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2287 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002288 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002289 if (PBI->getSuccessor(0) == TrueDest) {
2290 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2291 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2292 // is false: !PBI_Cond and BI_Value
2293 Instruction *NotCond =
2294 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2295 "not.cond"));
2296 MergedCond =
2297 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2298 NotCond, New,
2299 "and.cond"));
2300 if (PBI_C->isOne())
2301 MergedCond =
2302 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2303 PBI->getCondition(), MergedCond,
2304 "or.cond"));
2305 } else {
2306 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2307 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2308 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002309 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002310 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2311 PBI->getCondition(), New,
2312 "and.cond"));
2313 if (PBI_C->isOne()) {
2314 Instruction *NotCond =
2315 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2316 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002317 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002318 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2319 NotCond, MergedCond,
2320 "or.cond"));
2321 }
2322 }
2323 // Update PHI Node.
2324 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2325 MergedCond);
2326 }
2327 // Change PBI from Conditional to Unconditional.
2328 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2329 EraseTerminatorInstAndDCECond(PBI);
2330 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002331 }
Devang Pateld715ec82011-04-06 22:37:20 +00002332
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002333 // TODO: If BB is reachable from all paths through PredBlock, then we
2334 // could replace PBI's branch probabilities with BI's.
2335
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002336 // Copy any debug value intrinsics into the end of PredBlock.
2337 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2338 if (isa<DbgInfoIntrinsic>(*I))
2339 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002340
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002341 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002342 }
2343 return false;
2344}
2345
Philip Reamesb42db212015-10-14 22:46:19 +00002346
2347/// Return true if B is known to be implied by A. A & B must be i1 (boolean)
2348static bool implies(Value *A, Value *B, const DataLayout &DL) {
2349 assert(A->getType()->isIntegerTy(1) && B->getType()->isIntegerTy(1));
2350 // Note that the truth table for implication is the same as <=u on i1
2351 // values.
2352 Value *Simplified = SimplifyICmpInst(ICmpInst::ICMP_ULE, A, B, DL);
2353 Constant *Con = dyn_cast_or_null<Constant>(Simplified);
2354 return Con && Con->isOneValue();
2355}
2356
2357/// If we have a series of tests leading to a frequently executed fallthrough
2358/// path and we can test all the conditions at once, we can execute a single
2359/// test on the fast path and figure out which condition failed on the slow
2360/// path. This transformation considers a pair of branches at a time since
2361/// recursively considering branches pairwise will cause an entire chain to
2362/// collapse. This transformation is code size neutral, but makes it
2363/// dynamically more expensive to fail either check. As such, we only want to
2364/// do this if both checks are expected to essentially never fail.
2365/// The key motivating examples are cases like:
2366/// br (i < Length), in_bounds, fail1
2367/// in_bounds:
2368/// br (i+1 < Length), in_bounds2, fail2
2369/// in_bounds2:
2370/// ...
2371///
2372/// We can rewrite this as:
2373/// br (i+1 < Length), in_bounds2, dispatch
2374/// in_bounds2:
2375/// ...
2376/// dispatch:
2377/// br (i < Length), fail2, fail1
2378///
2379/// TODO: we could consider duplicating some (non-speculatable) instructions
2380/// from BI->getParent() down both paths
2381static bool SpeculativelyFlattenCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
2382 const DataLayout &DL) {
2383 auto *PredBB = PBI->getParent();
2384 auto *BB = BI->getParent();
2385
2386 /// Is the failing path of this branch taken rarely if at all?
2387 auto isRarelyUntaken = [](BranchInst *BI) {
2388 uint64_t ProbTrue;
2389 uint64_t ProbFalse;
2390 if (!ExtractBranchMetadata(BI, ProbTrue, ProbFalse))
2391 return false;
2392 return ProbTrue > ProbFalse * SpeculativeFlattenBias;
2393 };
2394
2395 if (PBI->getSuccessor(0) != BB ||
2396 !isRarelyUntaken(PBI) || !isRarelyUntaken(BI) ||
2397 !implies(BI->getCondition(), PBI->getCondition(), DL))
2398 return false;
2399
2400 // TODO: The following code performs a similiar, but slightly distinct
2401 // transformation to that done by SpeculativelyExecuteBB. We should consider
2402 // combining them at some point.
2403
2404 // Can we speculate everything in the given block (except for the terminator
2405 // instruction) at the instruction boundary before 'At'?
2406 unsigned SpeculationCost = 0;
2407 for (Instruction &I : *BB) {
2408 if (isa<TerminatorInst>(I)) break;
2409 if (!isSafeToSpeculativelyExecute(&I, PBI))
2410 return false;
2411 SpeculationCost++;
2412 // Only flatten relatively small BBs to avoid making the bad case terrible
2413 if (SpeculationCost > SpeculativeFlattenThreshold || isa<CallInst>(I))
2414 return false;
2415 }
2416
2417 DEBUG(dbgs() << "Outlining slow path comparison: "
2418 << *PBI->getCondition() << " implied by "
2419 << *BI->getCondition() << "\n");
2420 // See the example in the function comment.
2421 Value *WhichCond = PBI->getCondition();
2422 auto *Success = BI->getSuccessor(0);
2423 auto *FailPBI = PBI->getSuccessor(1);
2424 auto *FailBI = BI->getSuccessor(1);
2425 // Have PBI branch directly to the fast path using BI's condition, branch
2426 // to this BI's block for the slow path dispatch
2427 PBI->setSuccessor(0, Success);
2428 PBI->setSuccessor(1, BB);
2429 PBI->setCondition(BI->getCondition());
2430 // Rewrite BI to distinguish between the two failing cases
2431 BI->setSuccessor(0, FailBI);
2432 BI->setSuccessor(1, FailPBI);
2433 BI->setCondition(WhichCond);
2434 // Move all of the instructions from BI->getParent other than
2435 // the terminator into the fastpath. This requires speculating them past
2436 // the original PBI branch, but we checked for that legality above.
2437 // TODO: This doesn't handle dependent loads. We could duplicate those
2438 // down both paths, but that involves further code growth. We need to
2439 // figure out a good cost model here.
2440 PredBB->getInstList().splice(PBI, BB->getInstList(),
2441 BB->begin(), std::prev(BB->end()));
2442
2443 // To be conservatively correct, drop all metadata on the rewritten
2444 // branches. TODO: update metadata
2445 PBI->dropUnknownNonDebugMetadata();
2446 BI->dropUnknownNonDebugMetadata();
2447 return true;
2448}
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002449/// If we have a conditional branch as a predecessor of another block,
2450/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00002451/// that PBI and BI are both conditional branches, and BI is in one of the
2452/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00002453static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
2454 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00002455 assert(PBI->isConditional() && BI->isConditional());
2456 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002457
Chris Lattner9aada1d2008-07-13 21:53:26 +00002458 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002459 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002460 // this conditional branch redundant.
2461 if (PBI->getCondition() == BI->getCondition() &&
2462 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2463 // Okay, the outcome of this conditional branch is statically
2464 // knowable. If this block had a single pred, handle specially.
2465 if (BB->getSinglePredecessor()) {
2466 // Turn this into a branch on constant.
2467 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002468 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002469 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002470 return true; // Nuke the branch on constant.
2471 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002472
Chris Lattner9aada1d2008-07-13 21:53:26 +00002473 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2474 // in the constant and simplify the block result. Subsequent passes of
2475 // simplifycfg will thread the block.
2476 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002477 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002478 PHINode *NewPN = PHINode::Create(
2479 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
2480 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00002481 // Okay, we're going to insert the PHI node. Since PBI is not the only
2482 // predecessor, compute the PHI'd conditional value for all of the preds.
2483 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002484 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002485 BasicBlock *P = *PI;
2486 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002487 PBI != BI && PBI->isConditional() &&
2488 PBI->getCondition() == BI->getCondition() &&
2489 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2490 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002491 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002492 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002493 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002494 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002495 }
Gabor Greif8629f122010-07-12 10:59:23 +00002496 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002497
Chris Lattner9aada1d2008-07-13 21:53:26 +00002498 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002499 return true;
2500 }
2501 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002502
Philip Reamesb42db212015-10-14 22:46:19 +00002503 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2504 if (CE->canTrap())
2505 return false;
2506
2507 if (SpeculativelyFlattenCondBranchToCondBranch(PBI, BI, DL))
2508 return true;
2509
Chris Lattner9aada1d2008-07-13 21:53:26 +00002510 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002511 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002512 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002513 BasicBlock::iterator BBI = BB->begin();
2514 // Ignore dbg intrinsics.
2515 while (isa<DbgInfoIntrinsic>(BBI))
2516 ++BBI;
2517 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002518 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002519
Chris Lattner834ab4e2008-07-13 22:04:41 +00002520 int PBIOp, BIOp;
2521 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2522 PBIOp = BIOp = 0;
2523 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2524 PBIOp = 0, BIOp = 1;
2525 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2526 PBIOp = 1, BIOp = 0;
2527 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2528 PBIOp = BIOp = 1;
2529 else
2530 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002531
Chris Lattner834ab4e2008-07-13 22:04:41 +00002532 // Check to make sure that the other destination of this branch
2533 // isn't BB itself. If so, this is an infinite loop that will
2534 // keep getting unwound.
2535 if (PBI->getSuccessor(PBIOp) == BB)
2536 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002537
2538 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002539 // insertion of a large number of select instructions. For targets
2540 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002541
Sanjay Patela932da82014-07-07 21:19:00 +00002542 // Also do not perform this transformation if any phi node in the common
2543 // destination block can trap when reached by BB or PBB (PR17073). In that
2544 // case, it would be unsafe to hoist the operation into a select instruction.
2545
2546 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002547 unsigned NumPhis = 0;
2548 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002549 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002550 if (NumPhis > 2) // Disable this xform.
2551 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002552
Sanjay Patela932da82014-07-07 21:19:00 +00002553 PHINode *PN = cast<PHINode>(II);
2554 Value *BIV = PN->getIncomingValueForBlock(BB);
2555 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2556 if (CE->canTrap())
2557 return false;
2558
2559 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2560 Value *PBIV = PN->getIncomingValue(PBBIdx);
2561 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2562 if (CE->canTrap())
2563 return false;
2564 }
2565
Chris Lattner834ab4e2008-07-13 22:04:41 +00002566 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002567 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002568
David Greene725c7c32010-01-05 01:26:52 +00002569 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002570 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002571
2572
Chris Lattner80b03a12008-07-13 22:23:11 +00002573 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2574 // branch in it, where one edge (OtherDest) goes back to itself but the other
2575 // exits. We don't *know* that the program avoids the infinite loop
2576 // (even though that seems likely). If we do this xform naively, we'll end up
2577 // recursively unpeeling the loop. Since we know that (after the xform is
2578 // done) that the block *is* infinite if reached, we just make it an obviously
2579 // infinite loop with no cond branch.
2580 if (OtherDest == BB) {
2581 // Insert it at the end of the function, because it's either code,
2582 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002583 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2584 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002585 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2586 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002587 }
2588
David Greene725c7c32010-01-05 01:26:52 +00002589 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002590
Chris Lattner834ab4e2008-07-13 22:04:41 +00002591 // BI may have other predecessors. Because of this, we leave
2592 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002593
Chris Lattner834ab4e2008-07-13 22:04:41 +00002594 // Make sure we get to CommonDest on True&True directions.
2595 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002596 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002597 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002598 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2599
Chris Lattner834ab4e2008-07-13 22:04:41 +00002600 Value *BICond = BI->getCondition();
2601 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002602 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2603
Chris Lattner834ab4e2008-07-13 22:04:41 +00002604 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002605 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002606
Chris Lattner834ab4e2008-07-13 22:04:41 +00002607 // Modify PBI to branch on the new condition to the new dests.
2608 PBI->setCondition(Cond);
2609 PBI->setSuccessor(0, CommonDest);
2610 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002611
Manman Ren2d4c10f2012-09-17 21:30:40 +00002612 // Update branch weight for PBI.
2613 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002614 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2615 PredFalseWeight);
2616 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2617 SuccFalseWeight);
Manman Ren2d4c10f2012-09-17 21:30:40 +00002618 if (PredHasWeights && SuccHasWeights) {
2619 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2620 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2621 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2622 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2623 // The weight to CommonDest should be PredCommon * SuccTotal +
2624 // PredOther * SuccCommon.
2625 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00002626 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2627 PredOther * SuccCommon,
2628 PredOther * SuccOther};
Manman Ren2d4c10f2012-09-17 21:30:40 +00002629 // Halve the weights if any of them cannot fit in an uint32_t
2630 FitWeights(NewWeights);
2631
Manman Ren2d4c10f2012-09-17 21:30:40 +00002632 PBI->setMetadata(LLVMContext::MD_prof,
Benjamin Kramerea68a942015-02-19 15:26:17 +00002633 MDBuilder(BI->getContext())
2634 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00002635 }
2636
Chris Lattner834ab4e2008-07-13 22:04:41 +00002637 // OtherDest may have phi nodes. If so, add an entry from PBI's
2638 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002639 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002640
Chris Lattner834ab4e2008-07-13 22:04:41 +00002641 // We know that the CommonDest already had an edge from PBI to
2642 // it. If it has PHIs though, the PHIs may have different
2643 // entries for BB and PBI's BB. If so, insert a select to make
2644 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002645 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002646 for (BasicBlock::iterator II = CommonDest->begin();
2647 (PN = dyn_cast<PHINode>(II)); ++II) {
2648 Value *BIV = PN->getIncomingValueForBlock(BB);
2649 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2650 Value *PBIV = PN->getIncomingValue(PBBIdx);
2651 if (BIV != PBIV) {
2652 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002653 Value *NV = cast<SelectInst>
2654 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002655 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002656 }
2657 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002658
David Greene725c7c32010-01-05 01:26:52 +00002659 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2660 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002661
Chris Lattner834ab4e2008-07-13 22:04:41 +00002662 // This basic block is probably dead. We know it has at least
2663 // one fewer predecessor.
2664 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002665}
2666
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002667// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2668// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00002669// Takes care of updating the successors and removing the old terminator.
2670// Also makes sure not to introduce new successors by assuming that edges to
2671// non-successor TrueBBs and FalseBBs aren't reachable.
2672static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002673 BasicBlock *TrueBB, BasicBlock *FalseBB,
2674 uint32_t TrueWeight,
2675 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002676 // Remove any superfluous successor edges from the CFG.
2677 // First, figure out which successors to preserve.
2678 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2679 // successor.
2680 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002681 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002682
2683 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00002684 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002685 // Make sure only to keep exactly one copy of each edge.
2686 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002687 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002688 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002689 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002690 else
2691 Succ->removePredecessor(OldTerm->getParent());
2692 }
2693
Devang Patel2c2ea222011-05-18 18:43:31 +00002694 IRBuilder<> Builder(OldTerm);
2695 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2696
Frits van Bommel8e158492011-01-11 12:52:11 +00002697 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002698 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002699 if (TrueBB == FalseBB)
2700 // We were only looking for one successor, and it was present.
2701 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002702 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002703 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002704 // We found both of the successors we were looking for.
2705 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002706 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2707 if (TrueWeight != FalseWeight)
2708 NewBI->setMetadata(LLVMContext::MD_prof,
2709 MDBuilder(OldTerm->getContext()).
2710 createBranchWeights(TrueWeight, FalseWeight));
2711 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002712 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2713 // Neither of the selected blocks were successors, so this
2714 // terminator must be unreachable.
2715 new UnreachableInst(OldTerm->getContext(), OldTerm);
2716 } else {
2717 // One of the selected values was a successor, but the other wasn't.
2718 // Insert an unconditional branch to the one that was found;
2719 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002720 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002721 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002722 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002723 else
2724 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002725 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002726 }
2727
2728 EraseTerminatorInstAndDCECond(OldTerm);
2729 return true;
2730}
2731
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002732// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00002733// (switch (select cond, X, Y)) on constant X, Y
2734// with a branch - conditional if X and Y lead to distinct BBs,
2735// unconditional otherwise.
2736static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2737 // Check for constant integer values in the select.
2738 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2739 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2740 if (!TrueVal || !FalseVal)
2741 return false;
2742
2743 // Find the relevant condition and destinations.
2744 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002745 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2746 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002747
Manman Ren774246a2012-09-17 22:28:55 +00002748 // Get weight for TrueBB and FalseBB.
2749 uint32_t TrueWeight = 0, FalseWeight = 0;
2750 SmallVector<uint64_t, 8> Weights;
2751 bool HasWeights = HasBranchWeights(SI);
2752 if (HasWeights) {
2753 GetBranchWeights(SI, Weights);
2754 if (Weights.size() == 1 + SI->getNumCases()) {
2755 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2756 getSuccessorIndex()];
2757 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2758 getSuccessorIndex()];
2759 }
2760 }
2761
Frits van Bommel8ae07992011-02-28 09:44:07 +00002762 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002763 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2764 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002765}
2766
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002767// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002768// (indirectbr (select cond, blockaddress(@fn, BlockA),
2769// blockaddress(@fn, BlockB)))
2770// with
2771// (br cond, BlockA, BlockB).
2772static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2773 // Check that both operands of the select are block addresses.
2774 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2775 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2776 if (!TBA || !FBA)
2777 return false;
2778
2779 // Extract the actual blocks.
2780 BasicBlock *TrueBB = TBA->getBasicBlock();
2781 BasicBlock *FalseBB = FBA->getBasicBlock();
2782
Frits van Bommel8e158492011-01-11 12:52:11 +00002783 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002784 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2785 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002786}
2787
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002788/// This is called when we find an icmp instruction
2789/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002790/// block that ends with an uncond branch. We are looking for a very specific
2791/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2792/// this case, we merge the first two "or's of icmp" into a switch, but then the
2793/// default value goes to an uncond block with a seteq in it, we get something
2794/// like:
2795///
2796/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2797/// DEFAULT:
2798/// %tmp = icmp eq i8 %A, 92
2799/// br label %end
2800/// end:
2801/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00002802///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002803/// We prefer to split the edge to 'end' so that there is a true/false entry to
2804/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00002805static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002806 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
2807 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
2808 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002809 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00002810
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002811 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2812 // complex.
2813 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2814
2815 Value *V = ICI->getOperand(0);
2816 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002817
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002818 // The pattern we're looking for is where our only predecessor is a switch on
2819 // 'V' and this block is the default case for the switch. In this case we can
2820 // fold the compared value into the switch to simplify things.
2821 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00002822 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002823
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002824 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2825 if (SI->getCondition() != V)
2826 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002827
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002828 // If BB is reachable on a non-default case, then we simply know the value of
2829 // V in this block. Substitute it and constant fold the icmp instruction
2830 // away.
2831 if (SI->getDefaultDest() != BB) {
2832 ConstantInt *VVal = SI->findCaseDest(BB);
2833 assert(VVal && "Should have a unique destination value");
2834 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002835
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002836 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00002837 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002838 ICI->eraseFromParent();
2839 }
2840 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002841 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002842 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002843
Chris Lattner62cc76e2010-12-13 03:43:57 +00002844 // Ok, the block is reachable from the default dest. If the constant we're
2845 // comparing exists in one of the other edges, then we can constant fold ICI
2846 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002847 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00002848 Value *V;
2849 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2850 V = ConstantInt::getFalse(BB->getContext());
2851 else
2852 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002853
Chris Lattner62cc76e2010-12-13 03:43:57 +00002854 ICI->replaceAllUsesWith(V);
2855 ICI->eraseFromParent();
2856 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002857 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00002858 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002859
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002860 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2861 // the block.
2862 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00002863 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00002864 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002865 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2866 return false;
2867
2868 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2869 // true in the PHI.
2870 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2871 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2872
2873 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2874 std::swap(DefaultCst, NewCst);
2875
2876 // Replace ICI (which is used by the PHI for the default value) with true or
2877 // false depending on if it is EQ or NE.
2878 ICI->replaceAllUsesWith(DefaultCst);
2879 ICI->eraseFromParent();
2880
2881 // Okay, the switch goes to this block on a default value. Add an edge from
2882 // the switch to the merge point on the compared value.
2883 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2884 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00002885 SmallVector<uint64_t, 8> Weights;
2886 bool HasWeights = HasBranchWeights(SI);
2887 if (HasWeights) {
2888 GetBranchWeights(SI, Weights);
2889 if (Weights.size() == 1 + SI->getNumCases()) {
2890 // Split weight for default case to case for "Cst".
2891 Weights[0] = (Weights[0]+1) >> 1;
2892 Weights.push_back(Weights[0]);
2893
2894 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2895 SI->setMetadata(LLVMContext::MD_prof,
2896 MDBuilder(SI->getContext()).
2897 createBranchWeights(MDWeights));
2898 }
2899 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002900 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002901
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002902 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00002903 Builder.SetInsertPoint(NewBB);
2904 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2905 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002906 PHIUse->addIncoming(NewCst, NewBB);
2907 return true;
2908}
2909
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002910/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00002911/// Check to see if it is branching on an or/and chain of icmp instructions, and
2912/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002913static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
2914 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00002915 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00002916 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002917
Chris Lattnera69c4432010-12-13 05:03:41 +00002918 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2919 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2920 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002921
Mehdi Amini9a25cb82014-11-19 20:09:11 +00002922 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00002923 ConstantComparesGatherer ConstantCompare(Cond, DL);
2924 // Unpack the result
2925 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
2926 Value *CompVal = ConstantCompare.CompValue;
2927 unsigned UsedICmps = ConstantCompare.UsedICmps;
2928 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002929
Chris Lattnera69c4432010-12-13 05:03:41 +00002930 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00002931 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00002932
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002933 // Avoid turning single icmps into a switch.
2934 if (UsedICmps <= 1)
2935 return false;
2936
Mehdi Aminiffd01002014-11-20 22:40:25 +00002937 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
2938
Chris Lattnera69c4432010-12-13 05:03:41 +00002939 // There might be duplicate constants in the list, which the switch
2940 // instruction can't handle, remove them now.
2941 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2942 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002943
Chris Lattnera69c4432010-12-13 05:03:41 +00002944 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00002945 // transformation. A switch with one value is just a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00002946 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002947
Andrew Trick3051aa12012-08-29 21:46:38 +00002948 // TODO: Preserve branch weight metadata, similarly to how
2949 // FoldValueComparisonIntoPredecessors preserves it.
2950
Chris Lattnera69c4432010-12-13 05:03:41 +00002951 // Figure out which block is which destination.
2952 BasicBlock *DefaultBB = BI->getSuccessor(1);
2953 BasicBlock *EdgeBB = BI->getSuccessor(0);
2954 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002955
Chris Lattnera69c4432010-12-13 05:03:41 +00002956 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002957
Chris Lattnerd7beca32010-12-14 06:17:25 +00002958 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002959 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002960
Chris Lattnera69c4432010-12-13 05:03:41 +00002961 // If there are any extra values that couldn't be folded into the switch
2962 // then we evaluate them with an explicit branch first. Split the block
2963 // right before the condbr to handle it.
2964 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002965 BasicBlock *NewBB =
2966 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00002967 // Remove the uncond branch added to the old block.
2968 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00002969 Builder.SetInsertPoint(OldTI);
2970
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002971 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00002972 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002973 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00002974 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002975
Chris Lattnera69c4432010-12-13 05:03:41 +00002976 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002977
Chris Lattnercb570f82010-12-13 05:34:18 +00002978 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2979 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002980 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002981
Chris Lattnerd7beca32010-12-14 06:17:25 +00002982 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2983 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00002984 BB = NewBB;
2985 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00002986
2987 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00002988 // Convert pointer to int before we switch.
2989 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002990 CompVal = Builder.CreatePtrToInt(
2991 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00002992 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002993
Chris Lattnera69c4432010-12-13 05:03:41 +00002994 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00002995 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00002996
Chris Lattnera69c4432010-12-13 05:03:41 +00002997 // Add all of the 'cases' to the switch instruction.
2998 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2999 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003000
Chris Lattnera69c4432010-12-13 05:03:41 +00003001 // We added edges from PI to the EdgeBB. As such, if there were any
3002 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3003 // the number of edges added.
3004 for (BasicBlock::iterator BBI = EdgeBB->begin();
3005 isa<PHINode>(BBI); ++BBI) {
3006 PHINode *PN = cast<PHINode>(BBI);
3007 Value *InVal = PN->getIncomingValueForBlock(BB);
3008 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
3009 PN->addIncoming(InVal, BB);
3010 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003011
Chris Lattnera69c4432010-12-13 05:03:41 +00003012 // Erase the old branch instruction.
3013 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003014
Chris Lattnerd7beca32010-12-14 06:17:25 +00003015 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00003016 return true;
3017}
3018
Duncan Sands29192d02011-09-05 12:57:57 +00003019bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
3020 // If this is a trivial landing pad that just continues unwinding the caught
3021 // exception then zap the landing pad, turning its invokes into calls.
3022 BasicBlock *BB = RI->getParent();
3023 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
3024 if (RI->getValue() != LPInst)
3025 // Not a landing pad, or the resume is not unwinding the exception that
3026 // caused control to branch here.
3027 return false;
3028
3029 // Check that there are no other instructions except for debug intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003030 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
Duncan Sands29192d02011-09-05 12:57:57 +00003031 while (++I != E)
3032 if (!isa<DbgInfoIntrinsic>(I))
3033 return false;
3034
3035 // Turn all invokes that unwind here into calls and delete the basic block.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003036 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003037 BasicBlock *Pred = *PI++;
3038 removeUnwindEdge(Pred);
Duncan Sands29192d02011-09-05 12:57:57 +00003039 }
3040
Reid Klecknerf12b3342015-01-22 19:29:46 +00003041 // The landingpad is now unreachable. Zap it.
3042 BB->eraseFromParent();
3043 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00003044}
3045
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003046bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
3047 // If this is a trivial cleanup pad that executes no instructions, it can be
3048 // eliminated. If the cleanup pad continues to the caller, any predecessor
3049 // that is an EH pad will be updated to continue to the caller and any
3050 // predecessor that terminates with an invoke instruction will have its invoke
3051 // instruction converted to a call instruction. If the cleanup pad being
3052 // simplified does not continue to the caller, each predecessor will be
3053 // updated to continue to the unwind destination of the cleanup pad being
3054 // simplified.
3055 BasicBlock *BB = RI->getParent();
3056 Instruction *CPInst = dyn_cast<CleanupPadInst>(BB->getFirstNonPHI());
3057 if (!CPInst)
3058 // This isn't an empty cleanup.
3059 return false;
3060
3061 // Check that there are no other instructions except for debug intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003062 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003063 while (++I != E)
3064 if (!isa<DbgInfoIntrinsic>(I))
3065 return false;
3066
3067 // If the cleanup return we are simplifying unwinds to the caller, this
3068 // will set UnwindDest to nullptr.
3069 BasicBlock *UnwindDest = RI->getUnwindDest();
3070
3071 // We're about to remove BB from the control flow. Before we do, sink any
3072 // PHINodes into the unwind destination. Doing this before changing the
3073 // control flow avoids some potentially slow checks, since we can currently
3074 // be certain that UnwindDest and BB have no common predecessors (since they
3075 // are both EH pads).
3076 if (UnwindDest) {
3077 // First, go through the PHI nodes in UnwindDest and update any nodes that
3078 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003079 for (BasicBlock::iterator I = UnwindDest->begin(),
3080 IE = UnwindDest->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003081 I != IE; ++I) {
3082 PHINode *DestPN = cast<PHINode>(I);
3083
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003084 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003085 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003086 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003087 // This PHI node has an incoming value that corresponds to a control
3088 // path through the cleanup pad we are removing. If the incoming
3089 // value is in the cleanup pad, it must be a PHINode (because we
3090 // verified above that the block is otherwise empty). Otherwise, the
3091 // value is either a constant or a value that dominates the cleanup
3092 // pad being removed.
3093 //
3094 // Because BB and UnwindDest are both EH pads, all of their
3095 // predecessors must unwind to these blocks, and since no instruction
3096 // can have multiple unwind destinations, there will be no overlap in
3097 // incoming blocks between SrcPN and DestPN.
3098 Value *SrcVal = DestPN->getIncomingValue(Idx);
3099 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3100
3101 // Remove the entry for the block we are deleting.
3102 DestPN->removeIncomingValue(Idx, false);
3103
3104 if (SrcPN && SrcPN->getParent() == BB) {
3105 // If the incoming value was a PHI node in the cleanup pad we are
3106 // removing, we need to merge that PHI node's incoming values into
3107 // DestPN.
3108 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
3109 SrcIdx != SrcE; ++SrcIdx) {
3110 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3111 SrcPN->getIncomingBlock(SrcIdx));
3112 }
3113 } else {
3114 // Otherwise, the incoming value came from above BB and
3115 // so we can just reuse it. We must associate all of BB's
3116 // predecessors with this value.
3117 for (auto *pred : predecessors(BB)) {
3118 DestPN->addIncoming(SrcVal, pred);
3119 }
3120 }
3121 }
3122
3123 // Sink any remaining PHI nodes directly into UnwindDest.
3124 Instruction *InsertPt = UnwindDest->getFirstNonPHI();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003125 for (BasicBlock::iterator I = BB->begin(),
3126 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003127 I != IE;) {
3128 // The iterator must be incremented here because the instructions are
3129 // being moved to another block.
3130 PHINode *PN = cast<PHINode>(I++);
3131 if (PN->use_empty())
3132 // If the PHI node has no uses, just leave it. It will be erased
3133 // when we erase BB below.
3134 continue;
3135
3136 // Otherwise, sink this PHI node into UnwindDest.
3137 // Any predecessors to UnwindDest which are not already represented
3138 // must be back edges which inherit the value from the path through
3139 // BB. In this case, the PHI value must reference itself.
3140 for (auto *pred : predecessors(UnwindDest))
3141 if (pred != BB)
3142 PN->addIncoming(PN, pred);
3143 PN->moveBefore(InsertPt);
3144 }
3145 }
3146
3147 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3148 // The iterator must be updated here because we are removing this pred.
3149 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003150 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003151 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003152 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003153 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003154 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003155 }
3156 }
3157
3158 // The cleanup pad is now unreachable. Zap it.
3159 BB->eraseFromParent();
3160 return true;
3161}
3162
Devang Pateldd14e0f2011-05-18 21:33:11 +00003163bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003164 BasicBlock *BB = RI->getParent();
3165 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003166
Chris Lattner25c3af32010-12-13 06:25:44 +00003167 // Find predecessors that end with branches.
3168 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3169 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003170 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3171 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003172 TerminatorInst *PTI = P->getTerminator();
3173 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3174 if (BI->isUnconditional())
3175 UncondBranchPreds.push_back(P);
3176 else
3177 CondBranchPreds.push_back(BI);
3178 }
3179 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003180
Chris Lattner25c3af32010-12-13 06:25:44 +00003181 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00003182 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003183 while (!UncondBranchPreds.empty()) {
3184 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3185 DEBUG(dbgs() << "FOLDING: " << *BB
3186 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00003187 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00003188 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003189
Chris Lattner25c3af32010-12-13 06:25:44 +00003190 // If we eliminated all predecessors of the block, delete the block now.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003191 if (pred_empty(BB))
Chris Lattner25c3af32010-12-13 06:25:44 +00003192 // We know there are no successors, so just nuke the block.
3193 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003194
Chris Lattner25c3af32010-12-13 06:25:44 +00003195 return true;
3196 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003197
Chris Lattner25c3af32010-12-13 06:25:44 +00003198 // Check out all of the conditional branches going to this return
3199 // instruction. If any of them just select between returns, change the
3200 // branch itself into a select/return pair.
3201 while (!CondBranchPreds.empty()) {
3202 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003203
Chris Lattner25c3af32010-12-13 06:25:44 +00003204 // Check to see if the non-BB successor is also a return block.
3205 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3206 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003207 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003208 return true;
3209 }
3210 return false;
3211}
3212
Chris Lattner25c3af32010-12-13 06:25:44 +00003213bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3214 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003215
Chris Lattner25c3af32010-12-13 06:25:44 +00003216 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003217
Chris Lattner25c3af32010-12-13 06:25:44 +00003218 // If there are any instructions immediately before the unreachable that can
3219 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003220 while (UI->getIterator() != BB->begin()) {
3221 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00003222 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003223 // Do not delete instructions that can have side effects which might cause
3224 // the unreachable to not be reachable; specifically, calls and volatile
3225 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003226 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003227
3228 if (BBI->mayHaveSideEffects()) {
3229 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3230 if (SI->isVolatile())
3231 break;
3232 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3233 if (LI->isVolatile())
3234 break;
3235 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3236 if (RMWI->isVolatile())
3237 break;
3238 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3239 if (CXI->isVolatile())
3240 break;
3241 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3242 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003243 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003244 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003245 // Note that deleting LandingPad's here is in fact okay, although it
3246 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3247 // all the predecessors of this block will be the unwind edges of Invokes,
3248 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003249 }
3250
Eli Friedmanaac35b32011-03-09 00:48:33 +00003251 // Delete this instruction (any uses are guaranteed to be dead)
3252 if (!BBI->use_empty())
3253 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003254 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003255 Changed = true;
3256 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003257
Chris Lattner25c3af32010-12-13 06:25:44 +00003258 // If the unreachable instruction is the first in the block, take a gander
3259 // at all of the predecessors of this instruction, and simplify them.
3260 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003261
Chris Lattner25c3af32010-12-13 06:25:44 +00003262 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3263 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3264 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003265 IRBuilder<> Builder(TI);
Chris Lattner25c3af32010-12-13 06:25:44 +00003266 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3267 if (BI->isUnconditional()) {
3268 if (BI->getSuccessor(0) == BB) {
3269 new UnreachableInst(TI->getContext(), TI);
3270 TI->eraseFromParent();
3271 Changed = true;
3272 }
3273 } else {
3274 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003275 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003276 EraseTerminatorInstAndDCECond(BI);
3277 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003278 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003279 EraseTerminatorInstAndDCECond(BI);
3280 Changed = true;
3281 }
3282 }
3283 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003284 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003285 i != e; ++i)
3286 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003287 BB->removePredecessor(SI->getParent());
3288 SI->removeCase(i);
3289 --i; --e;
3290 Changed = true;
3291 }
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003292 } else if ((isa<InvokeInst>(TI) &&
3293 cast<InvokeInst>(TI)->getUnwindDest() == BB) ||
3294 isa<CatchEndPadInst>(TI) || isa<TerminatePadInst>(TI)) {
3295 removeUnwindEdge(TI->getParent());
3296 Changed = true;
3297 } else if (isa<CleanupReturnInst>(TI) || isa<CleanupEndPadInst>(TI) ||
3298 isa<CatchReturnInst>(TI)) {
3299 new UnreachableInst(TI->getContext(), TI);
3300 TI->eraseFromParent();
3301 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00003302 }
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003303 // TODO: If TI is a CatchPadInst, then (BB must be its normal dest and)
3304 // we can eliminate it, redirecting its preds to its unwind successor,
3305 // or to the next outer handler if the removed catch is the last for its
3306 // catchendpad.
Chris Lattner25c3af32010-12-13 06:25:44 +00003307 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003308
Chris Lattner25c3af32010-12-13 06:25:44 +00003309 // If this block is now dead, remove it.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003310 if (pred_empty(BB) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00003311 BB != &BB->getParent()->getEntryBlock()) {
3312 // We know there are no successors, so just nuke the block.
3313 BB->eraseFromParent();
3314 return true;
3315 }
3316
3317 return Changed;
3318}
3319
Hans Wennborg68000082015-01-26 19:52:32 +00003320static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3321 assert(Cases.size() >= 1);
3322
3323 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3324 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3325 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3326 return false;
3327 }
3328 return true;
3329}
3330
3331/// Turn a switch with two reachable destinations into an integer range
3332/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003333static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003334 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003335
Hans Wennborg68000082015-01-26 19:52:32 +00003336 bool HasDefault =
3337 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003338
Hans Wennborg68000082015-01-26 19:52:32 +00003339 // Partition the cases into two sets with different destinations.
3340 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3341 BasicBlock *DestB = nullptr;
3342 SmallVector <ConstantInt *, 16> CasesA;
3343 SmallVector <ConstantInt *, 16> CasesB;
3344
3345 for (SwitchInst::CaseIt I : SI->cases()) {
3346 BasicBlock *Dest = I.getCaseSuccessor();
3347 if (!DestA) DestA = Dest;
3348 if (Dest == DestA) {
3349 CasesA.push_back(I.getCaseValue());
3350 continue;
3351 }
3352 if (!DestB) DestB = Dest;
3353 if (Dest == DestB) {
3354 CasesB.push_back(I.getCaseValue());
3355 continue;
3356 }
3357 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003358 }
3359
Hans Wennborg68000082015-01-26 19:52:32 +00003360 assert(DestA && DestB && "Single-destination switch should have been folded.");
3361 assert(DestA != DestB);
3362 assert(DestB != SI->getDefaultDest());
3363 assert(!CasesB.empty() && "There must be non-default cases.");
3364 assert(!CasesA.empty() || HasDefault);
3365
3366 // Figure out if one of the sets of cases form a contiguous range.
3367 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3368 BasicBlock *ContiguousDest = nullptr;
3369 BasicBlock *OtherDest = nullptr;
3370 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3371 ContiguousCases = &CasesA;
3372 ContiguousDest = DestA;
3373 OtherDest = DestB;
3374 } else if (CasesAreContiguous(CasesB)) {
3375 ContiguousCases = &CasesB;
3376 ContiguousDest = DestB;
3377 OtherDest = DestA;
3378 } else
3379 return false;
3380
3381 // Start building the compare and branch.
3382
3383 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3384 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003385
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003386 Value *Sub = SI->getCondition();
3387 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00003388 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3389
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003390 Value *Cmp;
3391 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00003392 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003393 Cmp = ConstantInt::getTrue(SI->getContext());
3394 else
3395 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00003396 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003397
Manman Ren56575552012-09-18 00:47:33 +00003398 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00003399 if (HasBranchWeights(SI)) {
3400 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00003401 GetBranchWeights(SI, Weights);
3402 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00003403 uint64_t TrueWeight = 0;
3404 uint64_t FalseWeight = 0;
3405 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3406 if (SI->getSuccessor(I) == ContiguousDest)
3407 TrueWeight += Weights[I];
3408 else
3409 FalseWeight += Weights[I];
3410 }
3411 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3412 TrueWeight /= 2;
3413 FalseWeight /= 2;
3414 }
Manman Ren56575552012-09-18 00:47:33 +00003415 NewBI->setMetadata(LLVMContext::MD_prof,
Hans Wennborg68000082015-01-26 19:52:32 +00003416 MDBuilder(SI->getContext()).createBranchWeights(
3417 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00003418 }
3419 }
3420
Hans Wennborg68000082015-01-26 19:52:32 +00003421 // Prune obsolete incoming values off the successors' PHI nodes.
3422 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3423 unsigned PreviousEdges = ContiguousCases->size();
3424 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3425 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003426 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3427 }
Hans Wennborg68000082015-01-26 19:52:32 +00003428 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3429 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3430 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3431 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3432 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3433 }
3434
3435 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003436 SI->eraseFromParent();
3437
3438 return true;
3439}
Chris Lattner25c3af32010-12-13 06:25:44 +00003440
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003441/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003442/// and use it to remove dead cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003443static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3444 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003445 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003446 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003447 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003448 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003449
3450 // Gather dead cases.
3451 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003452 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003453 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3454 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3455 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003456 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003457 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003458 }
3459 }
3460
Philip Reames98a2dab2015-08-26 23:56:46 +00003461 // If we can prove that the cases must cover all possible values, the
Philip Reames05370132015-09-10 17:44:47 +00003462 // default destination becomes dead and we can remove it. If we know some
3463 // of the bits in the value, we can use that to more precisely compute the
3464 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00003465 bool HasDefault =
3466 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Philip Reames05370132015-09-10 17:44:47 +00003467 const unsigned NumUnknownBits = Bits -
3468 (KnownZero.Or(KnownOne)).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00003469 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00003470 if (HasDefault && DeadCases.empty() &&
3471 NumUnknownBits < 64 /* avoid overflow */ &&
3472 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00003473 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
3474 BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(),
3475 SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003476 SI->setDefaultDest(&*NewDefault);
3477 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00003478 auto *OldTI = NewDefault->getTerminator();
3479 new UnreachableInst(SI->getContext(), OldTI);
3480 EraseTerminatorInstAndDCECond(OldTI);
3481 return true;
3482 }
3483
Manman Ren56575552012-09-18 00:47:33 +00003484 SmallVector<uint64_t, 8> Weights;
3485 bool HasWeight = HasBranchWeights(SI);
3486 if (HasWeight) {
3487 GetBranchWeights(SI, Weights);
3488 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3489 }
3490
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003491 // Remove dead cases from the switch.
3492 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003493 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003494 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003495 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003496 if (HasWeight) {
3497 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3498 Weights.pop_back();
3499 }
3500
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003501 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003502 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003503 SI->removeCase(Case);
3504 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003505 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003506 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3507 SI->setMetadata(LLVMContext::MD_prof,
3508 MDBuilder(SI->getParent()->getContext()).
3509 createBranchWeights(MDWeights));
3510 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003511
3512 return !DeadCases.empty();
3513}
3514
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003515/// If BB would be eligible for simplification by
3516/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003517/// by an unconditional branch), look at the phi node for BB in the successor
3518/// block and see if the incoming value is equal to CaseValue. If so, return
3519/// the phi node, and set PhiIndex to BB's index in the phi node.
3520static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3521 BasicBlock *BB,
3522 int *PhiIndex) {
3523 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003524 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003525 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003526 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003527
3528 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3529 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003530 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003531
3532 BasicBlock *Succ = Branch->getSuccessor(0);
3533
3534 BasicBlock::iterator I = Succ->begin();
3535 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3536 int Idx = PHI->getBasicBlockIndex(BB);
3537 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3538
3539 Value *InValue = PHI->getIncomingValue(Idx);
3540 if (InValue != CaseValue) continue;
3541
3542 *PhiIndex = Idx;
3543 return PHI;
3544 }
3545
Craig Topperf40110f2014-04-25 05:29:35 +00003546 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003547}
3548
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003549/// Try to forward the condition of a switch instruction to a phi node
3550/// dominated by the switch, if that would mean that some of the destination
3551/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003552/// Returns true if a change is made.
3553static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3554 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3555 ForwardingNodesMap ForwardingNodes;
3556
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003557 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003558 ConstantInt *CaseValue = I.getCaseValue();
3559 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003560
3561 int PhiIndex;
3562 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3563 &PhiIndex);
3564 if (!PHI) continue;
3565
3566 ForwardingNodes[PHI].push_back(PhiIndex);
3567 }
3568
3569 bool Changed = false;
3570
3571 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3572 E = ForwardingNodes.end(); I != E; ++I) {
3573 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003574 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003575
3576 if (Indexes.size() < 2) continue;
3577
3578 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3579 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3580 Changed = true;
3581 }
3582
3583 return Changed;
3584}
3585
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003586/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003587/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003588static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003589 if (C->isThreadDependent())
3590 return false;
3591 if (C->isDLLImportDependent())
3592 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003593
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003594 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3595 return CE->isGEPWithNoNotionalOverIndexing();
3596
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003597 return isa<ConstantFP>(C) ||
3598 isa<ConstantInt>(C) ||
3599 isa<ConstantPointerNull>(C) ||
3600 isa<GlobalValue>(C) ||
3601 isa<UndefValue>(C);
3602}
3603
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003604/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003605/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003606static Constant *LookupConstant(Value *V,
3607 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3608 if (Constant *C = dyn_cast<Constant>(V))
3609 return C;
3610 return ConstantPool.lookup(V);
3611}
3612
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003613/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003614/// simple instructions such as binary operations where both operands are
3615/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003616/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003617static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003618ConstantFold(Instruction *I, const DataLayout &DL,
3619 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003620 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003621 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3622 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003623 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003624 if (A->isAllOnesValue())
3625 return LookupConstant(Select->getTrueValue(), ConstantPool);
3626 if (A->isNullValue())
3627 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003628 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003629 }
3630
Benjamin Kramer7c302602013-11-12 12:24:36 +00003631 SmallVector<Constant *, 4> COps;
3632 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3633 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3634 COps.push_back(A);
3635 else
Craig Topperf40110f2014-04-25 05:29:35 +00003636 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003637 }
3638
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003639 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00003640 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3641 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003642 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00003643
3644 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003645}
3646
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003647/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003648/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003649/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003650/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003651static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003652GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00003653 BasicBlock **CommonDest,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003654 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
3655 const DataLayout &DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003656 // The block from which we enter the common destination.
3657 BasicBlock *Pred = SI->getParent();
3658
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003659 // If CaseDest is empty except for some side-effect free instructions through
3660 // which we can constant-propagate the CaseVal, continue to its successor.
3661 SmallDenseMap<Value*, Constant*> ConstantPool;
3662 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3663 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3664 ++I) {
3665 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3666 // If the terminator is a simple branch, continue to the next block.
3667 if (T->getNumSuccessors() != 1)
3668 return false;
3669 Pred = CaseDest;
3670 CaseDest = T->getSuccessor(0);
3671 } else if (isa<DbgInfoIntrinsic>(I)) {
3672 // Skip debug intrinsic.
3673 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003674 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003675 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00003676
3677 // If the instruction has uses outside this block or a phi node slot for
3678 // the block, it is not safe to bypass the instruction since it would then
3679 // no longer dominate all its uses.
3680 for (auto &Use : I->uses()) {
3681 User *User = Use.getUser();
3682 if (Instruction *I = dyn_cast<Instruction>(User))
3683 if (I->getParent() == CaseDest)
3684 continue;
3685 if (PHINode *Phi = dyn_cast<PHINode>(User))
3686 if (Phi->getIncomingBlock(Use) == CaseDest)
3687 continue;
3688 return false;
3689 }
3690
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003691 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003692 } else {
3693 break;
3694 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003695 }
3696
3697 // If we did not have a CommonDest before, use the current one.
3698 if (!*CommonDest)
3699 *CommonDest = CaseDest;
3700 // If the destination isn't the common one, abort.
3701 if (CaseDest != *CommonDest)
3702 return false;
3703
3704 // Get the values for this case from phi nodes in the destination block.
3705 BasicBlock::iterator I = (*CommonDest)->begin();
3706 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3707 int Idx = PHI->getBasicBlockIndex(Pred);
3708 if (Idx == -1)
3709 continue;
3710
Hans Wennborg09acdb92012-10-31 15:14:39 +00003711 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3712 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003713 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003714 return false;
3715
3716 // Be conservative about which kinds of constants we support.
3717 if (!ValidLookupTableConstant(ConstVal))
3718 return false;
3719
3720 Res.push_back(std::make_pair(PHI, ConstVal));
3721 }
3722
Hans Wennborgac114a32014-01-12 00:44:41 +00003723 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003724}
3725
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003726// Helper function used to add CaseVal to the list of cases that generate
3727// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003728static void MapCaseToResult(ConstantInt *CaseVal,
3729 SwitchCaseResultVectorTy &UniqueResults,
3730 Constant *Result) {
3731 for (auto &I : UniqueResults) {
3732 if (I.first == Result) {
3733 I.second.push_back(CaseVal);
3734 return;
3735 }
3736 }
3737 UniqueResults.push_back(std::make_pair(Result,
3738 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3739}
3740
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003741// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003742// results for the PHI node of the common destination block for a switch
3743// instruction. Returns false if multiple PHI nodes have been found or if
3744// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003745static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
3746 BasicBlock *&CommonDest,
3747 SwitchCaseResultVectorTy &UniqueResults,
3748 Constant *&DefaultResult,
3749 const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003750 for (auto &I : SI->cases()) {
3751 ConstantInt *CaseVal = I.getCaseValue();
3752
3753 // Resulting value at phi nodes for this case value.
3754 SwitchCaseResultsTy Results;
3755 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3756 DL))
3757 return false;
3758
3759 // Only one value per case is permitted
3760 if (Results.size() > 1)
3761 return false;
3762 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3763
3764 // Check the PHI consistency.
3765 if (!PHI)
3766 PHI = Results[0].first;
3767 else if (PHI != Results[0].first)
3768 return false;
3769 }
3770 // Find the default result value.
3771 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3772 BasicBlock *DefaultDest = SI->getDefaultDest();
3773 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3774 DL);
3775 // If the default value is not found abort unless the default destination
3776 // is unreachable.
3777 DefaultResult =
3778 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3779 if ((!DefaultResult &&
3780 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3781 return false;
3782
3783 return true;
3784}
3785
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003786// Helper function that checks if it is possible to transform a switch with only
3787// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003788// Example:
3789// switch (a) {
3790// case 10: %0 = icmp eq i32 %a, 10
3791// return 10; %1 = select i1 %0, i32 10, i32 4
3792// case 20: ----> %2 = icmp eq i32 %a, 20
3793// return 2; %3 = select i1 %2, i32 2, i32 %1
3794// default:
3795// return 4;
3796// }
3797static Value *
3798ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3799 Constant *DefaultResult, Value *Condition,
3800 IRBuilder<> &Builder) {
3801 assert(ResultVector.size() == 2 &&
3802 "We should have exactly two unique results at this point");
3803 // If we are selecting between only two cases transform into a simple
3804 // select or a two-way select if default is possible.
3805 if (ResultVector[0].second.size() == 1 &&
3806 ResultVector[1].second.size() == 1) {
3807 ConstantInt *const FirstCase = ResultVector[0].second[0];
3808 ConstantInt *const SecondCase = ResultVector[1].second[0];
3809
3810 bool DefaultCanTrigger = DefaultResult;
3811 Value *SelectValue = ResultVector[1].first;
3812 if (DefaultCanTrigger) {
3813 Value *const ValueCompare =
3814 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3815 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3816 DefaultResult, "switch.select");
3817 }
3818 Value *const ValueCompare =
3819 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3820 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3821 "switch.select");
3822 }
3823
3824 return nullptr;
3825}
3826
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003827// Helper function to cleanup a switch instruction that has been converted into
3828// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003829static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3830 Value *SelectValue,
3831 IRBuilder<> &Builder) {
3832 BasicBlock *SelectBB = SI->getParent();
3833 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3834 PHI->removeIncomingValue(SelectBB);
3835 PHI->addIncoming(SelectValue, SelectBB);
3836
3837 Builder.CreateBr(PHI->getParent());
3838
3839 // Remove the switch.
3840 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3841 BasicBlock *Succ = SI->getSuccessor(i);
3842
3843 if (Succ == PHI->getParent())
3844 continue;
3845 Succ->removePredecessor(SelectBB);
3846 }
3847 SI->eraseFromParent();
3848}
3849
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003850/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003851/// phi nodes in a common successor block with only two different
3852/// constant values, replace the switch with select.
3853static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003854 AssumptionCache *AC, const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003855 Value *const Cond = SI->getCondition();
3856 PHINode *PHI = nullptr;
3857 BasicBlock *CommonDest = nullptr;
3858 Constant *DefaultResult;
3859 SwitchCaseResultVectorTy UniqueResults;
3860 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003861 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
3862 DL))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003863 return false;
3864 // Selects choose between maximum two values.
3865 if (UniqueResults.size() != 2)
3866 return false;
3867 assert(PHI != nullptr && "PHI for value select not found");
3868
3869 Builder.SetInsertPoint(SI);
3870 Value *SelectValue = ConvertTwoCaseSwitch(
3871 UniqueResults,
3872 DefaultResult, Cond, Builder);
3873 if (SelectValue) {
3874 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3875 return true;
3876 }
3877 // The switch couldn't be converted into a select.
3878 return false;
3879}
3880
Hans Wennborg776d7122012-09-26 09:34:53 +00003881namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003882 /// This class represents a lookup table that can be used to replace a switch.
Hans Wennborg776d7122012-09-26 09:34:53 +00003883 class SwitchLookupTable {
3884 public:
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003885 /// Create a lookup table to use as a switch replacement with the contents
3886 /// of Values, using DefaultValue to fill any holes in the table.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003887 SwitchLookupTable(
3888 Module &M, uint64_t TableSize, ConstantInt *Offset,
3889 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
3890 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00003891
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003892 /// Build instructions with Builder to retrieve the value at
Hans Wennborg776d7122012-09-26 09:34:53 +00003893 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00003894 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00003895
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003896 /// Return true if a table with TableSize elements of
Hans Wennborg39583b82012-09-26 09:44:49 +00003897 /// type ElementType would fit in a target-legal register.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003898 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00003899 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003900
Hans Wennborg776d7122012-09-26 09:34:53 +00003901 private:
3902 // Depending on the contents of the table, it can be represented in
3903 // different ways.
3904 enum {
3905 // For tables where each element contains the same value, we just have to
3906 // store that single value and return it for each lookup.
3907 SingleValueKind,
3908
Erik Eckstein105374f2014-11-17 09:13:57 +00003909 // For tables where there is a linear relationship between table index
3910 // and values. We calculate the result with a simple multiplication
3911 // and addition instead of a table lookup.
3912 LinearMapKind,
3913
Hans Wennborg39583b82012-09-26 09:44:49 +00003914 // For small tables with integer elements, we can pack them into a bitmap
3915 // that fits into a target-legal register. Values are retrieved by
3916 // shift and mask operations.
3917 BitMapKind,
3918
Hans Wennborg776d7122012-09-26 09:34:53 +00003919 // The table is stored as an array of values. Values are retrieved by load
3920 // instructions from the table.
3921 ArrayKind
3922 } Kind;
3923
3924 // For SingleValueKind, this is the single value.
3925 Constant *SingleValue;
3926
Hans Wennborg39583b82012-09-26 09:44:49 +00003927 // For BitMapKind, this is the bitmap.
3928 ConstantInt *BitMap;
3929 IntegerType *BitMapElementTy;
3930
Erik Eckstein105374f2014-11-17 09:13:57 +00003931 // For LinearMapKind, these are the constants used to derive the value.
3932 ConstantInt *LinearOffset;
3933 ConstantInt *LinearMultiplier;
3934
Hans Wennborg776d7122012-09-26 09:34:53 +00003935 // For ArrayKind, this is the array.
3936 GlobalVariable *Array;
3937 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003938}
Hans Wennborg776d7122012-09-26 09:34:53 +00003939
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003940SwitchLookupTable::SwitchLookupTable(
3941 Module &M, uint64_t TableSize, ConstantInt *Offset,
3942 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
3943 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00003944 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00003945 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003946 assert(Values.size() && "Can't build lookup table without values!");
3947 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003948
3949 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00003950 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003951
Hans Wennborgac114a32014-01-12 00:44:41 +00003952 Type *ValueType = Values.begin()->second->getType();
3953
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003954 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00003955 SmallVector<Constant*, 64> TableContents(TableSize);
3956 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3957 ConstantInt *CaseVal = Values[I].first;
3958 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00003959 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003960
Hans Wennborg776d7122012-09-26 09:34:53 +00003961 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3962 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003963 TableContents[Idx] = CaseRes;
3964
Hans Wennborg776d7122012-09-26 09:34:53 +00003965 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003966 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003967 }
3968
3969 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00003970 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00003971 assert(DefaultValue &&
3972 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00003973 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00003974 for (uint64_t I = 0; I < TableSize; ++I) {
3975 if (!TableContents[I])
3976 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003977 }
3978
Hans Wennborg776d7122012-09-26 09:34:53 +00003979 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003980 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003981 }
3982
Hans Wennborg776d7122012-09-26 09:34:53 +00003983 // If each element in the table contains the same value, we only need to store
3984 // that single value.
3985 if (SingleValue) {
3986 Kind = SingleValueKind;
3987 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003988 }
3989
Erik Eckstein105374f2014-11-17 09:13:57 +00003990 // Check if we can derive the value with a linear transformation from the
3991 // table index.
3992 if (isa<IntegerType>(ValueType)) {
3993 bool LinearMappingPossible = true;
3994 APInt PrevVal;
3995 APInt DistToPrev;
3996 assert(TableSize >= 2 && "Should be a SingleValue table.");
3997 // Check if there is the same distance between two consecutive values.
3998 for (uint64_t I = 0; I < TableSize; ++I) {
3999 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4000 if (!ConstVal) {
4001 // This is an undef. We could deal with it, but undefs in lookup tables
4002 // are very seldom. It's probably not worth the additional complexity.
4003 LinearMappingPossible = false;
4004 break;
4005 }
4006 APInt Val = ConstVal->getValue();
4007 if (I != 0) {
4008 APInt Dist = Val - PrevVal;
4009 if (I == 1) {
4010 DistToPrev = Dist;
4011 } else if (Dist != DistToPrev) {
4012 LinearMappingPossible = false;
4013 break;
4014 }
4015 }
4016 PrevVal = Val;
4017 }
4018 if (LinearMappingPossible) {
4019 LinearOffset = cast<ConstantInt>(TableContents[0]);
4020 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4021 Kind = LinearMapKind;
4022 ++NumLinearMaps;
4023 return;
4024 }
4025 }
4026
Hans Wennborg39583b82012-09-26 09:44:49 +00004027 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004028 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004029 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004030 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4031 for (uint64_t I = TableSize; I > 0; --I) {
4032 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00004033 // Insert values into the bitmap. Undef values are set to zero.
4034 if (!isa<UndefValue>(TableContents[I - 1])) {
4035 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4036 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4037 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004038 }
4039 BitMap = ConstantInt::get(M.getContext(), TableInt);
4040 BitMapElementTy = IT;
4041 Kind = BitMapKind;
4042 ++NumBitMaps;
4043 return;
4044 }
4045
Hans Wennborg776d7122012-09-26 09:34:53 +00004046 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004047 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004048 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4049
Hans Wennborg776d7122012-09-26 09:34:53 +00004050 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
4051 GlobalVariable::PrivateLinkage,
4052 Initializer,
4053 "switch.table");
4054 Array->setUnnamedAddr(true);
4055 Kind = ArrayKind;
4056}
4057
Manman Ren4d189fb2014-07-24 21:13:20 +00004058Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004059 switch (Kind) {
4060 case SingleValueKind:
4061 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00004062 case LinearMapKind: {
4063 // Derive the result value from the input value.
4064 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4065 false, "switch.idx.cast");
4066 if (!LinearMultiplier->isOne())
4067 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4068 if (!LinearOffset->isZero())
4069 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4070 return Result;
4071 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004072 case BitMapKind: {
4073 // Type of the bitmap (e.g. i59).
4074 IntegerType *MapTy = BitMap->getType();
4075
4076 // Cast Index to the same type as the bitmap.
4077 // Note: The Index is <= the number of elements in the table, so
4078 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00004079 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004080
4081 // Multiply the shift amount by the element width.
4082 ShiftAmt = Builder.CreateMul(ShiftAmt,
4083 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4084 "switch.shiftamt");
4085
4086 // Shift down.
4087 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
4088 "switch.downshift");
4089 // Mask off.
4090 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
4091 "switch.masked");
4092 }
Hans Wennborg776d7122012-09-26 09:34:53 +00004093 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00004094 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00004095 IntegerType *IT = cast<IntegerType>(Index->getType());
4096 uint64_t TableSize = Array->getInitializer()->getType()
4097 ->getArrayNumElements();
4098 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4099 Index = Builder.CreateZExt(Index,
4100 IntegerType::get(IT->getContext(),
4101 IT->getBitWidth() + 1),
4102 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00004103
Hans Wennborg776d7122012-09-26 09:34:53 +00004104 Value *GEPIndices[] = { Builder.getInt32(0), Index };
David Blaikieaa41cd52015-04-03 21:33:42 +00004105 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4106 GEPIndices, "switch.gep");
Hans Wennborg776d7122012-09-26 09:34:53 +00004107 return Builder.CreateLoad(GEP, "switch.load");
4108 }
4109 }
4110 llvm_unreachable("Unknown lookup table kind!");
4111}
4112
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004113bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00004114 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004115 Type *ElementType) {
4116 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004117 if (!IT)
4118 return false;
4119 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4120 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004121
4122 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4123 if (TableSize >= UINT_MAX/IT->getBitWidth())
4124 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004125 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00004126}
4127
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004128/// Determine whether a lookup table should be built for this switch, based on
4129/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004130static bool
4131ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4132 const TargetTransformInfo &TTI, const DataLayout &DL,
4133 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004134 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4135 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00004136
Chandler Carruth77d433d2012-11-30 09:26:25 +00004137 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00004138 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00004139 for (const auto &I : ResultTypes) {
4140 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004141
4142 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004143 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004144
4145 // Saturate this flag to false.
4146 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004147 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004148
4149 // If both flags saturate, we're done. NOTE: This *only* works with
4150 // saturating flags, and all flags have to saturate first due to the
4151 // non-deterministic behavior of iterating over a dense map.
4152 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00004153 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00004154 }
Evan Cheng65df8082012-11-30 02:02:42 +00004155
Chandler Carruth77d433d2012-11-30 09:26:25 +00004156 // If each table would fit in a register, we should build it anyway.
4157 if (AllTablesFitInRegister)
4158 return true;
4159
4160 // Don't build a table that doesn't fit in-register if it has illegal types.
4161 if (HasIllegalType)
4162 return false;
4163
4164 // The table density should be at least 40%. This is the same criterion as for
4165 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4166 // FIXME: Find the best cut-off.
4167 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004168}
4169
Erik Eckstein0d86c762014-11-27 15:13:14 +00004170/// Try to reuse the switch table index compare. Following pattern:
4171/// \code
4172/// if (idx < tablesize)
4173/// r = table[idx]; // table does not contain default_value
4174/// else
4175/// r = default_value;
4176/// if (r != default_value)
4177/// ...
4178/// \endcode
4179/// Is optimized to:
4180/// \code
4181/// cond = idx < tablesize;
4182/// if (cond)
4183/// r = table[idx];
4184/// else
4185/// r = default_value;
4186/// if (cond)
4187/// ...
4188/// \endcode
4189/// Jump threading will then eliminate the second if(cond).
4190static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4191 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4192 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4193
4194 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4195 if (!CmpInst)
4196 return;
4197
4198 // We require that the compare is in the same block as the phi so that jump
4199 // threading can do its work afterwards.
4200 if (CmpInst->getParent() != PhiBlock)
4201 return;
4202
4203 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4204 if (!CmpOp1)
4205 return;
4206
4207 Value *RangeCmp = RangeCheckBranch->getCondition();
4208 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4209 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4210
4211 // Check if the compare with the default value is constant true or false.
4212 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4213 DefaultValue, CmpOp1, true);
4214 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4215 return;
4216
4217 // Check if the compare with the case values is distinct from the default
4218 // compare result.
4219 for (auto ValuePair : Values) {
4220 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4221 ValuePair.second, CmpOp1, true);
4222 if (!CaseConst || CaseConst == DefaultConst)
4223 return;
4224 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4225 "Expect true or false as compare result.");
4226 }
4227
4228 // Check if the branch instruction dominates the phi node. It's a simple
4229 // dominance check, but sufficient for our needs.
4230 // Although this check is invariant in the calling loops, it's better to do it
4231 // at this late stage. Practically we do it at most once for a switch.
4232 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4233 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4234 BasicBlock *Pred = *PI;
4235 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4236 return;
4237 }
4238
4239 if (DefaultConst == FalseConst) {
4240 // The compare yields the same result. We can replace it.
4241 CmpInst->replaceAllUsesWith(RangeCmp);
4242 ++NumTableCmpReuses;
4243 } else {
4244 // The compare yields the same result, just inverted. We can replace it.
4245 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4246 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4247 RangeCheckBranch);
4248 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4249 ++NumTableCmpReuses;
4250 }
4251}
4252
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004253/// If the switch is only used to initialize one or more phi nodes in a common
4254/// successor block with different constant values, replace the switch with
4255/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004256static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4257 const DataLayout &DL,
4258 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004259 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004260
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004261 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004262 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004263 return false;
4264
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004265 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4266 // split off a dense part and build a lookup table for that.
4267
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004268 // FIXME: This creates arrays of GEPs to constant strings, which means each
4269 // GEP needs a runtime relocation in PIC code. We should just build one big
4270 // string and lookup indices into that.
4271
Hans Wennborg4744ac12014-01-15 05:00:27 +00004272 // Ignore switches with less than three cases. Lookup tables will not make them
4273 // faster, so we don't analyze them.
4274 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004275 return false;
4276
4277 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00004278 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004279 assert(SI->case_begin() != SI->case_end());
4280 SwitchInst::CaseIt CI = SI->case_begin();
4281 ConstantInt *MinCaseVal = CI.getCaseValue();
4282 ConstantInt *MaxCaseVal = CI.getCaseValue();
4283
Craig Topperf40110f2014-04-25 05:29:35 +00004284 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004285 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004286 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4287 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4288 SmallDenseMap<PHINode*, Type*> ResultTypes;
4289 SmallVector<PHINode*, 4> PHIs;
4290
4291 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4292 ConstantInt *CaseVal = CI.getCaseValue();
4293 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4294 MinCaseVal = CaseVal;
4295 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4296 MaxCaseVal = CaseVal;
4297
4298 // Resulting value at phi nodes for this case value.
4299 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4300 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004301 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004302 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004303 return false;
4304
4305 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004306 for (const auto &I : Results) {
4307 PHINode *PHI = I.first;
4308 Constant *Value = I.second;
4309 if (!ResultLists.count(PHI))
4310 PHIs.push_back(PHI);
4311 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004312 }
4313 }
4314
Hans Wennborgac114a32014-01-12 00:44:41 +00004315 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004316 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004317 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4318 }
4319
4320 uint64_t NumResults = ResultLists[PHIs[0]].size();
4321 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4322 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4323 bool TableHasHoles = (NumResults < TableSize);
4324
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004325 // If the table has holes, we need a constant result for the default case
4326 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004327 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00004328 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004329 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00004330
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004331 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4332 if (NeedMask) {
4333 // As an extra penalty for the validity test we require more cases.
4334 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4335 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004336 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004337 return false;
4338 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004339
Hans Wennborga6a11a92014-11-18 02:37:11 +00004340 for (const auto &I : DefaultResultsList) {
4341 PHINode *PHI = I.first;
4342 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004343 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004344 }
4345
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004346 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004347 return false;
4348
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004349 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004350 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004351 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4352 "switch.lookup",
4353 CommonDest->getParent(),
4354 CommonDest);
4355
Michael Gottesmanc024f322013-10-20 07:04:37 +00004356 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004357 Builder.SetInsertPoint(SI);
4358 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4359 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004360
4361 // Compute the maximum table size representable by the integer type we are
4362 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004363 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004364 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004365 assert(MaxTableSize >= TableSize &&
4366 "It is impossible for a switch to have more entries than the max "
4367 "representable value of its input integer type's size.");
4368
Hans Wennborgb64cb272015-01-26 19:52:34 +00004369 // If the default destination is unreachable, or if the lookup table covers
4370 // all values of the conditional variable, branch directly to the lookup table
4371 // BB. Otherwise, check that the condition is within the case range.
4372 const bool DefaultIsReachable =
4373 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4374 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004375 BranchInst *RangeCheckBranch = nullptr;
4376
Hans Wennborgb64cb272015-01-26 19:52:34 +00004377 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00004378 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00004379 // Note: We call removeProdecessor later since we need to be able to get the
4380 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00004381 } else {
4382 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004383 MinCaseVal->getType(), TableSize));
Erik Eckstein0d86c762014-11-27 15:13:14 +00004384 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00004385 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004386
4387 // Populate the BB that does the lookups.
4388 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004389
4390 if (NeedMask) {
4391 // Before doing the lookup we do the hole check.
4392 // The LookupBB is therefore re-purposed to do the hole check
4393 // and we create a new LookupBB.
4394 BasicBlock *MaskBB = LookupBB;
4395 MaskBB->setName("switch.hole_check");
4396 LookupBB = BasicBlock::Create(Mod.getContext(),
4397 "switch.lookup",
4398 CommonDest->getParent(),
4399 CommonDest);
4400
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004401 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4402 // unnecessary illegal types.
4403 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4404 APInt MaskInt(TableSizePowOf2, 0);
4405 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004406 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004407 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4408 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4409 uint64_t Idx = (ResultList[I].first->getValue() -
4410 MinCaseVal->getValue()).getLimitedValue();
4411 MaskInt |= One << Idx;
4412 }
4413 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4414
4415 // Get the TableIndex'th bit of the bitmask.
4416 // If this bit is 0 (meaning hole) jump to the default destination,
4417 // else continue with table lookup.
4418 IntegerType *MapTy = TableMask->getType();
4419 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4420 "switch.maskindex");
4421 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4422 "switch.shifted");
4423 Value *LoBit = Builder.CreateTrunc(Shifted,
4424 Type::getInt1Ty(Mod.getContext()),
4425 "switch.lobit");
4426 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4427
4428 Builder.SetInsertPoint(LookupBB);
4429 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4430 }
4431
Hans Wennborg86ac6302015-04-24 20:57:56 +00004432 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4433 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4434 // do not delete PHINodes here.
4435 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4436 /*DontDeleteUselessPHIs=*/true);
4437 }
4438
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004439 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004440 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4441 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004442 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004443
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004444 // If using a bitmask, use any value to fill the lookup table holes.
4445 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004446 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004447
Manman Ren4d189fb2014-07-24 21:13:20 +00004448 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004449
Hans Wennborgf744fa92012-09-19 14:24:21 +00004450 // If the result is used to return immediately from the function, we want to
4451 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004452 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4453 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004454 Builder.CreateRet(Result);
4455 ReturnedEarly = true;
4456 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004457 }
4458
Erik Eckstein0d86c762014-11-27 15:13:14 +00004459 // Do a small peephole optimization: re-use the switch table compare if
4460 // possible.
4461 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4462 BasicBlock *PhiBlock = PHI->getParent();
4463 // Search for compare instructions which use the phi.
4464 for (auto *User : PHI->users()) {
4465 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4466 }
4467 }
4468
Hans Wennborgf744fa92012-09-19 14:24:21 +00004469 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004470 }
4471
4472 if (!ReturnedEarly)
4473 Builder.CreateBr(CommonDest);
4474
4475 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004476 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004477 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004478
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004479 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004480 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004481 Succ->removePredecessor(SI->getParent());
4482 }
4483 SI->eraseFromParent();
4484
4485 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004486 if (NeedMask)
4487 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004488 return true;
4489}
4490
Devang Patela7ec47d2011-05-18 20:35:38 +00004491bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004492 BasicBlock *BB = SI->getParent();
4493
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004494 if (isValueEqualityComparison(SI)) {
4495 // If we only have one predecessor, and if it is a branch on this value,
4496 // see if that predecessor totally determines the outcome of this switch.
4497 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4498 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004499 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004500
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004501 Value *Cond = SI->getCondition();
4502 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4503 if (SimplifySwitchOnSelect(SI, Select))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004504 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004505
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004506 // If the block only contains the switch, see if we can fold the block
4507 // away into any preds.
4508 BasicBlock::iterator BBI = BB->begin();
4509 // Ignore dbg intrinsics.
4510 while (isa<DbgInfoIntrinsic>(BBI))
4511 ++BBI;
4512 if (SI == &*BBI)
4513 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004514 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004515 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004516
4517 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004518 if (TurnSwitchRangeIntoICmp(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004519 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004520
4521 // Remove unreachable cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004522 if (EliminateDeadSwitchCases(SI, AC, DL))
4523 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004524
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004525 if (SwitchToSelect(SI, Builder, AC, DL))
4526 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004527
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004528 if (ForwardSwitchConditionToPHI(SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004529 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004530
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004531 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4532 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004533
Chris Lattner25c3af32010-12-13 06:25:44 +00004534 return false;
4535}
4536
4537bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4538 BasicBlock *BB = IBI->getParent();
4539 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004540
Chris Lattner25c3af32010-12-13 06:25:44 +00004541 // Eliminate redundant destinations.
4542 SmallPtrSet<Value *, 8> Succs;
4543 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4544 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004545 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004546 Dest->removePredecessor(BB);
4547 IBI->removeDestination(i);
4548 --i; --e;
4549 Changed = true;
4550 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004551 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004552
4553 if (IBI->getNumDestinations() == 0) {
4554 // If the indirectbr has no successors, change it to unreachable.
4555 new UnreachableInst(IBI->getContext(), IBI);
4556 EraseTerminatorInstAndDCECond(IBI);
4557 return true;
4558 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004559
Chris Lattner25c3af32010-12-13 06:25:44 +00004560 if (IBI->getNumDestinations() == 1) {
4561 // If the indirectbr has one successor, change it to a direct branch.
4562 BranchInst::Create(IBI->getDestination(0), IBI);
4563 EraseTerminatorInstAndDCECond(IBI);
4564 return true;
4565 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004566
Chris Lattner25c3af32010-12-13 06:25:44 +00004567 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4568 if (SimplifyIndirectBrOnSelect(IBI, SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004569 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004570 }
4571 return Changed;
4572}
4573
Philip Reames2b969d72015-03-24 22:28:45 +00004574/// Given an block with only a single landing pad and a unconditional branch
4575/// try to find another basic block which this one can be merged with. This
4576/// handles cases where we have multiple invokes with unique landing pads, but
4577/// a shared handler.
4578///
4579/// We specifically choose to not worry about merging non-empty blocks
4580/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4581/// practice, the optimizer produces empty landing pad blocks quite frequently
4582/// when dealing with exception dense code. (see: instcombine, gvn, if-else
4583/// sinking in this file)
4584///
4585/// This is primarily a code size optimization. We need to avoid performing
4586/// any transform which might inhibit optimization (such as our ability to
4587/// specialize a particular handler via tail commoning). We do this by not
4588/// merging any blocks which require us to introduce a phi. Since the same
4589/// values are flowing through both blocks, we don't loose any ability to
4590/// specialize. If anything, we make such specialization more likely.
4591///
4592/// TODO - This transformation could remove entries from a phi in the target
4593/// block when the inputs in the phi are the same for the two blocks being
4594/// merged. In some cases, this could result in removal of the PHI entirely.
4595static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
4596 BasicBlock *BB) {
4597 auto Succ = BB->getUniqueSuccessor();
4598 assert(Succ);
4599 // If there's a phi in the successor block, we'd likely have to introduce
4600 // a phi into the merged landing pad block.
4601 if (isa<PHINode>(*Succ->begin()))
4602 return false;
4603
4604 for (BasicBlock *OtherPred : predecessors(Succ)) {
4605 if (BB == OtherPred)
4606 continue;
4607 BasicBlock::iterator I = OtherPred->begin();
4608 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
4609 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
4610 continue;
4611 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4612 BranchInst *BI2 = dyn_cast<BranchInst>(I);
4613 if (!BI2 || !BI2->isIdenticalTo(BI))
4614 continue;
4615
4616 // We've found an identical block. Update our predeccessors to take that
4617 // path instead and make ourselves dead.
4618 SmallSet<BasicBlock *, 16> Preds;
4619 Preds.insert(pred_begin(BB), pred_end(BB));
4620 for (BasicBlock *Pred : Preds) {
4621 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
4622 assert(II->getNormalDest() != BB &&
4623 II->getUnwindDest() == BB && "unexpected successor");
4624 II->setUnwindDest(OtherPred);
4625 }
4626
4627 // The debug info in OtherPred doesn't cover the merged control flow that
4628 // used to go through BB. We need to delete it or update it.
4629 for (auto I = OtherPred->begin(), E = OtherPred->end();
4630 I != E;) {
4631 Instruction &Inst = *I; I++;
4632 if (isa<DbgInfoIntrinsic>(Inst))
4633 Inst.eraseFromParent();
4634 }
4635
4636 SmallSet<BasicBlock *, 16> Succs;
4637 Succs.insert(succ_begin(BB), succ_end(BB));
4638 for (BasicBlock *Succ : Succs) {
4639 Succ->removePredecessor(BB);
4640 }
4641
4642 IRBuilder<> Builder(BI);
4643 Builder.CreateUnreachable();
4644 BI->eraseFromParent();
4645 return true;
4646 }
4647 return false;
4648}
4649
Devang Patel767f6932011-05-18 18:28:48 +00004650bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00004651 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004652
Manman Ren93ab6492012-09-20 22:37:36 +00004653 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4654 return true;
4655
Chris Lattner25c3af32010-12-13 06:25:44 +00004656 // If the Terminator is the only non-phi instruction, simplify the block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004657 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00004658 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4659 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4660 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004661
Chris Lattner25c3af32010-12-13 06:25:44 +00004662 // If the only instruction in the block is a seteq/setne comparison
4663 // against a constant, try to simplify the block.
4664 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4665 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4666 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4667 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004668 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004669 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
4670 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00004671 return true;
4672 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004673
Philip Reames2b969d72015-03-24 22:28:45 +00004674 // See if we can merge an empty landing pad block with another which is
4675 // equivalent.
4676 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
4677 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4678 if (I->isTerminator() &&
4679 TryToMergeLandingPad(LPad, BI, BB))
4680 return true;
4681 }
4682
Manman Rend33f4ef2012-06-13 05:43:29 +00004683 // If this basic block is ONLY a compare and a branch, and if a predecessor
4684 // branches to us and our successor, fold the comparison into the
4685 // predecessor and use logical operations to update the incoming value
4686 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004687 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4688 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004689 return false;
4690}
4691
4692
Devang Patela7ec47d2011-05-18 20:35:38 +00004693bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004694 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004695
Chris Lattner25c3af32010-12-13 06:25:44 +00004696 // Conditional branch
4697 if (isValueEqualityComparison(BI)) {
4698 // If we only have one predecessor, and if it is a branch on this value,
4699 // see if that predecessor totally determines the outcome of this
4700 // switch.
4701 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00004702 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004703 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004704
Chris Lattner25c3af32010-12-13 06:25:44 +00004705 // This block must be empty, except for the setcond inst, if it exists.
4706 // Ignore dbg intrinsics.
4707 BasicBlock::iterator I = BB->begin();
4708 // Ignore dbg intrinsics.
4709 while (isa<DbgInfoIntrinsic>(I))
4710 ++I;
4711 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00004712 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004713 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004714 } else if (&*I == cast<Instruction>(BI->getCondition())){
4715 ++I;
4716 // Ignore dbg intrinsics.
4717 while (isa<DbgInfoIntrinsic>(I))
4718 ++I;
Devang Patel58380552011-05-18 20:53:17 +00004719 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004720 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004721 }
4722 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004723
Chris Lattner25c3af32010-12-13 06:25:44 +00004724 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004725 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00004726 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004727
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00004728 // If this basic block is ONLY a compare and a branch, and if a predecessor
4729 // branches to us and one of our successors, fold the comparison into the
4730 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004731 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4732 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004733
Chris Lattner25c3af32010-12-13 06:25:44 +00004734 // We have a conditional branch to two blocks that are only reachable
4735 // from BI. We know that the condbr dominates the two blocks, so see if
4736 // there is any identical code in the "then" and "else" blocks. If so, we
4737 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00004738 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4739 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004740 if (HoistThenElseCodeToIf(BI, TTI))
4741 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004742 } else {
4743 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004744 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00004745 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4746 if (Succ0TI->getNumSuccessors() == 1 &&
4747 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004748 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
4749 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004750 }
Craig Topperf40110f2014-04-25 05:29:35 +00004751 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004752 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004753 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00004754 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4755 if (Succ1TI->getNumSuccessors() == 1 &&
4756 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004757 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
4758 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004759 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004760
Chris Lattner25c3af32010-12-13 06:25:44 +00004761 // If this is a branch on a phi node in the current block, thread control
4762 // through this block if any PHI node entries are constants.
4763 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4764 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004765 if (FoldCondBranchOnPHI(BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004766 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004767
Chris Lattner25c3af32010-12-13 06:25:44 +00004768 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004769 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4770 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00004771 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00004772 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004773 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004774
4775 return false;
4776}
4777
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004778/// Check if passing a value to an instruction will cause undefined behavior.
4779static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4780 Constant *C = dyn_cast<Constant>(V);
4781 if (!C)
4782 return false;
4783
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004784 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004785 return false;
4786
4787 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004788 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00004789 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004790
4791 // Now make sure that there are no instructions in between that can alter
4792 // control flow (eg. calls)
4793 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00004794 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004795 return false;
4796
4797 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4798 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4799 if (GEP->getPointerOperand() == I)
4800 return passingValueIsAlwaysUndefined(V, GEP);
4801
4802 // Look through bitcasts.
4803 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4804 return passingValueIsAlwaysUndefined(V, BC);
4805
Benjamin Kramer0655b782011-08-26 02:25:55 +00004806 // Load from null is undefined.
4807 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004808 if (!LI->isVolatile())
4809 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004810
Benjamin Kramer0655b782011-08-26 02:25:55 +00004811 // Store to null is undefined.
4812 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004813 if (!SI->isVolatile())
4814 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004815 }
4816 return false;
4817}
4818
4819/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004820/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004821static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4822 for (BasicBlock::iterator i = BB->begin();
4823 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4824 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4825 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4826 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4827 IRBuilder<> Builder(T);
4828 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4829 BB->removePredecessor(PHI->getIncomingBlock(i));
4830 // Turn uncoditional branches into unreachables and remove the dead
4831 // destination from conditional branches.
4832 if (BI->isUnconditional())
4833 Builder.CreateUnreachable();
4834 else
4835 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4836 BI->getSuccessor(0));
4837 BI->eraseFromParent();
4838 return true;
4839 }
4840 // TODO: SwitchInst.
4841 }
4842
4843 return false;
4844}
4845
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004846bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00004847 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00004848
Chris Lattnerd7beca32010-12-14 06:17:25 +00004849 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00004850 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00004851
Dan Gohman4a63fad2010-08-14 00:29:42 +00004852 // Remove basic blocks that have no predecessors (except the entry block)...
4853 // or that just have themself as a predecessor. These are unreachable.
Ramkumar Ramachandra181233b2015-01-13 04:17:47 +00004854 if ((pred_empty(BB) &&
Chris Lattnerd7beca32010-12-14 06:17:25 +00004855 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00004856 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00004857 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00004858 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00004859 return true;
4860 }
4861
Chris Lattner031340a2003-08-17 19:41:53 +00004862 // Check to see if we can constant propagate this terminator instruction
4863 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00004864 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00004865
Dan Gohman1a951062009-10-30 22:39:04 +00004866 // Check for and eliminate duplicate PHI nodes in this block.
4867 Changed |= EliminateDuplicatePHINodes(BB);
4868
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004869 // Check for and remove branches that will always cause undefined behavior.
4870 Changed |= removeUndefIntroducingPredecessor(BB);
4871
Chris Lattner2e3832d2010-12-13 05:10:48 +00004872 // Merge basic blocks into their predecessor if there is only one distinct
4873 // pred, and if there is only one distinct successor of the predecessor, and
4874 // if there are no PHI nodes.
4875 //
4876 if (MergeBlockIntoPredecessor(BB))
4877 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004878
Devang Patel15ad6762011-05-18 18:01:27 +00004879 IRBuilder<> Builder(BB);
4880
Dan Gohman20af5a02008-03-11 21:53:06 +00004881 // If there is a trivial two-entry PHI node in this basic block, and we can
4882 // eliminate it, do so now.
4883 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4884 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004885 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00004886
Devang Patela7ec47d2011-05-18 20:35:38 +00004887 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00004888 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00004889 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00004890 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004891 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00004892 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004893 }
4894 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00004895 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00004896 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4897 if (SimplifyResume(RI, Builder)) return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00004898 } else if (CleanupReturnInst *RI =
4899 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
4900 if (SimplifyCleanupReturn(RI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004901 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00004902 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004903 } else if (UnreachableInst *UI =
4904 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4905 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004906 } else if (IndirectBrInst *IBI =
4907 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4908 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00004909 }
4910
Chris Lattner031340a2003-08-17 19:41:53 +00004911 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00004912}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004913
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004914/// This function is used to do simplification of a CFG.
4915/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004916/// eliminates unreachable basic blocks, and does other "peephole" optimization
4917/// of the CFG. It returns true if a modification was made.
4918///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004919bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004920 unsigned BonusInstThreshold, AssumptionCache *AC) {
4921 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
4922 BonusInstThreshold, AC).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004923}