blob: 213169bd0dbbc1d6673f29ad756ec321e7fc8375 [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
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/STLExtras.h"
James Molloy4de84dd2015-11-04 15:28:04 +000016#include "llvm/ADT/SetOperations.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#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"
Joseph Tremoulet0d808882016-01-05 02:37:41 +000022#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000024#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000026#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000027#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/MDBuilder.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000039#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000041#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/Type.h"
Evan Chengd983eba2011-01-29 04:46:23 +000043#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000044#include "llvm/Support/Debug.h"
45#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dehao Chenf6c00832016-05-18 19:44:21 +000047#include "llvm/Transforms/Utils/Local.h"
Jingyue Wufc029672014-09-30 22:23:38 +000048#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000049#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000050#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000052using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000053using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000054
Chandler Carruth964daaa2014-04-22 02:55:47 +000055#define DEBUG_TYPE "simplifycfg"
56
James Molloy1b6207e2015-02-13 10:48:30 +000057// Chosen as 2 so as to be cheap, but still to have enough power to fold
58// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
59// To catch this, we need to fold a compare and a select, hence '2' being the
60// minimum reasonable default.
Dehao Chenf6c00832016-05-18 19:44:21 +000061static cl::opt<unsigned> PHINodeFoldingThreshold(
62 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
63 cl::desc(
64 "Control the amount of phi node folding to perform (default = 2)"));
65
66static cl::opt<bool> DupRet(
67 "simplifycfg-dup-ret", cl::Hidden, cl::init(false),
68 cl::desc("Duplicate return instructions into unconditional branches"));
Peter Collingbourne616044a2011-04-29 18:47:38 +000069
Evan Chengd983eba2011-01-29 04:46:23 +000070static cl::opt<bool>
Dehao Chenf6c00832016-05-18 19:44:21 +000071 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
72 cl::desc("Sink common instructions down to the end block"));
Manman Ren93ab6492012-09-20 22:37:36 +000073
Alp Tokercb402912014-01-24 17:20:08 +000074static cl::opt<bool> HoistCondStores(
75 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
76 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000077
James Molloy4de84dd2015-11-04 15:28:04 +000078static cl::opt<bool> MergeCondStores(
79 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
80 cl::desc("Hoist conditional stores even if an unconditional store does not "
81 "precede - hoist multiple conditional stores into a single "
82 "predicated store"));
83
84static cl::opt<bool> MergeCondStoresAggressively(
85 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
86 cl::desc("When merging conditional stores, do so even if the resultant "
87 "basic blocks are unlikely to be if-converted as a result"));
88
David Majnemerfccf5c62016-01-27 02:59:41 +000089static cl::opt<bool> SpeculateOneExpensiveInst(
90 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
91 cl::desc("Allow exactly one expensive instruction to be speculatively "
92 "executed"));
93
Sanjay Patel5264cc72016-01-27 19:22:45 +000094static cl::opt<unsigned> MaxSpeculationDepth(
95 "max-speculation-depth", cl::Hidden, cl::init(10),
96 cl::desc("Limit maximum recursion depth when calculating costs of "
97 "speculatively executed instructions"));
98
Hans Wennborg39583b82012-09-26 09:44:49 +000099STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Dehao Chenf6c00832016-05-18 19:44:21 +0000100STATISTIC(NumLinearMaps,
101 "Number of switch instructions turned into linear mapping");
102STATISTIC(NumLookupTables,
103 "Number of switch instructions turned into lookup tables");
104STATISTIC(
105 NumLookupTablesHoles,
106 "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +0000107STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Dehao Chenf6c00832016-05-18 19:44:21 +0000108STATISTIC(NumSinkCommons,
109 "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +0000110STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +0000111
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000112namespace {
Dehao Chenf6c00832016-05-18 19:44:21 +0000113// The first field contains the value that the switch produces when a certain
114// case group is selected, and the second field is a vector containing the
115// cases composing the case group.
116typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000117 SwitchCaseResultVectorTy;
Dehao Chenf6c00832016-05-18 19:44:21 +0000118// The first field contains the phi node that generates a result of the switch
119// and the second field contains the value generated for a certain case in the
120// switch for that PHI.
121typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000122
Dehao Chenf6c00832016-05-18 19:44:21 +0000123/// ValueEqualityComparisonCase - Represents a case of a switch.
124struct ValueEqualityComparisonCase {
125 ConstantInt *Value;
126 BasicBlock *Dest;
Eric Christopherb65acc62012-07-02 23:22:21 +0000127
Dehao Chenf6c00832016-05-18 19:44:21 +0000128 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
Eric Christopherb65acc62012-07-02 23:22:21 +0000129 : Value(Value), Dest(Dest) {}
130
Dehao Chenf6c00832016-05-18 19:44:21 +0000131 bool operator<(ValueEqualityComparisonCase RHS) const {
132 // Comparing pointers is ok as we only rely on the order for uniquing.
133 return Value < RHS.Value;
134 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000135
Dehao Chenf6c00832016-05-18 19:44:21 +0000136 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
137};
Eric Christopherb65acc62012-07-02 23:22:21 +0000138
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000139class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000140 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000141 const DataLayout &DL;
Jingyue Wufc029672014-09-30 22:23:38 +0000142 unsigned BonusInstThreshold;
Chandler Carruth66b31302015-01-04 12:03:27 +0000143 AssumptionCache *AC;
Hyojin Sung4673f102016-03-29 04:08:57 +0000144 SmallPtrSetImpl<BasicBlock *> *LoopHeaders;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000145 Value *isValueEqualityComparison(TerminatorInst *TI);
Dehao Chenf6c00832016-05-18 19:44:21 +0000146 BasicBlock *GetValueEqualityComparisonCases(
147 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000148 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000149 BasicBlock *Pred,
150 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000151 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
152 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000153
Devang Pateldd14e0f2011-05-18 21:33:11 +0000154 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000155 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chen Li1689c2f2016-01-10 05:48:01 +0000156 bool SimplifySingleResume(ResumeInst *RI);
157 bool SimplifyCommonResume(ResumeInst *RI);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000158 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000159 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000160 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000161 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Dehao Chenf6c00832016-05-18 19:44:21 +0000162 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
163 bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000164
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000165public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000166 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
Hyojin Sung4673f102016-03-29 04:08:57 +0000167 unsigned BonusInstThreshold, AssumptionCache *AC,
168 SmallPtrSetImpl<BasicBlock *> *LoopHeaders)
169 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC),
170 LoopHeaders(LoopHeaders) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000171 bool run(BasicBlock *BB);
172};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000173}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000174
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000175/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000176/// terminator instructions together.
James Molloy8e69b032016-08-31 10:46:39 +0000177static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2,
178 std::vector<BasicBlock*> *FailBlocks = nullptr) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000179 if (SI1 == SI2)
180 return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000181
Chris Lattner76dc2042005-08-03 00:19:45 +0000182 // It is not safe to merge these two switch instructions if they have a common
183 // successor, and if that successor has a PHI node, and if *that* PHI node has
184 // conflicting incoming values from the two switch blocks.
185 BasicBlock *SI1BB = SI1->getParent();
186 BasicBlock *SI2BB = SI2->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +0000187
James Molloy8e69b032016-08-31 10:46:39 +0000188 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
189 bool Fail = false;
Sanjay Patel5781d842016-03-12 16:52:17 +0000190 for (BasicBlock *Succ : successors(SI2BB))
191 if (SI1Succs.count(Succ))
192 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000193 PHINode *PN = cast<PHINode>(BBI);
194 if (PN->getIncomingValueForBlock(SI1BB) !=
James Molloy8e69b032016-08-31 10:46:39 +0000195 PN->getIncomingValueForBlock(SI2BB)) {
196 if (FailBlocks)
197 FailBlocks->push_back(Succ);
198 Fail = true;
199 }
Chris Lattner76dc2042005-08-03 00:19:45 +0000200 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000201
James Molloy8e69b032016-08-31 10:46:39 +0000202 return !Fail;
Chris Lattner76dc2042005-08-03 00:19:45 +0000203}
204
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000205/// Return true if it is safe and profitable to merge these two terminator
206/// instructions together, where SI1 is an unconditional branch. PhiNodes will
207/// store all PHI nodes in common successors.
Dehao Chenf6c00832016-05-18 19:44:21 +0000208static bool
209isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2,
210 Instruction *Cond,
211 SmallVectorImpl<PHINode *> &PhiNodes) {
212 if (SI1 == SI2)
213 return false; // Can't merge with self!
Manman Rend33f4ef2012-06-13 05:43:29 +0000214 assert(SI1->isUnconditional() && SI2->isConditional());
215
216 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000217 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000218 // 1> We have a constant incoming value for the conditional branch;
219 // 2> We have "Cond" as the incoming value for the unconditional branch;
220 // 3> SI2->getCondition() and Cond have same operands.
221 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
Dehao Chenf6c00832016-05-18 19:44:21 +0000222 if (!Ci2)
223 return false;
Manman Rend33f4ef2012-06-13 05:43:29 +0000224 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
225 Cond->getOperand(1) == Ci2->getOperand(1)) &&
226 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
227 Cond->getOperand(1) == Ci2->getOperand(0)))
228 return false;
229
230 BasicBlock *SI1BB = SI1->getParent();
231 BasicBlock *SI2BB = SI2->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000232 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Sanjay Patel5781d842016-03-12 16:52:17 +0000233 for (BasicBlock *Succ : successors(SI2BB))
234 if (SI1Succs.count(Succ))
235 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
Manman Rend33f4ef2012-06-13 05:43:29 +0000236 PHINode *PN = cast<PHINode>(BBI);
237 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000238 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000239 return false;
240 PhiNodes.push_back(PN);
241 }
242 return true;
243}
244
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000245/// Update PHI nodes in Succ to indicate that there will now be entries in it
246/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
247/// will be the same as those coming in from ExistPred, an existing predecessor
248/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000249static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
250 BasicBlock *ExistPred) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000251 if (!isa<PHINode>(Succ->begin()))
252 return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000253
Chris Lattner80b03a12008-07-13 22:23:11 +0000254 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +0000255 for (BasicBlock::iterator I = Succ->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
Chris Lattner80b03a12008-07-13 22:23:11 +0000256 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000257}
258
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000259/// Compute an abstract "cost" of speculating the given instruction,
260/// which is assumed to be safe to speculate. TCC_Free means cheap,
261/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000262/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000263static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000264 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000265 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000266 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000267 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000268}
Sanjay Patelf9b77632015-09-15 15:24:42 +0000269
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000270/// If we have a merge point of an "if condition" as accepted above,
271/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000272/// don't handle the true generality of domination here, just a special case
273/// which works well enough for us.
274///
275/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000276/// see if V (which must be an instruction) and its recursive operands
277/// that do not dominate BB have a combined cost lower than CostRemaining and
278/// are non-trapping. If both are true, the instruction is inserted into the
279/// set and true is returned.
280///
281/// The cost for most non-trapping instructions is defined as 1 except for
282/// Select whose cost is 2.
283///
284/// After this function returns, CostRemaining is decreased by the cost of
285/// V plus its non-dominating operands. If that cost is greater than
286/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000287static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Dehao Chenf6c00832016-05-18 19:44:21 +0000288 SmallPtrSetImpl<Instruction *> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000289 unsigned &CostRemaining,
David Majnemerfccf5c62016-01-27 02:59:41 +0000290 const TargetTransformInfo &TTI,
291 unsigned Depth = 0) {
Sanjay Patel5264cc72016-01-27 19:22:45 +0000292 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
293 // so limit the recursion depth.
294 // TODO: While this recursion limit does prevent pathological behavior, it
295 // would be better to track visited instructions to avoid cycles.
296 if (Depth == MaxSpeculationDepth)
297 return false;
298
Chris Lattner0aa56562004-04-09 22:50:22 +0000299 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000300 if (!I) {
301 // Non-instructions all dominate instructions, but not all constantexprs
302 // can be executed unconditionally.
303 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
304 if (C->canTrap())
305 return false;
306 return true;
307 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000308 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000309
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000310 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000311 // the bottom of this block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000312 if (PBB == BB)
313 return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000314
Chris Lattner0aa56562004-04-09 22:50:22 +0000315 // If this instruction is defined in a block that contains an unconditional
316 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000317 // statement". If not, it definitely dominates the region.
318 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000319 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000320 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000321
Chris Lattner9ac168d2010-12-14 07:41:39 +0000322 // If we aren't allowing aggressive promotion anymore, then don't consider
323 // instructions in the 'if region'.
Dehao Chenf6c00832016-05-18 19:44:21 +0000324 if (!AggressiveInsts)
325 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000326
Peter Collingbournee3511e12011-04-29 18:47:31 +0000327 // If we have seen this instruction before, don't count it again.
Dehao Chenf6c00832016-05-18 19:44:21 +0000328 if (AggressiveInsts->count(I))
329 return true;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000330
Chris Lattner9ac168d2010-12-14 07:41:39 +0000331 // Okay, it looks like the instruction IS in the "condition". Check to
332 // see if it's a cheap instruction to unconditionally compute, and if it
333 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000334 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000335 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000336
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000337 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000338
David Majnemerfccf5c62016-01-27 02:59:41 +0000339 // Allow exactly one instruction to be speculated regardless of its cost
340 // (as long as it is safe to do so).
341 // This is intended to flatten the CFG even if the instruction is a division
342 // or other expensive operation. The speculation of an expensive instruction
343 // is expected to be undone in CodeGenPrepare if the speculation has not
344 // enabled further IR optimizations.
345 if (Cost > CostRemaining &&
346 (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0))
Peter Collingbournee3511e12011-04-29 18:47:31 +0000347 return false;
348
David Majnemerfccf5c62016-01-27 02:59:41 +0000349 // Avoid unsigned wrap.
350 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000351
352 // Okay, we can only really hoist these out if their operands do
353 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000354 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
David Majnemerfccf5c62016-01-27 02:59:41 +0000355 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
356 Depth + 1))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000357 return false;
358 // Okay, it's safe to do this! Remember this instruction.
359 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000360 return true;
361}
Chris Lattner466a0492002-05-21 20:50:24 +0000362
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000363/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000364/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000365static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000366 // Normal constant int.
367 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000368 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000369 return CI;
370
371 // This is some kind of pointer constant. Turn it into a pointer-sized
372 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000373 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000374
375 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
376 if (isa<ConstantPointerNull>(V))
377 return ConstantInt::get(PtrTy, 0);
378
379 // IntToPtr const int.
380 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
381 if (CE->getOpcode() == Instruction::IntToPtr)
382 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
383 // The constant is very likely to have the right type already.
384 if (CI->getType() == PtrTy)
385 return CI;
386 else
Dehao Chenf6c00832016-05-18 19:44:21 +0000387 return cast<ConstantInt>(
388 ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000389 }
Craig Topperf40110f2014-04-25 05:29:35 +0000390 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000391}
392
Mehdi Aminiffd01002014-11-20 22:40:25 +0000393namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000394
Mehdi Aminiffd01002014-11-20 22:40:25 +0000395/// Given a chain of or (||) or and (&&) comparison of a value against a
396/// constant, this will try to recover the information required for a switch
397/// structure.
398/// It will depth-first traverse the chain of comparison, seeking for patterns
399/// like %a == 12 or %a < 4 and combine them to produce a set of integer
400/// representing the different cases for the switch.
401/// Note that if the chain is composed of '||' it will build the set of elements
402/// that matches the comparisons (i.e. any of this value validate the chain)
403/// while for a chain of '&&' it will build the set elements that make the test
404/// fail.
405struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000406 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000407 Value *CompValue; /// Value found for the switch comparison
408 Value *Extra; /// Extra clause to be checked before the switch
409 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
410 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000411
Mehdi Aminiffd01002014-11-20 22:40:25 +0000412 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000413 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
414 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
415 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000416 }
417
Mehdi Aminiffd01002014-11-20 22:40:25 +0000418 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000419 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000420 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000421 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000422
Mehdi Aminiffd01002014-11-20 22:40:25 +0000423private:
Mehdi Aminiffd01002014-11-20 22:40:25 +0000424 /// Try to set the current value used for the comparison, it succeeds only if
425 /// it wasn't set before or if the new value is the same as the old one
426 bool setValueOnce(Value *NewVal) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000427 if (CompValue && CompValue != NewVal)
428 return false;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000429 CompValue = NewVal;
430 return (CompValue != nullptr);
431 }
432
433 /// Try to match Instruction "I" as a comparison against a constant and
434 /// populates the array Vals with the set of values that match (or do not
435 /// match depending on isEQ).
436 /// Return false on failure. On success, the Value the comparison matched
437 /// against is placed in CompValue.
438 /// If CompValue is already set, the function is expected to fail if a match
439 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000440 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000441 // If this is an icmp against a constant, handle this as one of the cases.
442 ICmpInst *ICI;
443 ConstantInt *C;
444 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
Dehao Chenf6c00832016-05-18 19:44:21 +0000445 (C = GetConstantInt(I->getOperand(1), DL)))) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000446 return false;
447 }
448
449 Value *RHSVal;
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000450 const APInt *RHSC;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000451
452 // Pattern match a special case
David Majnemerc761afd2016-01-27 02:43:28 +0000453 // (x & ~2^z) == y --> x == y || x == y|2^z
Mehdi Aminiffd01002014-11-20 22:40:25 +0000454 // This undoes a transformation done by instcombine to fuse 2 compares.
Dehao Chenf6c00832016-05-18 19:44:21 +0000455 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000456
457 // It's a little bit hard to see why the following transformations are
458 // correct. Here is a CVC3 program to verify them for 64-bit values:
459
460 /*
461 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
462 x : BITVECTOR(64);
463 y : BITVECTOR(64);
464 z : BITVECTOR(64);
465 mask : BITVECTOR(64) = BVSHL(ONE, z);
466 QUERY( (y & ~mask = y) =>
467 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
468 );
Chuang-Yu Cheng68f7f1c2016-06-24 01:59:00 +0000469 QUERY( (y | mask = y) =>
470 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
471 );
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000472 */
473
474 // Please note that each pattern must be a dual implication (<--> or
475 // iff). One directional implication can create spurious matches. If the
476 // implication is only one-way, an unsatisfiable condition on the left
477 // side can imply a satisfiable condition on the right side. Dual
478 // implication ensures that satisfiable conditions are transformed to
479 // other satisfiable conditions and unsatisfiable conditions are
480 // transformed to other unsatisfiable conditions.
481
482 // Here is a concrete example of a unsatisfiable condition on the left
483 // implying a satisfiable condition on the right:
484 //
485 // mask = (1 << z)
486 // (x & ~mask) == y --> (x == y || x == (y | mask))
487 //
488 // Substituting y = 3, z = 0 yields:
489 // (x & -2) == 3 --> (x == 3 || x == 2)
490
491 // Pattern match a special case:
492 /*
493 QUERY( (y & ~mask = y) =>
494 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
495 );
496 */
Mehdi Aminiffd01002014-11-20 22:40:25 +0000497 if (match(ICI->getOperand(0),
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000498 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
499 APInt Mask = ~*RHSC;
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000500 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000501 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000502 if (!setValueOnce(RHSVal))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000503 return false;
504
505 Vals.push_back(C);
Dehao Chenf6c00832016-05-18 19:44:21 +0000506 Vals.push_back(
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000507 ConstantInt::get(C->getContext(),
508 C->getValue() | Mask));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000509 UsedICmps++;
510 return true;
511 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000512 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000513
Chuang-Yu Cheng68f7f1c2016-06-24 01:59:00 +0000514 // Pattern match a special case:
515 /*
516 QUERY( (y | mask = y) =>
517 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
518 );
519 */
520 if (match(ICI->getOperand(0),
521 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
522 APInt Mask = *RHSC;
523 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
524 // If we already have a value for the switch, it has to match!
525 if (!setValueOnce(RHSVal))
526 return false;
527
528 Vals.push_back(C);
529 Vals.push_back(ConstantInt::get(C->getContext(),
530 C->getValue() & ~Mask));
531 UsedICmps++;
532 return true;
533 }
534 }
535
Mehdi Aminiffd01002014-11-20 22:40:25 +0000536 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000537 if (!setValueOnce(ICI->getOperand(0)))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000538 return false;
539
540 UsedICmps++;
541 Vals.push_back(C);
542 return ICI->getOperand(0);
543 }
544
545 // 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 +0000546 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
547 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000548
549 // Shift the range if the compare is fed by an add. This is the range
550 // compare idiom as emitted by instcombine.
551 Value *CandidateVal = I->getOperand(0);
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000552 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
553 Span = Span.subtract(*RHSC);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000554 CandidateVal = RHSVal;
555 }
556
557 // If this is an and/!= check, then we are looking to build the set of
558 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
559 // x != 0 && x != 1.
560 if (!isEQ)
561 Span = Span.inverse();
562
563 // If there are a ton of values, we don't want to make a ginormous switch.
564 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
565 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000566 }
567
568 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000569 if (!setValueOnce(CandidateVal))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000570 return false;
571
572 // Add all values from the range to the set
573 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
574 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000575
576 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000577 return true;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000578 }
579
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000580 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000581 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
582 /// the value being compared, and stick the list constants into the Vals
583 /// vector.
584 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000585 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000586 Instruction *I = dyn_cast<Instruction>(V);
587 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000588
Mehdi Aminiffd01002014-11-20 22:40:25 +0000589 // Keep a stack (SmallVector for efficiency) for depth-first traversal
590 SmallVector<Value *, 8> DFT;
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000591 SmallPtrSet<Value *, 8> Visited;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000592
Mehdi Aminiffd01002014-11-20 22:40:25 +0000593 // Initialize
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000594 Visited.insert(V);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000595 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000596
Dehao Chenf6c00832016-05-18 19:44:21 +0000597 while (!DFT.empty()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000598 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000599
Mehdi Aminiffd01002014-11-20 22:40:25 +0000600 if (Instruction *I = dyn_cast<Instruction>(V)) {
601 // If it is a || (or && depending on isEQ), process the operands.
602 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000603 if (Visited.insert(I->getOperand(1)).second)
604 DFT.push_back(I->getOperand(1));
605 if (Visited.insert(I->getOperand(0)).second)
606 DFT.push_back(I->getOperand(0));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000607 continue;
608 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000609
Mehdi Aminiffd01002014-11-20 22:40:25 +0000610 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000611 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000612 // Match succeed, continue the loop
613 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000614 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000615
Mehdi Aminiffd01002014-11-20 22:40:25 +0000616 // One element of the sequence of || (or &&) could not be match as a
617 // comparison against the same value as the others.
618 // We allow only one "Extra" case to be checked before the switch
619 if (!Extra) {
620 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000621 continue;
622 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000623 // Failed to parse a proper sequence, abort now
624 CompValue = nullptr;
625 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000626 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000627 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000628};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000629}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000630
Eli Friedmancb61afb2008-12-16 20:54:32 +0000631static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000632 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000633 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
634 Cond = dyn_cast<Instruction>(SI->getCondition());
635 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
636 if (BI->isConditional())
637 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000638 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
639 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000640 }
641
642 TI->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000643 if (Cond)
644 RecursivelyDeleteTriviallyDeadInstructions(Cond);
Eli Friedmancb61afb2008-12-16 20:54:32 +0000645}
646
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000647/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000648/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000649Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000650 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000651 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
652 // Do not permit merging of large switch instructions into their
653 // predecessors unless there is only one predecessor.
Dehao Chenf6c00832016-05-18 19:44:21 +0000654 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
655 pred_end(SI->getParent())) <=
656 128)
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000657 CV = SI->getCondition();
658 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000659 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000660 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000661 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000662 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000663 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000664
665 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000666 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000667 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
668 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000669 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000670 CV = Ptr;
671 }
672 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000673 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000674}
675
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000676/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000677/// decode all of the 'cases' that it represents and return the 'default' block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000678BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
679 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000680 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000681 Cases.reserve(SI->getNumCases());
Dehao Chenf6c00832016-05-18 19:44:21 +0000682 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e;
683 ++i)
684 Cases.push_back(
685 ValueEqualityComparisonCase(i.getCaseValue(), i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000686 return SI->getDefaultDest();
687 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000688
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000689 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000690 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000691 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
Dehao Chenf6c00832016-05-18 19:44:21 +0000692 Cases.push_back(ValueEqualityComparisonCase(
693 GetConstantInt(ICI->getOperand(1), DL), Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000694 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000695}
696
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000697/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000698/// in the list that match the specified block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000699static void
700EliminateBlockCases(BasicBlock *BB,
701 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000702 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000703}
704
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000705/// Return true if there are any keys in C1 that exist in C2 as well.
Dehao Chenf6c00832016-05-18 19:44:21 +0000706static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
707 std::vector<ValueEqualityComparisonCase> &C2) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000708 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
709
710 // Make V1 be smaller than V2.
711 if (V1->size() > V2->size())
712 std::swap(V1, V2);
713
Dehao Chenf6c00832016-05-18 19:44:21 +0000714 if (V1->size() == 0)
715 return false;
Eric Christopherb65acc62012-07-02 23:22:21 +0000716 if (V1->size() == 1) {
717 // Just scan V2.
718 ConstantInt *TheVal = (*V1)[0].Value;
719 for (unsigned i = 0, e = V2->size(); i != e; ++i)
720 if (TheVal == (*V2)[i].Value)
721 return true;
722 }
723
724 // Otherwise, just sort both lists and compare element by element.
725 array_pod_sort(V1->begin(), V1->end());
726 array_pod_sort(V2->begin(), V2->end());
727 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
728 while (i1 != e1 && i2 != e2) {
729 if ((*V1)[i1].Value == (*V2)[i2].Value)
730 return true;
731 if ((*V1)[i1].Value < (*V2)[i2].Value)
732 ++i1;
733 else
734 ++i2;
735 }
736 return false;
737}
738
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000739/// If TI is known to be a terminator instruction and its block is known to
740/// only have a single predecessor block, check to see if that predecessor is
741/// also a value comparison with the same value, and if that comparison
742/// determines the outcome of this comparison. If so, simplify TI. This does a
743/// very limited form of jump threading.
Dehao Chenf6c00832016-05-18 19:44:21 +0000744bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
745 TerminatorInst *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000746 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
Dehao Chenf6c00832016-05-18 19:44:21 +0000747 if (!PredVal)
748 return false; // Not a value comparison in predecessor.
Chris Lattner1cca9592005-02-24 06:17:52 +0000749
750 Value *ThisVal = isValueEqualityComparison(TI);
751 assert(ThisVal && "This isn't a value comparison!!");
Dehao Chenf6c00832016-05-18 19:44:21 +0000752 if (ThisVal != PredVal)
753 return false; // Different predicates.
Chris Lattner1cca9592005-02-24 06:17:52 +0000754
Andrew Trick3051aa12012-08-29 21:46:38 +0000755 // TODO: Preserve branch weight metadata, similarly to how
756 // FoldValueComparisonIntoPredecessors preserves it.
757
Chris Lattner1cca9592005-02-24 06:17:52 +0000758 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000759 std::vector<ValueEqualityComparisonCase> PredCases;
Dehao Chenf6c00832016-05-18 19:44:21 +0000760 BasicBlock *PredDef =
761 GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
762 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000763
Chris Lattner1cca9592005-02-24 06:17:52 +0000764 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000765 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000766 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Dehao Chenf6c00832016-05-18 19:44:21 +0000767 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000768
769 // If TI's block is the default block from Pred's comparison, potentially
770 // simplify TI based on this knowledge.
771 if (PredDef == TI->getParent()) {
772 // If we are here, we know that the value is none of those cases listed in
773 // PredCases. If there are any cases in ThisCases that are in PredCases, we
774 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000775 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000776 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000777
Chris Lattner4088e2b2010-12-13 01:47:07 +0000778 if (isa<BranchInst>(TI)) {
779 // Okay, one of the successors of this condbr is dead. Convert it to a
780 // uncond br.
781 assert(ThisCases.size() == 1 && "Branch can only have one case!");
782 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000783 Instruction *NI = Builder.CreateBr(ThisDef);
Dehao Chenf6c00832016-05-18 19:44:21 +0000784 (void)NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000785
Chris Lattner4088e2b2010-12-13 01:47:07 +0000786 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000787 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000788
Chris Lattner4088e2b2010-12-13 01:47:07 +0000789 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Dehao Chenf6c00832016-05-18 19:44:21 +0000790 << "Through successor TI: " << *TI << "Leaving: " << *NI
791 << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000792
Chris Lattner4088e2b2010-12-13 01:47:07 +0000793 EraseTerminatorInstAndDCECond(TI);
794 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000795 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000796
Chris Lattner4088e2b2010-12-13 01:47:07 +0000797 SwitchInst *SI = cast<SwitchInst>(TI);
798 // Okay, TI has cases that are statically dead, prune them away.
Dehao Chenf6c00832016-05-18 19:44:21 +0000799 SmallPtrSet<Constant *, 16> DeadCases;
Eric Christopherb65acc62012-07-02 23:22:21 +0000800 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
801 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000802
David Greene725c7c32010-01-05 01:26:52 +0000803 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000804 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000805
Manman Ren8691e522012-09-14 21:53:06 +0000806 // Collect branch weights into a vector.
807 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000808 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000809 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
810 if (HasWeight)
811 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
812 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000813 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000814 Weights.push_back(CI->getValue().getZExtValue());
815 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000816 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
817 --i;
818 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000819 if (HasWeight) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000820 std::swap(Weights[i.getCaseIndex() + 1], Weights.back());
Manman Ren8691e522012-09-14 21:53:06 +0000821 Weights.pop_back();
822 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000823 i.getCaseSuccessor()->removePredecessor(TI->getParent());
824 SI->removeCase(i);
825 }
826 }
Manman Ren97c18762012-10-11 22:28:34 +0000827 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000828 SI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +0000829 MDBuilder(SI->getParent()->getContext())
830 .createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000831
832 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000833 return true;
834 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000835
Chris Lattner4088e2b2010-12-13 01:47:07 +0000836 // Otherwise, TI's block must correspond to some matched value. Find out
837 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000838 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000839 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000840 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
841 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000842 if (TIV)
Dehao Chenf6c00832016-05-18 19:44:21 +0000843 return false; // Cannot handle multiple values coming to this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000844 TIV = PredCases[i].Value;
845 }
846 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000847
848 // Okay, we found the one constant that our value can be if we get into TI's
849 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000850 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000851 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
852 if (ThisCases[i].Value == TIV) {
853 TheRealDest = ThisCases[i].Dest;
854 break;
855 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000856
857 // If not handled by any explicit cases, it is handled by the default case.
Dehao Chenf6c00832016-05-18 19:44:21 +0000858 if (!TheRealDest)
859 TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000860
861 // Remove PHI node entries for dead edges.
862 BasicBlock *CheckEdge = TheRealDest;
Sanjay Patel5781d842016-03-12 16:52:17 +0000863 for (BasicBlock *Succ : successors(TIBB))
864 if (Succ != CheckEdge)
865 Succ->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000866 else
Craig Topperf40110f2014-04-25 05:29:35 +0000867 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000868
869 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000870 Instruction *NI = Builder.CreateBr(TheRealDest);
Dehao Chenf6c00832016-05-18 19:44:21 +0000871 (void)NI;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000872
873 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Dehao Chenf6c00832016-05-18 19:44:21 +0000874 << "Through successor TI: " << *TI << "Leaving: " << *NI
875 << "\n");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000876
877 EraseTerminatorInstAndDCECond(TI);
878 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000879}
880
Dale Johannesen7f99d222009-03-12 21:01:11 +0000881namespace {
Dehao Chenf6c00832016-05-18 19:44:21 +0000882/// This class implements a stable ordering of constant
883/// integers that does not depend on their address. This is important for
884/// applications that sort ConstantInt's to ensure uniqueness.
885struct ConstantIntOrdering {
886 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
887 return LHS->getValue().ult(RHS->getValue());
888 }
889};
Dale Johannesen7f99d222009-03-12 21:01:11 +0000890}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000891
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000892static int ConstantIntSortPredicate(ConstantInt *const *P1,
893 ConstantInt *const *P2) {
894 const ConstantInt *LHS = *P1;
895 const ConstantInt *RHS = *P2;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000896 if (LHS == RHS)
Chris Lattnere893e262010-12-15 04:52:41 +0000897 return 0;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000898 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000899}
900
Dehao Chenf6c00832016-05-18 19:44:21 +0000901static inline bool HasBranchWeights(const Instruction *I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000902 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000903 if (ProfMD && ProfMD->getOperand(0))
Dehao Chenf6c00832016-05-18 19:44:21 +0000904 if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
Andrew Trick3051aa12012-08-29 21:46:38 +0000905 return MDS->getString().equals("branch_weights");
906
907 return false;
908}
909
Manman Ren571d9e42012-09-11 17:43:35 +0000910/// Get Weights of a given TerminatorInst, the default weight is at the front
911/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
912/// metadata.
913static void GetBranchWeights(TerminatorInst *TI,
914 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000915 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000916 assert(MD);
917 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000918 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000919 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000920 }
921
Manman Ren571d9e42012-09-11 17:43:35 +0000922 // If TI is a conditional eq, the default case is the false case,
923 // and the corresponding branch-weight data is at index 2. We swap the
924 // default weight to be the first entry.
Dehao Chenf6c00832016-05-18 19:44:21 +0000925 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Manman Ren571d9e42012-09-11 17:43:35 +0000926 assert(Weights.size() == 2);
927 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
928 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
929 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000930 }
931}
932
Sanjay Patel84a0bf62016-05-06 17:51:37 +0000933/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000934static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000935 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
936 if (Max > UINT_MAX) {
937 unsigned Offset = 32 - countLeadingZeros(Max);
938 for (uint64_t &I : Weights)
939 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000940 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000941}
942
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000943/// The specified terminator is a value equality comparison instruction
944/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000945/// See if any of the predecessors of the terminator block are value comparisons
946/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000947bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
948 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000949 BasicBlock *BB = TI->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000950 Value *CV = isValueEqualityComparison(TI); // CondVal
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000951 assert(CV && "Not a comparison?");
952 bool Changed = false;
953
Dehao Chenf6c00832016-05-18 19:44:21 +0000954 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000955 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000956 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000957
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000958 // See if the predecessor is a comparison with the same value.
959 TerminatorInst *PTI = Pred->getTerminator();
Dehao Chenf6c00832016-05-18 19:44:21 +0000960 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000961
James Molloy8e69b032016-08-31 10:46:39 +0000962 if (PCV == CV && TI != PTI) {
963 std::vector<BasicBlock*> FailBlocks;
964 if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
965 for (auto *Succ : FailBlocks) {
966 std::vector<BasicBlock*> Blocks = { TI->getParent() };
967 if (!SplitBlockPredecessors(Succ, Blocks, ".fold.split"))
968 return false;
969 }
970 }
971
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000972 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000973 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000974 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
975
Eric Christopherb65acc62012-07-02 23:22:21 +0000976 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000977 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
978
979 // Based on whether the default edge from PTI goes to BB or not, fill in
980 // PredCases and PredDefault with the new switch cases we would like to
981 // build.
Dehao Chenf6c00832016-05-18 19:44:21 +0000982 SmallVector<BasicBlock *, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000983
Andrew Trick3051aa12012-08-29 21:46:38 +0000984 // Update the branch weight metadata along the way
985 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000986 bool PredHasWeights = HasBranchWeights(PTI);
987 bool SuccHasWeights = HasBranchWeights(TI);
988
Manman Ren5e5049d2012-09-14 19:05:19 +0000989 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000990 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000991 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000992 if (Weights.size() != 1 + PredCases.size())
993 PredHasWeights = SuccHasWeights = false;
994 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000995 // If there are no predecessor weights but there are successor weights,
996 // populate Weights with 1, which will later be scaled to the sum of
997 // successor's weights
998 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000999
Manman Ren571d9e42012-09-11 17:43:35 +00001000 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +00001001 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +00001002 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +00001003 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +00001004 if (SuccWeights.size() != 1 + BBCases.size())
1005 PredHasWeights = SuccHasWeights = false;
1006 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +00001007 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +00001008
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001009 if (PredDefault == BB) {
1010 // If this is the default destination from PTI, only the edges in TI
1011 // that don't occur in PTI, or that branch to BB will be activated.
Dehao Chenf6c00832016-05-18 19:44:21 +00001012 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +00001013 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1014 if (PredCases[i].Dest != BB)
1015 PTIHandled.insert(PredCases[i].Value);
1016 else {
1017 // The default destination is BB, we don't need explicit targets.
1018 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +00001019
Manman Ren571d9e42012-09-11 17:43:35 +00001020 if (PredHasWeights || SuccHasWeights) {
1021 // Increase weight for the default case.
Dehao Chenf6c00832016-05-18 19:44:21 +00001022 Weights[0] += Weights[i + 1];
1023 std::swap(Weights[i + 1], Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +00001024 Weights.pop_back();
1025 }
1026
Eric Christopherb65acc62012-07-02 23:22:21 +00001027 PredCases.pop_back();
Dehao Chenf6c00832016-05-18 19:44:21 +00001028 --i;
1029 --e;
Eric Christopherb65acc62012-07-02 23:22:21 +00001030 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001031
Eric Christopherb65acc62012-07-02 23:22:21 +00001032 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001033 if (PredDefault != BBDefault) {
1034 PredDefault->removePredecessor(Pred);
1035 PredDefault = BBDefault;
1036 NewSuccessors.push_back(BBDefault);
1037 }
Andrew Trick3051aa12012-08-29 21:46:38 +00001038
Manman Ren571d9e42012-09-11 17:43:35 +00001039 unsigned CasesFromPred = Weights.size();
1040 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +00001041 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1042 if (!PTIHandled.count(BBCases[i].Value) &&
1043 BBCases[i].Dest != BBDefault) {
1044 PredCases.push_back(BBCases[i]);
1045 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +00001046 if (SuccHasWeights || PredHasWeights) {
1047 // The default weight is at index 0, so weight for the ith case
1048 // should be at index i+1. Scale the cases from successor by
1049 // PredDefaultWeight (Weights[0]).
Dehao Chenf6c00832016-05-18 19:44:21 +00001050 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1051 ValidTotalSuccWeight += SuccWeights[i + 1];
Andrew Trick3051aa12012-08-29 21:46:38 +00001052 }
Eric Christopherb65acc62012-07-02 23:22:21 +00001053 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001054
Manman Ren571d9e42012-09-11 17:43:35 +00001055 if (SuccHasWeights || PredHasWeights) {
1056 ValidTotalSuccWeight += SuccWeights[0];
1057 // Scale the cases from predecessor by ValidTotalSuccWeight.
1058 for (unsigned i = 1; i < CasesFromPred; ++i)
1059 Weights[i] *= ValidTotalSuccWeight;
1060 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1061 Weights[0] *= SuccWeights[0];
1062 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001063 } else {
1064 // If this is not the default destination from PSI, only the edges
1065 // in SI that occur in PSI with a destination of BB will be
1066 // activated.
Dehao Chenf6c00832016-05-18 19:44:21 +00001067 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1068 std::map<ConstantInt *, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +00001069 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1070 if (PredCases[i].Dest == BB) {
1071 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +00001072
1073 if (PredHasWeights || SuccHasWeights) {
Dehao Chenf6c00832016-05-18 19:44:21 +00001074 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1075 std::swap(Weights[i + 1], Weights.back());
Manman Rend81b8e82012-09-14 17:29:56 +00001076 Weights.pop_back();
1077 }
1078
Eric Christopherb65acc62012-07-02 23:22:21 +00001079 std::swap(PredCases[i], PredCases.back());
1080 PredCases.pop_back();
Dehao Chenf6c00832016-05-18 19:44:21 +00001081 --i;
1082 --e;
Eric Christopherb65acc62012-07-02 23:22:21 +00001083 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001084
1085 // Okay, now we know which constants were sent to BB from the
1086 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +00001087 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1088 if (PTIHandled.count(BBCases[i].Value)) {
1089 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +00001090 if (PredHasWeights || SuccHasWeights)
1091 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +00001092 PredCases.push_back(BBCases[i]);
1093 NewSuccessors.push_back(BBCases[i].Dest);
Dehao Chenf6c00832016-05-18 19:44:21 +00001094 PTIHandled.erase(
1095 BBCases[i].Value); // This constant is taken care of
Eric Christopherb65acc62012-07-02 23:22:21 +00001096 }
1097
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001098 // If there are any constants vectored to BB that TI doesn't handle,
1099 // they must go to the default destination of TI.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001100 for (ConstantInt *I : PTIHandled) {
Andrew Trick90f50292012-11-15 18:40:29 +00001101 if (PredHasWeights || SuccHasWeights)
Benjamin Kramer135f7352016-06-26 12:28:59 +00001102 Weights.push_back(WeightsForHandled[I]);
1103 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001104 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +00001105 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001106 }
1107
1108 // Okay, at this point, we know which new successor Pred will get. Make
1109 // sure we update the number of entries in the PHI nodes for these
1110 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +00001111 for (BasicBlock *NewSuccessor : NewSuccessors)
1112 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001113
Devang Patel58380552011-05-18 20:53:17 +00001114 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001115 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +00001116 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001117 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +00001118 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001119 }
1120
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001121 // Now that the successors are updated, create the new Switch instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00001122 SwitchInst *NewSI =
1123 Builder.CreateSwitch(CV, PredDefault, PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001124 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +00001125 for (ValueEqualityComparisonCase &V : PredCases)
1126 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001127
Andrew Trick3051aa12012-08-29 21:46:38 +00001128 if (PredHasWeights || SuccHasWeights) {
1129 // Halve the weights if any of them cannot fit in an uint32_t
1130 FitWeights(Weights);
1131
1132 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1133
Dehao Chenf6c00832016-05-18 19:44:21 +00001134 NewSI->setMetadata(
1135 LLVMContext::MD_prof,
1136 MDBuilder(BB->getContext()).createBranchWeights(MDWeights));
Andrew Trick3051aa12012-08-29 21:46:38 +00001137 }
1138
Eli Friedmancb61afb2008-12-16 20:54:32 +00001139 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001140
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001141 // Okay, last check. If BB is still a successor of PSI, then we must
1142 // have an infinite loop case. If so, add an infinitely looping block
1143 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001144 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001145 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1146 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001147 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001148 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001149 // or it won't matter if it's hot. :)
Dehao Chenf6c00832016-05-18 19:44:21 +00001150 InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop",
1151 BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001152 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001153 }
1154 NewSI->setSuccessor(i, InfLoopBlock);
1155 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001156
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001157 Changed = true;
1158 }
1159 }
1160 return Changed;
1161}
1162
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001163// If we would need to insert a select that uses the value of this invoke
1164// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1165// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001166static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1167 Instruction *I1, Instruction *I2) {
Sanjay Patel5781d842016-03-12 16:52:17 +00001168 for (BasicBlock *Succ : successors(BB1)) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001169 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001170 for (BasicBlock::iterator BBI = Succ->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001171 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1172 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1173 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001174 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001175 return false;
1176 }
1177 }
1178 }
1179 return true;
1180}
1181
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001182static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1183
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001184/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1185/// in the two blocks up into the branch block. The caller of this function
1186/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001187static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001188 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001189 // This does very trivial matching, with limited scanning, to find identical
1190 // instructions in the two blocks. In particular, we don't want to get into
1191 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1192 // such, we currently just scan for obviously identical instructions in an
1193 // identical order.
Dehao Chenf6c00832016-05-18 19:44:21 +00001194 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1195 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
Chris Lattner389cfac2004-11-30 00:29:14 +00001196
Devang Patelf10e2872009-02-04 00:03:08 +00001197 BasicBlock::iterator BB1_Itr = BB1->begin();
1198 BasicBlock::iterator BB2_Itr = BB2->begin();
1199
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001200 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001201 // Skip debug info if it is not identical.
1202 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1203 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1204 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1205 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001206 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001207 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001208 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001209 }
Devang Patele48ddf82011-04-07 00:30:15 +00001210 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001211 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001212 return false;
1213
Chris Lattner389cfac2004-11-30 00:29:14 +00001214 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001215
David Majnemerc82f27a2013-06-03 20:43:12 +00001216 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001217 do {
1218 // If we are hoisting the terminator instruction, don't move one (making a
1219 // broken BB), instead clone it, and remove BI.
1220 if (isa<TerminatorInst>(I1))
1221 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001222
Chad Rosier54390052015-02-23 19:15:16 +00001223 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1224 return Changed;
1225
Chris Lattner389cfac2004-11-30 00:29:14 +00001226 // For a normal instruction, we just move one to right before the branch,
1227 // then replace all uses of the other with the first. Finally, we remove
1228 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001229 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001230 if (!I2->use_empty())
1231 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001232 I1->intersectOptionalDataWith(I2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001233 unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
1234 LLVMContext::MD_range,
1235 LLVMContext::MD_fpmath,
1236 LLVMContext::MD_invariant_load,
1237 LLVMContext::MD_nonnull,
1238 LLVMContext::MD_invariant_group,
1239 LLVMContext::MD_align,
1240 LLVMContext::MD_dereferenceable,
1241 LLVMContext::MD_dereferenceable_or_null,
1242 LLVMContext::MD_mem_parallel_loop_access};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001243 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001244 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001245 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001246
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001247 I1 = &*BB1_Itr++;
1248 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001249 // Skip debug info if it is not identical.
1250 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1251 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1252 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1253 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001254 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001255 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001256 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001257 }
Devang Patele48ddf82011-04-07 00:30:15 +00001258 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001259
1260 return true;
1261
1262HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001263 // It may not be possible to hoist an invoke.
1264 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001265 return Changed;
1266
Sanjay Patel5781d842016-03-12 16:52:17 +00001267 for (BasicBlock *Succ : successors(BB1)) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001268 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001269 for (BasicBlock::iterator BBI = Succ->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001270 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1271 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1272 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1273 if (BB1V == BB2V)
1274 continue;
1275
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001276 // Check for passingValueIsAlwaysUndefined here because we would rather
1277 // eliminate undefined control flow then converting it to a select.
1278 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1279 passingValueIsAlwaysUndefined(BB2V, PN))
Dehao Chenf6c00832016-05-18 19:44:21 +00001280 return Changed;
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001281
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001282 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001283 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001284 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001285 return Changed;
1286 }
1287 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001288
Chris Lattner389cfac2004-11-30 00:29:14 +00001289 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001290 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001291 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001292 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001293 I1->replaceAllUsesWith(NT);
1294 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001295 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001296 }
1297
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001298 IRBuilder<NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001299 // Hoisting one of the terminators from our successor is a great thing.
1300 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1301 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1302 // nodes, so we insert select instruction to compute the final result.
Dehao Chenf6c00832016-05-18 19:44:21 +00001303 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
Sanjay Patel5781d842016-03-12 16:52:17 +00001304 for (BasicBlock *Succ : successors(BB1)) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001305 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001306 for (BasicBlock::iterator BBI = Succ->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001307 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001308 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1309 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001310 if (BB1V == BB2V)
1311 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001312
Chris Lattner4088e2b2010-12-13 01:47:07 +00001313 // These values do not agree. Insert a select instruction before NT
1314 // that determines the right value.
1315 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001316 if (!SI)
Dehao Chenf6c00832016-05-18 19:44:21 +00001317 SI = cast<SelectInst>(
1318 Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1319 BB1V->getName() + "." + BB2V->getName(), BI));
Devang Patel1407fb42011-05-19 20:52:46 +00001320
Chris Lattner4088e2b2010-12-13 01:47:07 +00001321 // Make the PHI node use the select for all incoming values for BB1/BB2
1322 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1323 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1324 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001325 }
1326 }
1327
1328 // Update any PHI nodes in our new successors.
Sanjay Patel5781d842016-03-12 16:52:17 +00001329 for (BasicBlock *Succ : successors(BB1))
1330 AddPredecessorToBlock(Succ, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001331
Eli Friedmancb61afb2008-12-16 20:54:32 +00001332 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001333 return true;
1334}
1335
James Molloy5bf21142016-08-22 19:07:15 +00001336// Is it legal to place a variable in operand \c OpIdx of \c I?
1337// FIXME: This should be promoted to Instruction.
1338static bool canReplaceOperandWithVariable(const Instruction *I,
1339 unsigned OpIdx) {
1340 // Early exit.
1341 if (!isa<Constant>(I->getOperand(OpIdx)))
1342 return true;
1343
1344 switch (I->getOpcode()) {
1345 default:
1346 return true;
1347 case Instruction::Call:
1348 case Instruction::Invoke:
1349 // FIXME: many arithmetic intrinsics have no issue taking a
1350 // variable, however it's hard to distingish these from
1351 // specials such as @llvm.frameaddress that require a constant.
1352 return !isa<IntrinsicInst>(I);
1353 case Instruction::ShuffleVector:
1354 // Shufflevector masks are constant.
1355 return OpIdx != 2;
1356 case Instruction::ExtractValue:
1357 case Instruction::InsertValue:
1358 // All operands apart from the first are constant.
1359 return OpIdx == 0;
1360 case Instruction::Alloca:
1361 return false;
1362 case Instruction::GetElementPtr:
1363 if (OpIdx == 0)
1364 return true;
1365 gep_type_iterator It = std::next(gep_type_begin(I), OpIdx - 1);
1366 return !It->isStructTy();
1367 }
1368}
1369
James Molloy55bd04c2016-08-31 10:46:23 +00001370// All instructions in Insts belong to different blocks that all unconditionally
1371// branch to a common successor. Analyze each instruction and return true if it
1372// would be possible to sink them into their successor, creating one common
1373// instruction instead. For every value that would be required to be provided by
1374// PHI node (because an operand varies in each input block), add to PHIOperands.
1375static bool canSinkInstructions(
1376 ArrayRef<Instruction *> Insts,
1377 DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
James Molloy5bf21142016-08-22 19:07:15 +00001378 // Prune out obviously bad instructions to move. Any non-store instruction
1379 // must have exactly one use, and we check later that use is by a single,
1380 // common PHI instruction in the successor.
1381 for (auto *I : Insts) {
1382 // These instructions may change or break semantics if moved.
1383 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1384 I->getType()->isTokenTy())
1385 return false;
James Molloy5bf21142016-08-22 19:07:15 +00001386 // Everything must have only one use too, apart from stores which
1387 // have no uses.
1388 if (!isa<StoreInst>(I) && !I->hasOneUse())
1389 return false;
1390 }
1391
1392 const Instruction *I0 = Insts.front();
1393 for (auto *I : Insts)
1394 if (!I->isSameOperationAs(I0))
1395 return false;
1396
James Molloy55bd04c2016-08-31 10:46:23 +00001397 // All instructions in Insts are known to be the same opcode. If they aren't
1398 // stores, check the only user of each is a PHI or in the same block as the
1399 // instruction, because if a user is in the same block as an instruction
1400 // we're contemplating sinking, it must already be determined to be sinkable.
James Molloy5bf21142016-08-22 19:07:15 +00001401 if (!isa<StoreInst>(I0)) {
1402 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
James Molloy55bd04c2016-08-31 10:46:23 +00001403 if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
1404 auto *U = cast<Instruction>(*I->user_begin());
1405 return U == PNUse || U->getParent() == I->getParent();
James Molloy5bf21142016-08-22 19:07:15 +00001406 }))
1407 return false;
1408 }
1409
James Molloy5bf21142016-08-22 19:07:15 +00001410 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1411 if (I0->getOperand(OI)->getType()->isTokenTy())
1412 // Don't touch any operand of token type.
1413 return false;
1414 auto SameAsI0 = [&I0, OI](const Instruction *I) {
James Molloy55bd04c2016-08-31 10:46:23 +00001415 assert(I->getNumOperands() == I0->getNumOperands());
1416 return I->getOperand(OI) == I0->getOperand(OI);
James Molloy5bf21142016-08-22 19:07:15 +00001417 };
1418 if (!all_of(Insts, SameAsI0)) {
1419 if (!canReplaceOperandWithVariable(I0, OI))
1420 // We can't create a PHI from this GEP.
1421 return false;
James Molloy923e98c2016-08-31 10:46:16 +00001422 // Don't create indirect calls! The called value is the final operand.
1423 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OI == OE - 1) {
James Molloy5bf21142016-08-22 19:07:15 +00001424 // FIXME: if the call was *already* indirect, we should do this.
1425 return false;
James Molloy923e98c2016-08-31 10:46:16 +00001426 }
James Molloy55bd04c2016-08-31 10:46:23 +00001427 for (auto *I : Insts)
1428 PHIOperands[I].push_back(I->getOperand(OI));
James Molloy5bf21142016-08-22 19:07:15 +00001429 }
1430 }
1431 return true;
1432}
1433
1434// Assuming canSinkLastInstruction(Blocks) has returned true, sink the last
1435// instruction of every block in Blocks to their common successor, commoning
1436// into one instruction.
James Molloy8a66a392016-08-31 13:16:30 +00001437static void sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
James Molloy5bf21142016-08-22 19:07:15 +00001438 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1439
1440 // canSinkLastInstruction returning true guarantees that every block has at
1441 // least one non-terminator instruction.
1442 SmallVector<Instruction*,4> Insts;
1443 for (auto *BB : Blocks)
1444 Insts.push_back(BB->getTerminator()->getPrevNode());
1445
James Molloy8a66a392016-08-31 13:16:30 +00001446 // We don't need to do any checking here; canSinkLastInstruction should have
1447 // done it all for us.
James Molloy5bf21142016-08-22 19:07:15 +00001448 Instruction *I0 = Insts.front();
1449 SmallVector<Value*, 4> NewOperands;
1450 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
1451 // This check is different to that in canSinkLastInstruction. There, we
1452 // cared about the global view once simplifycfg (and instcombine) have
1453 // completed - it takes into account PHIs that become trivially
1454 // simplifiable. However here we need a more local view; if an operand
1455 // differs we create a PHI and rely on instcombine to clean up the very
1456 // small mess we may make.
1457 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
1458 return I->getOperand(O) != I0->getOperand(O);
1459 });
1460 if (!NeedPHI) {
1461 NewOperands.push_back(I0->getOperand(O));
1462 continue;
1463 }
1464
1465 // Create a new PHI in the successor block and populate it.
1466 auto *Op = I0->getOperand(O);
1467 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
1468 auto *PN = PHINode::Create(Op->getType(), Insts.size(),
1469 Op->getName() + ".sink", &BBEnd->front());
1470 for (auto *I : Insts)
1471 PN->addIncoming(I->getOperand(O), I->getParent());
1472 NewOperands.push_back(PN);
1473 }
1474
1475 // Arbitrarily use I0 as the new "common" instruction; remap its operands
1476 // and move it to the start of the successor block.
1477 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
1478 I0->getOperandUse(O).set(NewOperands[O]);
1479 I0->moveBefore(&*BBEnd->getFirstInsertionPt());
1480
James Molloyd13b1232016-08-30 10:56:08 +00001481 // Update metadata.
1482 for (auto *I : Insts)
1483 if (I != I0)
1484 combineMetadataForCSE(I0, I);
1485
James Molloy5bf21142016-08-22 19:07:15 +00001486 if (!isa<StoreInst>(I0)) {
1487 // canSinkLastInstruction checked that all instructions were used by
1488 // one and only one PHI node. Find that now, RAUW it to our common
1489 // instruction and nuke it.
1490 assert(I0->hasOneUse());
1491 auto *PN = cast<PHINode>(*I0->user_begin());
1492 PN->replaceAllUsesWith(I0);
1493 PN->eraseFromParent();
1494 }
1495
1496 // Finally nuke all instructions apart from the common instruction.
1497 for (auto *I : Insts)
1498 if (I != I0)
1499 I->eraseFromParent();
1500}
1501
James Molloy55bd04c2016-08-31 10:46:23 +00001502namespace {
1503 // LockstepReverseIterator - Iterates through instructions
1504 // in a set of blocks in reverse order from the first non-terminator.
1505 // For example (assume all blocks have size n):
1506 // LockstepReverseIterator I([B1, B2, B3]);
1507 // *I-- = [B1[n], B2[n], B3[n]];
1508 // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
1509 // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
1510 // ...
1511 class LockstepReverseIterator {
1512 ArrayRef<BasicBlock*> Blocks;
1513 SmallVector<Instruction*,4> Insts;
1514 bool Fail;
1515 public:
1516 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) :
1517 Blocks(Blocks) {
1518 reset();
1519 }
1520
1521 void reset() {
1522 Fail = false;
1523 Insts.clear();
1524 for (auto *BB : Blocks) {
1525 if (BB->size() <= 1) {
1526 // Block wasn't big enough
1527 Fail = true;
1528 return;
1529 }
1530 Insts.push_back(BB->getTerminator()->getPrevNode());
1531 }
1532 }
1533
1534 bool isValid() const {
1535 return !Fail;
1536 }
1537
1538 void operator -- () {
1539 if (Fail)
1540 return;
1541 for (auto *&Inst : Insts) {
1542 if (Inst == &Inst->getParent()->front()) {
1543 Fail = true;
1544 return;
1545 }
1546 Inst = Inst->getPrevNode();
1547 }
1548 }
1549
1550 ArrayRef<Instruction*> operator * () const {
1551 return Insts;
1552 }
1553 };
1554}
1555
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001556/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001557/// check whether BBEnd has only two predecessors and the other predecessor
1558/// ends with an unconditional branch. If it is true, sink any common code
1559/// in the two predecessors to BBEnd.
1560static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1561 assert(BI1->isUnconditional());
Manman Ren93ab6492012-09-20 22:37:36 +00001562 BasicBlock *BBEnd = BI1->getSuccessor(0);
1563
James Molloy76c9d422016-08-31 13:16:45 +00001564 // We currently only support branch targets with two predecessors.
1565 // FIXME: this is an arbitrary restriction and should be lifted.
1566 SmallVector<BasicBlock*,4> Blocks;
1567 for (auto *BB : predecessors(BBEnd))
1568 Blocks.push_back(BB);
1569 if (Blocks.size() != 2 ||
1570 !all_of(Blocks, [](const BasicBlock *BB) {
1571 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
1572 return BI && BI->isUnconditional();
1573 }))
James Molloy475f4a72016-08-22 18:13:12 +00001574 return false;
James Molloy76c9d422016-08-31 13:16:45 +00001575
Manman Ren93ab6492012-09-20 22:37:36 +00001576 bool Changed = false;
James Molloy76c9d422016-08-31 13:16:45 +00001577
James Molloy55bd04c2016-08-31 10:46:23 +00001578 // We take a two-step approach to tail sinking. First we scan from the end of
1579 // each block upwards in lockstep. If the n'th instruction from the end of each
1580 // block can be sunk, those instructions are added to ValuesToSink and we
1581 // carry on. If we can sink an instruction but need to PHI-merge some operands
1582 // (because they're not identical in each instruction) we add these to
1583 // PHIOperands.
1584 unsigned ScanIdx = 0;
1585 SmallPtrSet<Value*,4> InstructionsToSink;
1586 DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
James Molloy76c9d422016-08-31 13:16:45 +00001587 LockstepReverseIterator LRI(Blocks);
James Molloy55bd04c2016-08-31 10:46:23 +00001588 while (LRI.isValid() &&
1589 canSinkInstructions(*LRI, PHIOperands)) {
James Molloy8a66a392016-08-31 13:16:30 +00001590 DEBUG(dbgs() << "SINK: instruction can be sunk: " << (*LRI)[0] << "\n");
James Molloy55bd04c2016-08-31 10:46:23 +00001591 InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
1592 ++ScanIdx;
1593 --LRI;
1594 }
1595
1596 // Now that we've analyzed all potential sinking candidates, perform the
1597 // actual sink. We iteratively sink the last non-terminator of the source
1598 // blocks into their common successor unless doing so would require too
1599 // many PHI instructions to be generated (currently only one PHI is allowed
1600 // per sunk instruction).
1601 //
1602 // We can use InstructionsToSink to discount values needing PHI-merging that will
1603 // actually be sunk in a later iteration. This allows us to be more
1604 // aggressive in what we sink. This does allow a false positive where we
1605 // sink presuming a later value will also be sunk, but stop half way through
1606 // and never actually sink it which means we produce more PHIs than intended.
1607 // This is unlikely in practice though.
1608 for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
1609 DEBUG(dbgs() << "SINK: Sink: "
James Molloy76c9d422016-08-31 13:16:45 +00001610 << *Blocks[0]->getTerminator()->getPrevNode()
James Molloy55bd04c2016-08-31 10:46:23 +00001611 << "\n");
1612 // Because we've sunk every instruction in turn, the current instruction to
1613 // sink is always at index 0.
James Molloy76c9d422016-08-31 13:16:45 +00001614 LRI.reset();
1615 unsigned NumPHIdValues = 0;
1616 for (auto *I : *LRI)
1617 for (auto *V : PHIOperands[I])
1618 if (InstructionsToSink.count(V) == 0)
1619 ++NumPHIdValues;
1620 DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
1621 assert((NumPHIdValues % Blocks.size() == 0) &&
1622 "Every operand must either be PHId or not PHId!");
James Molloy55bd04c2016-08-31 10:46:23 +00001623
James Molloy76c9d422016-08-31 13:16:45 +00001624 if (NumPHIdValues / Blocks.size() > 1)
1625 // Too many PHIs would be created.
1626 break;
1627
1628 sinkLastInstruction(Blocks);
Manman Ren93ab6492012-09-20 22:37:36 +00001629 NumSinkCommons++;
1630 Changed = true;
1631 }
James Molloy76c9d422016-08-31 13:16:45 +00001632
Manman Ren93ab6492012-09-20 22:37:36 +00001633 return Changed;
1634}
1635
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001636/// \brief Determine if we can hoist sink a sole store instruction out of a
1637/// conditional block.
1638///
1639/// We are looking for code like the following:
1640/// BrBB:
1641/// store i32 %add, i32* %arrayidx2
1642/// ... // No other stores or function calls (we could be calling a memory
1643/// ... // function).
1644/// %cmp = icmp ult %x, %y
1645/// br i1 %cmp, label %EndBB, label %ThenBB
1646/// ThenBB:
1647/// store i32 %add5, i32* %arrayidx2
1648/// br label EndBB
1649/// EndBB:
1650/// ...
1651/// We are going to transform this into:
1652/// BrBB:
1653/// store i32 %add, i32* %arrayidx2
1654/// ... //
1655/// %cmp = icmp ult %x, %y
1656/// %add.add5 = select i1 %cmp, i32 %add, %add5
1657/// store i32 %add.add5, i32* %arrayidx2
1658/// ...
1659///
1660/// \return The pointer to the value of the previous store if the store can be
1661/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001662static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1663 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001664 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1665 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001666 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001667
1668 // Volatile or atomic.
1669 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001670 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001671
1672 Value *StorePtr = StoreToHoist->getPointerOperand();
1673
1674 // Look for a store to the same pointer in BrBB.
Hans Wennborg0c3518e2016-05-04 15:40:57 +00001675 unsigned MaxNumInstToLookAt = 9;
David Majnemerd7708772016-06-24 04:05:21 +00001676 for (Instruction &CurI : reverse(*BrBB)) {
1677 if (!MaxNumInstToLookAt)
1678 break;
Hans Wennborg0c3518e2016-05-04 15:40:57 +00001679 // Skip debug info.
1680 if (isa<DbgInfoIntrinsic>(CurI))
1681 continue;
1682 --MaxNumInstToLookAt;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001683
David L Kreitzer96674172016-08-12 21:06:53 +00001684 // Could be calling an instruction that affects memory like free().
David Majnemerd7708772016-06-24 04:05:21 +00001685 if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001686 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001687
David Majnemerd7708772016-06-24 04:05:21 +00001688 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
1689 // Found the previous store make sure it stores to the same location.
1690 if (SI->getPointerOperand() == StorePtr)
1691 // Found the previous store, return its value operand.
1692 return SI->getValueOperand();
Craig Topperf40110f2014-04-25 05:29:35 +00001693 return nullptr; // Unknown store.
David Majnemerd7708772016-06-24 04:05:21 +00001694 }
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001695 }
1696
Craig Topperf40110f2014-04-25 05:29:35 +00001697 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001698}
1699
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001700/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001701///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001702/// Note that this is a very risky transform currently. Speculating
1703/// instructions like this is most often not desirable. Instead, there is an MI
1704/// pass which can do it with full awareness of the resource constraints.
1705/// However, some cases are "obvious" and we should do directly. An example of
1706/// this is speculating a single, reasonably cheap instruction.
1707///
1708/// There is only one distinct advantage to flattening the CFG at the IR level:
1709/// it makes very common but simplistic optimizations such as are common in
1710/// instcombine and the DAG combiner more powerful by removing CFG edges and
1711/// modeling their effects with easier to reason about SSA value graphs.
1712///
1713///
1714/// An illustration of this transform is turning this IR:
1715/// \code
1716/// BB:
1717/// %cmp = icmp ult %x, %y
1718/// br i1 %cmp, label %EndBB, label %ThenBB
1719/// ThenBB:
1720/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001721/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001722/// EndBB:
1723/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1724/// ...
1725/// \endcode
1726///
1727/// Into this IR:
1728/// \code
1729/// BB:
1730/// %cmp = icmp ult %x, %y
1731/// %sub = sub %x, %y
1732/// %cond = select i1 %cmp, 0, %sub
1733/// ...
1734/// \endcode
1735///
1736/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001737static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001738 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001739 // Be conservative for now. FP select instruction can often be expensive.
1740 Value *BrCond = BI->getCondition();
1741 if (isa<FCmpInst>(BrCond))
1742 return false;
1743
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001744 BasicBlock *BB = BI->getParent();
1745 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1746
1747 // If ThenBB is actually on the false edge of the conditional branch, remember
1748 // to swap the select operands later.
1749 bool Invert = false;
1750 if (ThenBB != BI->getSuccessor(0)) {
1751 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1752 Invert = true;
1753 }
1754 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1755
Chandler Carruthceff2222013-01-25 05:40:09 +00001756 // Keep a count of how many times instructions are used within CondBB when
1757 // they are candidates for sinking into CondBB. Specifically:
1758 // - They are defined in BB, and
1759 // - They have no side effects, and
1760 // - All of their uses are in CondBB.
1761 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1762
Chandler Carruth7481ca82013-01-24 11:52:58 +00001763 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001764 Value *SpeculatedStoreValue = nullptr;
1765 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001766 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001767 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001768 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001769 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001770 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001771 if (isa<DbgInfoIntrinsic>(I))
1772 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001773
Mark Lacey274f48b2015-04-12 18:18:51 +00001774 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001775 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001776 ++SpeculationCost;
1777 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001778 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001779
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001780 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001781 if (!isSafeToSpeculativelyExecute(I) &&
1782 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1783 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001784 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001785 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001786 ComputeSpeculationCost(I, TTI) >
1787 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001788 return false;
1789
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001790 // Store the store speculation candidate.
1791 if (SpeculatedStoreValue)
1792 SpeculatedStore = cast<StoreInst>(I);
1793
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001794 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001795 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001796 // being sunk into the use block.
Dehao Chenf6c00832016-05-18 19:44:21 +00001797 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001798 Instruction *OpI = dyn_cast<Instruction>(*i);
Dehao Chenf6c00832016-05-18 19:44:21 +00001799 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
Chandler Carruthceff2222013-01-25 05:40:09 +00001800 continue; // Not a candidate for sinking.
1801
1802 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001803 }
1804 }
Evan Cheng89200c92008-06-07 08:52:29 +00001805
Chandler Carruthceff2222013-01-25 05:40:09 +00001806 // Consider any sink candidates which are only used in CondBB as costs for
1807 // speculation. Note, while we iterate over a DenseMap here, we are summing
1808 // and so iteration order isn't significant.
Dehao Chenf6c00832016-05-18 19:44:21 +00001809 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
1810 I = SinkCandidateUseCounts.begin(),
1811 E = SinkCandidateUseCounts.end();
Chandler Carruthceff2222013-01-25 05:40:09 +00001812 I != E; ++I)
1813 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001814 ++SpeculationCost;
1815 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001816 return false;
1817 }
1818
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001819 // Check that the PHI nodes can be converted to selects.
1820 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001821 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001822 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001823 Value *OrigV = PN->getIncomingValueForBlock(BB);
1824 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001825
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001826 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001827 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001828 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001829 continue;
1830
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001831 // Don't convert to selects if we could remove undefined behavior instead.
1832 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1833 passingValueIsAlwaysUndefined(ThenV, PN))
1834 return false;
1835
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001836 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001837 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1838 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1839 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001840 continue; // Known safe and cheap.
1841
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001842 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1843 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001844 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001845 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1846 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
Dehao Chenf6c00832016-05-18 19:44:21 +00001847 unsigned MaxCost =
1848 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
James Molloy7c336572015-02-11 12:15:41 +00001849 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00001850 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001851
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001852 // Account for the cost of an unfolded ConstantExpr which could end up
1853 // getting expanded into Instructions.
1854 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001855 // constant expression.
1856 ++SpeculationCost;
1857 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001858 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001859 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001860
1861 // If there are no PHIs to process, bail early. This helps ensure idempotence
1862 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001863 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001864 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001865
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001866 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001867 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001868
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001869 // Insert a select of the value of the speculated store.
1870 if (SpeculatedStoreValue) {
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001871 IRBuilder<NoFolder> Builder(BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001872 Value *TrueV = SpeculatedStore->getValueOperand();
1873 Value *FalseV = SpeculatedStoreValue;
1874 if (Invert)
1875 std::swap(TrueV, FalseV);
Sanjay Patel796db352016-03-26 23:30:50 +00001876 Value *S = Builder.CreateSelect(
1877 BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001878 SpeculatedStore->setOperand(0, S);
1879 }
1880
Igor Laevsky7310c682015-11-18 14:50:18 +00001881 // Metadata can be dependent on the condition we are hoisting above.
1882 // Conservatively strip all metadata on the instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00001883 for (auto &I : *ThenBB)
Igor Laevsky7310c682015-11-18 14:50:18 +00001884 I.dropUnknownNonDebugMetadata();
1885
Chandler Carruth7481ca82013-01-24 11:52:58 +00001886 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001887 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
1888 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001889
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001890 // Insert selects and rewrite the PHI operands.
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001891 IRBuilder<NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001892 for (BasicBlock::iterator I = EndBB->begin();
1893 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1894 unsigned OrigI = PN->getBasicBlockIndex(BB);
1895 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1896 Value *OrigV = PN->getIncomingValue(OrigI);
1897 Value *ThenV = PN->getIncomingValue(ThenI);
1898
1899 // Skip PHIs which are trivial.
1900 if (OrigV == ThenV)
1901 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001902
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001903 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001904 // false value is the preexisting value. Swap them if the branch
1905 // destinations were inverted.
1906 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001907 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001908 std::swap(TrueV, FalseV);
Sanjay Patelf11ab052016-04-15 15:32:12 +00001909 Value *V = Builder.CreateSelect(
1910 BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001911 PN->setIncomingValue(OrigI, V);
1912 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001913 }
1914
Evan Cheng89553cc2008-06-12 21:15:59 +00001915 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001916 return true;
1917}
1918
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001919/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001920static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1921 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001922 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001923
Devang Patel84fceff2009-03-10 18:00:05 +00001924 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001925 if (isa<DbgInfoIntrinsic>(BBI))
1926 continue;
Dehao Chenf6c00832016-05-18 19:44:21 +00001927 if (Size > 10)
1928 return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001929 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001930
Dale Johannesened6f5a82009-03-12 23:18:09 +00001931 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001932 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001933 for (User *U : BBI->users()) {
1934 Instruction *UI = cast<Instruction>(U);
Dehao Chenf6c00832016-05-18 19:44:21 +00001935 if (UI->getParent() != BB || isa<PHINode>(UI))
1936 return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001937 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001938
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001939 // Looks ok, continue checking.
1940 }
Chris Lattner6c701062005-09-20 01:48:40 +00001941
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001942 return true;
1943}
1944
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001945/// If we have a conditional branch on a PHI node value that is defined in the
1946/// same block as the branch and if any PHI entries are constants, thread edges
1947/// corresponding to that entry to be branches to their ultimate destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001948static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001949 BasicBlock *BB = BI->getParent();
1950 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001951 // NOTE: we currently cannot transform this case if the PHI node is used
1952 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001953 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1954 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001955
Chris Lattner748f9032005-09-19 23:49:37 +00001956 // Degenerate case of a single entry PHI.
1957 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001958 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001959 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001960 }
1961
1962 // Now we know that this block has multiple preds and two succs.
Dehao Chenf6c00832016-05-18 19:44:21 +00001963 if (!BlockIsSimpleEnoughToThreadThrough(BB))
1964 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001965
Justin Lebardb639492016-02-12 21:01:36 +00001966 // Can't fold blocks that contain noduplicate or convergent calls.
David Majnemer0a16c222016-08-11 21:15:00 +00001967 if (any_of(*BB, [](const Instruction &I) {
Justin Lebardb639492016-02-12 21:01:36 +00001968 const CallInst *CI = dyn_cast<CallInst>(&I);
1969 return CI && (CI->cannotDuplicate() || CI->isConvergent());
1970 }))
1971 return false;
Tom Stellarde1631dd2013-10-21 20:07:30 +00001972
Chris Lattner748f9032005-09-19 23:49:37 +00001973 // Okay, this is a simple enough basic block. See if any phi values are
1974 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001975 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001976 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Dehao Chenf6c00832016-05-18 19:44:21 +00001977 if (!CB || !CB->getType()->isIntegerTy(1))
1978 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001979
Chris Lattner4088e2b2010-12-13 01:47:07 +00001980 // Okay, we now know that all edges from PredBB should be revectored to
1981 // branch to RealDest.
1982 BasicBlock *PredBB = PN->getIncomingBlock(i);
1983 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001984
Dehao Chenf6c00832016-05-18 19:44:21 +00001985 if (RealDest == BB)
1986 continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001987 // Skip if the predecessor's terminator is an indirect branch.
Dehao Chenf6c00832016-05-18 19:44:21 +00001988 if (isa<IndirectBrInst>(PredBB->getTerminator()))
1989 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001990
Chris Lattner4088e2b2010-12-13 01:47:07 +00001991 // The dest block might have PHI nodes, other predecessors and other
1992 // difficult cases. Instead of being smart about this, just insert a new
1993 // block that jumps to the destination block, effectively splitting
1994 // the edge we are about to create.
Dehao Chenf6c00832016-05-18 19:44:21 +00001995 BasicBlock *EdgeBB =
1996 BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
1997 RealDest->getParent(), RealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001998 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001999
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002000 // Update PHI nodes.
2001 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002002
2003 // BB may have instructions that are being threaded over. Clone these
2004 // instructions into EdgeBB. We know that there will be no uses of the
2005 // cloned instructions outside of EdgeBB.
2006 BasicBlock::iterator InsertPt = EdgeBB->begin();
Dehao Chenf6c00832016-05-18 19:44:21 +00002007 DenseMap<Value *, Value *> TranslateMap; // Track translated values.
Chris Lattner4088e2b2010-12-13 01:47:07 +00002008 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
2009 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
2010 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
2011 continue;
2012 }
2013 // Clone the instruction.
2014 Instruction *N = BBI->clone();
Dehao Chenf6c00832016-05-18 19:44:21 +00002015 if (BBI->hasName())
2016 N->setName(BBI->getName() + ".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002017
Chris Lattner4088e2b2010-12-13 01:47:07 +00002018 // Update operands due to translation.
Dehao Chenf6c00832016-05-18 19:44:21 +00002019 for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) {
2020 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002021 if (PI != TranslateMap.end())
2022 *i = PI->second;
2023 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002024
Chris Lattner4088e2b2010-12-13 01:47:07 +00002025 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002026 if (Value *V = SimplifyInstruction(N, DL)) {
David Majnemerb8da3a22016-06-25 00:04:10 +00002027 if (!BBI->use_empty())
2028 TranslateMap[&*BBI] = V;
2029 if (!N->mayHaveSideEffects()) {
2030 delete N; // Instruction folded away, don't need actual inst
2031 N = nullptr;
2032 }
Chris Lattner4088e2b2010-12-13 01:47:07 +00002033 } else {
Chris Lattner4088e2b2010-12-13 01:47:07 +00002034 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002035 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00002036 }
David Majnemerb8da3a22016-06-25 00:04:10 +00002037 // Insert the new instruction into its new home.
2038 if (N)
2039 EdgeBB->getInstList().insert(InsertPt, N);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002040 }
2041
2042 // Loop over all of the edges from PredBB to BB, changing them to branch
2043 // to EdgeBB instead.
2044 TerminatorInst *PredBBTI = PredBB->getTerminator();
2045 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
2046 if (PredBBTI->getSuccessor(i) == BB) {
2047 BB->removePredecessor(PredBB);
2048 PredBBTI->setSuccessor(i, EdgeBB);
2049 }
Bill Wendling4f163df2011-06-04 09:42:04 +00002050
Chris Lattner4088e2b2010-12-13 01:47:07 +00002051 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002052 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00002053 }
Chris Lattner748f9032005-09-19 23:49:37 +00002054
2055 return false;
2056}
2057
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002058/// Given a BB that starts with the specified two-entry PHI node,
2059/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002060static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
2061 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002062 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
2063 // statement", which has a very simple dominance structure. Basically, we
2064 // are trying to find the condition that is being branched on, which
2065 // subsequently causes this merge to happen. We really want control
2066 // dependence information for this check, but simplifycfg can't keep it up
2067 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002068 BasicBlock *BB = PN->getParent();
2069 BasicBlock *IfTrue, *IfFalse;
2070 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00002071 if (!IfCond ||
2072 // Don't bother if the branch will be constant folded trivially.
2073 isa<ConstantInt>(IfCond))
2074 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002075
Chris Lattner95adf8f12006-11-18 19:19:36 +00002076 // Okay, we found that we can merge this two-entry phi node into a select.
2077 // Doing so would require us to fold *all* two entry phi nodes in this block.
2078 // At some point this becomes non-profitable (particularly if the target
2079 // doesn't support cmov's). Only do this transformation if there are two or
2080 // fewer PHI nodes in this block.
2081 unsigned NumPhis = 0;
2082 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
2083 if (NumPhis > 2)
2084 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002085
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002086 // Loop over the PHI's seeing if we can promote them all to select
2087 // instructions. While we are at it, keep track of the instructions
2088 // that need to be moved to the dominating block.
Dehao Chenf6c00832016-05-18 19:44:21 +00002089 SmallPtrSet<Instruction *, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00002090 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
2091 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00002092 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
2093 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002094
Chris Lattner7499b452010-12-14 08:46:09 +00002095 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
2096 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002097 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00002098 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00002099 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00002100 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002101 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002102
Peter Collingbournee3511e12011-04-29 18:47:31 +00002103 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002104 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00002105 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002106 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00002107 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002108 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002109
Sylvestre Ledru35521e22012-07-23 08:51:15 +00002110 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00002111 // we ran out of PHIs then we simplified them all.
2112 PN = dyn_cast<PHINode>(BB->begin());
Dehao Chenf6c00832016-05-18 19:44:21 +00002113 if (!PN)
2114 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002115
Chris Lattner7499b452010-12-14 08:46:09 +00002116 // Don't fold i1 branches on PHIs which contain binary operators. These can
2117 // often be turned into switches and other things.
2118 if (PN->getType()->isIntegerTy(1) &&
2119 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
2120 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
2121 isa<BinaryOperator>(IfCond)))
2122 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002123
Sanjay Patel2e002772016-03-12 18:05:53 +00002124 // If all PHI nodes are promotable, check to make sure that all instructions
2125 // in the predecessor blocks can be promoted as well. If not, we won't be able
2126 // to get rid of the control flow, so it's not worth promoting to select
2127 // instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00002128 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002129 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
2130 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
2131 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002132 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002133 } else {
2134 DomBlock = *pred_begin(IfBlock1);
Dehao Chenf6c00832016-05-18 19:44:21 +00002135 for (BasicBlock::iterator I = IfBlock1->begin(); !isa<TerminatorInst>(I);
2136 ++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002137 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002138 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00002139 // Because of this, we won't be able to get rid of the control flow, so
2140 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002141 return false;
2142 }
2143 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002144
Chris Lattner9ac168d2010-12-14 07:41:39 +00002145 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002146 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002147 } else {
2148 DomBlock = *pred_begin(IfBlock2);
Dehao Chenf6c00832016-05-18 19:44:21 +00002149 for (BasicBlock::iterator I = IfBlock2->begin(); !isa<TerminatorInst>(I);
2150 ++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002151 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002152 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00002153 // Because of this, we won't be able to get rid of the control flow, so
2154 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002155 return false;
2156 }
2157 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002158
Chris Lattner9fd838d2010-12-14 07:23:10 +00002159 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00002160 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002161
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002162 // If we can still promote the PHI nodes after this gauntlet of tests,
2163 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00002164 Instruction *InsertPt = DomBlock->getTerminator();
Mehdi Aminiba9fba82016-03-13 21:05:13 +00002165 IRBuilder<NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002166
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002167 // Move all 'aggressive' instructions, which are defined in the
2168 // conditional parts of the if's up to the dominating block.
David Majnemere8fd5f92016-08-29 17:14:08 +00002169 if (IfBlock1) {
2170 for (auto &I : *IfBlock1)
2171 I.dropUnknownNonDebugMetadata();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002172 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00002173 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002174 IfBlock1->getTerminator()->getIterator());
David Majnemere8fd5f92016-08-29 17:14:08 +00002175 }
2176 if (IfBlock2) {
2177 for (auto &I : *IfBlock2)
2178 I.dropUnknownNonDebugMetadata();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002179 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00002180 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002181 IfBlock2->getTerminator()->getIterator());
David Majnemere8fd5f92016-08-29 17:14:08 +00002182 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002183
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002184 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
2185 // Change the PHI node into a select instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00002186 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002187 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002188
Sanjay Patel9e23fed2016-03-17 15:30:52 +00002189 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
2190 PN->replaceAllUsesWith(Sel);
2191 Sel->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00002192 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002193 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002194
Chris Lattner335f0e42010-12-14 08:01:53 +00002195 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
2196 // has been flattened. Change DomBlock to jump directly to our new block to
2197 // avoid other simplifycfg's kicking in on the diamond.
2198 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00002199 Builder.SetInsertPoint(OldTI);
2200 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00002201 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002202 return true;
2203}
Chris Lattner748f9032005-09-19 23:49:37 +00002204
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002205/// If we found a conditional branch that goes to two returning blocks,
2206/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00002207/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002208static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00002209 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002210 assert(BI->isConditional() && "Must be a conditional branch");
2211 BasicBlock *TrueSucc = BI->getSuccessor(0);
2212 BasicBlock *FalseSucc = BI->getSuccessor(1);
2213 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2214 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002215
Chris Lattner86bbf332008-04-24 00:01:19 +00002216 // Check to ensure both blocks are empty (just a return) or optionally empty
2217 // with PHI nodes. If there are other instructions, merging would cause extra
2218 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00002219 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00002220 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00002221 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00002222 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00002223
Devang Pateldd14e0f2011-05-18 21:33:11 +00002224 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002225 // Okay, we found a branch that is going to two return nodes. If
2226 // there is no return value for this function, just change the
2227 // branch into a return.
2228 if (FalseRet->getNumOperands() == 0) {
2229 TrueSucc->removePredecessor(BI->getParent());
2230 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00002231 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00002232 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002233 return true;
2234 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002235
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002236 // Otherwise, figure out what the true and false return values are
2237 // so we can insert a new select instruction.
2238 Value *TrueValue = TrueRet->getReturnValue();
2239 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002240
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002241 // Unwrap any PHI nodes in the return blocks.
2242 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2243 if (TVPN->getParent() == TrueSucc)
2244 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
2245 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2246 if (FVPN->getParent() == FalseSucc)
2247 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002248
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002249 // In order for this transformation to be safe, we must be able to
2250 // unconditionally execute both operands to the return. This is
2251 // normally the case, but we could have a potentially-trapping
2252 // constant expression that prevents this transformation from being
2253 // safe.
2254 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2255 if (TCV->canTrap())
2256 return false;
2257 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2258 if (FCV->canTrap())
2259 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002260
Chris Lattner86bbf332008-04-24 00:01:19 +00002261 // Okay, we collected all the mapped values and checked them for sanity, and
2262 // defined to really do this transformation. First, update the CFG.
2263 TrueSucc->removePredecessor(BI->getParent());
2264 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002265
Chris Lattner86bbf332008-04-24 00:01:19 +00002266 // Insert select instructions where needed.
2267 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002268 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002269 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002270 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2271 } else if (isa<UndefValue>(TrueValue)) {
2272 TrueValue = FalseValue;
2273 } else {
Sanjay Patelfacf45a2016-04-27 23:14:12 +00002274 TrueValue =
2275 Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002276 }
Chris Lattner86bbf332008-04-24 00:01:19 +00002277 }
2278
Dehao Chenf6c00832016-05-18 19:44:21 +00002279 Value *RI =
2280 !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
Devang Pateldd14e0f2011-05-18 21:33:11 +00002281
Dehao Chenf6c00832016-05-18 19:44:21 +00002282 (void)RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002283
David Greene725c7c32010-01-05 01:26:52 +00002284 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002285 << "\n " << *BI << "NewRet = " << *RI
Dehao Chenf6c00832016-05-18 19:44:21 +00002286 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: " << *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002287
Eli Friedmancb61afb2008-12-16 20:54:32 +00002288 EraseTerminatorInstAndDCECond(BI);
2289
Chris Lattner86bbf332008-04-24 00:01:19 +00002290 return true;
2291}
2292
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002293/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002294/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002295static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002296 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2297 return false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00002298 for (Instruction &I : *PB) {
2299 Instruction *PBI = &I;
Manman Rend33f4ef2012-06-13 05:43:29 +00002300 // Check whether Inst and PBI generate the same value.
2301 if (Inst->isIdenticalTo(PBI)) {
2302 Inst->replaceAllUsesWith(PBI);
2303 Inst->eraseFromParent();
2304 return true;
2305 }
2306 }
2307 return false;
2308}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002309
Dehao Chenf16376b2016-05-18 22:41:03 +00002310/// Return true if either PBI or BI has branch weight available, and store
2311/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
2312/// not have branch weight, use 1:1 as its weight.
2313static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
2314 uint64_t &PredTrueWeight,
2315 uint64_t &PredFalseWeight,
2316 uint64_t &SuccTrueWeight,
2317 uint64_t &SuccFalseWeight) {
2318 bool PredHasWeights =
2319 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
2320 bool SuccHasWeights =
2321 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
2322 if (PredHasWeights || SuccHasWeights) {
2323 if (!PredHasWeights)
2324 PredTrueWeight = PredFalseWeight = 1;
2325 if (!SuccHasWeights)
2326 SuccTrueWeight = SuccFalseWeight = 1;
2327 return true;
2328 } else {
2329 return false;
2330 }
2331}
2332
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002333/// If this basic block is simple enough, and if a predecessor branches to us
2334/// and one of our successors, fold the block into the predecessor and use
2335/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002336bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002337 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002338
Craig Topperf40110f2014-04-25 05:29:35 +00002339 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002340 if (BI->isConditional())
2341 Cond = dyn_cast<Instruction>(BI->getCondition());
2342 else {
2343 // For unconditional branch, check for a simple CFG pattern, where
2344 // BB has a single predecessor and BB's successor is also its predecessor's
2345 // successor. If such pattern exisits, check for CSE between BB and its
2346 // predecessor.
2347 if (BasicBlock *PB = BB->getSinglePredecessor())
2348 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2349 if (PBI->isConditional() &&
2350 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2351 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002352 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002353 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002354 if (isa<CmpInst>(Curr)) {
2355 Cond = Curr;
2356 break;
2357 }
2358 // Quit if we can't remove this instruction.
2359 if (!checkCSEInPredecessor(Curr, PB))
2360 return false;
2361 }
2362 }
2363
Craig Topperf40110f2014-04-25 05:29:35 +00002364 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002365 return false;
2366 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002367
Craig Topperf40110f2014-04-25 05:29:35 +00002368 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2369 Cond->getParent() != BB || !Cond->hasOneUse())
Sanjay Patel2e002772016-03-12 18:05:53 +00002370 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002371
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002372 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002373 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002374
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002375 // Ignore dbg intrinsics.
Dehao Chenf6c00832016-05-18 19:44:21 +00002376 while (isa<DbgInfoIntrinsic>(CondIt))
2377 ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002378
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002379 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002380 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002381
Jingyue Wufc029672014-09-30 22:23:38 +00002382 // Only allow this transformation if computing the condition doesn't involve
2383 // too many instructions and these involved instructions can be executed
2384 // unconditionally. We denote all involved instructions except the condition
2385 // as "bonus instructions", and only allow this transformation when the
2386 // number of the bonus instructions does not exceed a certain threshold.
2387 unsigned NumBonusInsts = 0;
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002388 for (auto I = BB->begin(); Cond != &*I; ++I) {
Jingyue Wufc029672014-09-30 22:23:38 +00002389 // Ignore dbg intrinsics.
2390 if (isa<DbgInfoIntrinsic>(I))
2391 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002392 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002393 return false;
2394 // I has only one use and can be executed unconditionally.
2395 Instruction *User = dyn_cast<Instruction>(I->user_back());
2396 if (User == nullptr || User->getParent() != BB)
2397 return false;
2398 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2399 // to use any other instruction, User must be an instruction between next(I)
2400 // and Cond.
2401 ++NumBonusInsts;
2402 // Early exits once we reach the limit.
2403 if (NumBonusInsts > BonusInstThreshold)
2404 return false;
2405 }
2406
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002407 // Cond is known to be a compare or binary operator. Check to make sure that
2408 // neither operand is a potentially-trapping constant expression.
2409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2410 if (CE->canTrap())
2411 return false;
2412 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2413 if (CE->canTrap())
2414 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002415
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002416 // Finally, don't infinitely unroll conditional loops.
Dehao Chenf6c00832016-05-18 19:44:21 +00002417 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002418 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002419 if (TrueDest == BB || FalseDest == BB)
2420 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002421
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002422 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2423 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002424 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002425
Chris Lattner80b03a12008-07-13 22:23:11 +00002426 // Check that we have two conditional branches. If there is a PHI node in
2427 // the common successor, verify that the same value flows in from both
2428 // blocks.
Dehao Chenf6c00832016-05-18 19:44:21 +00002429 SmallVector<PHINode *, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002430 if (!PBI || PBI->isUnconditional() ||
Dehao Chenf6c00832016-05-18 19:44:21 +00002431 (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
Manman Rend33f4ef2012-06-13 05:43:29 +00002432 (!BI->isConditional() &&
2433 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002434 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002435
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002436 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002437 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002438 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002439
Manman Rend33f4ef2012-06-13 05:43:29 +00002440 if (BI->isConditional()) {
Richard Trieu7a083812016-02-18 22:09:30 +00002441 if (PBI->getSuccessor(0) == TrueDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002442 Opc = Instruction::Or;
Richard Trieu7a083812016-02-18 22:09:30 +00002443 } else if (PBI->getSuccessor(1) == FalseDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002444 Opc = Instruction::And;
Richard Trieu7a083812016-02-18 22:09:30 +00002445 } else if (PBI->getSuccessor(0) == FalseDest) {
2446 Opc = Instruction::And;
2447 InvertPredCond = true;
2448 } else if (PBI->getSuccessor(1) == TrueDest) {
2449 Opc = Instruction::Or;
2450 InvertPredCond = true;
2451 } else {
Manman Rend33f4ef2012-06-13 05:43:29 +00002452 continue;
Richard Trieu7a083812016-02-18 22:09:30 +00002453 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002454 } else {
2455 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2456 continue;
2457 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002458
David Greene725c7c32010-01-05 01:26:52 +00002459 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002460 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002461
Chris Lattner55eaae12008-07-13 21:20:19 +00002462 // If we need to invert the condition in the pred block to match, do so now.
2463 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002464 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002465
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002466 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2467 CmpInst *CI = cast<CmpInst>(NewCond);
2468 CI->setPredicate(CI->getInversePredicate());
2469 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00002470 NewCond =
2471 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002472 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002473
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002474 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002475 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002476 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002477
Jingyue Wufc029672014-09-30 22:23:38 +00002478 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002479 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002480 // bonus instructions to a predecessor block.
2481 ValueToValueMapTy VMap; // maps original values to cloned values
2482 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002483 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002484 // instructions.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002485 for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
Jingyue Wufc029672014-09-30 22:23:38 +00002486 if (isa<DbgInfoIntrinsic>(BonusInst))
2487 continue;
2488 Instruction *NewBonusInst = BonusInst->clone();
2489 RemapInstruction(NewBonusInst, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00002490 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002491 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002492
2493 // If we moved a load, we cannot any longer claim any knowledge about
2494 // its potential value. The previous information might have been valid
2495 // only given the branch precondition.
2496 // For an analogous reason, we must also drop all the metadata whose
2497 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002498 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002499
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002500 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2501 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002502 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002503 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002504
Chris Lattner55eaae12008-07-13 21:20:19 +00002505 // Clone Cond into the predecessor basic block, and or/and the
2506 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002507 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002508 RemapInstruction(New, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00002509 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002510 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002511 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002512 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002513
Manman Rend33f4ef2012-06-13 05:43:29 +00002514 if (BI->isConditional()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002515 Instruction *NewCond = cast<Instruction>(
2516 Builder.CreateBinOp(Opc, PBI->getCondition(), New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002517 PBI->setCondition(NewCond);
2518
Manman Renbfb9d432012-09-15 00:39:57 +00002519 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Dehao Chenf16376b2016-05-18 22:41:03 +00002520 bool HasWeights =
2521 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
2522 SuccTrueWeight, SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002523 SmallVector<uint64_t, 8> NewWeights;
2524
Manman Rend33f4ef2012-06-13 05:43:29 +00002525 if (PBI->getSuccessor(0) == BB) {
Dehao Chenf16376b2016-05-18 22:41:03 +00002526 if (HasWeights) {
Manman Renbfb9d432012-09-15 00:39:57 +00002527 // PBI: br i1 %x, BB, FalseDest
2528 // BI: br i1 %y, TrueDest, FalseDest
Dehao Chenf6c00832016-05-18 19:44:21 +00002529 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
Manman Renbfb9d432012-09-15 00:39:57 +00002530 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
Dehao Chenf6c00832016-05-18 19:44:21 +00002531 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
Manman Renbfb9d432012-09-15 00:39:57 +00002532 // TrueWeight for PBI * FalseWeight for BI.
2533 // We assume that total weights of a BranchInst can fit into 32 bits.
2534 // Therefore, we will not have overflow using 64-bit arithmetic.
Dehao Chenf6c00832016-05-18 19:44:21 +00002535 NewWeights.push_back(PredFalseWeight *
2536 (SuccFalseWeight + SuccTrueWeight) +
2537 PredTrueWeight * SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002538 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002539 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2540 PBI->setSuccessor(0, TrueDest);
2541 }
2542 if (PBI->getSuccessor(1) == BB) {
Dehao Chenf16376b2016-05-18 22:41:03 +00002543 if (HasWeights) {
Manman Renbfb9d432012-09-15 00:39:57 +00002544 // PBI: br i1 %x, TrueDest, BB
2545 // BI: br i1 %y, TrueDest, FalseDest
Dehao Chenf6c00832016-05-18 19:44:21 +00002546 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
Manman Renbfb9d432012-09-15 00:39:57 +00002547 // FalseWeight for PBI * TrueWeight for BI.
Dehao Chenf6c00832016-05-18 19:44:21 +00002548 NewWeights.push_back(PredTrueWeight *
2549 (SuccFalseWeight + SuccTrueWeight) +
2550 PredFalseWeight * SuccTrueWeight);
2551 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
Manman Renbfb9d432012-09-15 00:39:57 +00002552 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2553 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002554 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2555 PBI->setSuccessor(1, FalseDest);
2556 }
Manman Renbfb9d432012-09-15 00:39:57 +00002557 if (NewWeights.size() == 2) {
2558 // Halve the weights if any of them cannot fit in an uint32_t
2559 FitWeights(NewWeights);
2560
Dehao Chenf6c00832016-05-18 19:44:21 +00002561 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
2562 NewWeights.end());
2563 PBI->setMetadata(
2564 LLVMContext::MD_prof,
2565 MDBuilder(BI->getContext()).createBranchWeights(MDWeights));
Manman Renbfb9d432012-09-15 00:39:57 +00002566 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002567 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002568 } else {
2569 // Update PHI nodes in the common successors.
2570 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002571 ConstantInt *PBI_C = cast<ConstantInt>(
Dehao Chenf6c00832016-05-18 19:44:21 +00002572 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
Manman Rend33f4ef2012-06-13 05:43:29 +00002573 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002574 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002575 if (PBI->getSuccessor(0) == TrueDest) {
2576 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2577 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2578 // is false: !PBI_Cond and BI_Value
Dehao Chenf6c00832016-05-18 19:44:21 +00002579 Instruction *NotCond = cast<Instruction>(
2580 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2581 MergedCond = cast<Instruction>(
2582 Builder.CreateBinOp(Instruction::And, NotCond, New, "and.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002583 if (PBI_C->isOne())
Dehao Chenf6c00832016-05-18 19:44:21 +00002584 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2585 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002586 } else {
2587 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2588 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2589 // is false: PBI_Cond and BI_Value
Dehao Chenf6c00832016-05-18 19:44:21 +00002590 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2591 Instruction::And, PBI->getCondition(), New, "and.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002592 if (PBI_C->isOne()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002593 Instruction *NotCond = cast<Instruction>(
2594 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2595 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2596 Instruction::Or, NotCond, MergedCond, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002597 }
2598 }
2599 // Update PHI Node.
2600 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2601 MergedCond);
2602 }
2603 // Change PBI from Conditional to Unconditional.
2604 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2605 EraseTerminatorInstAndDCECond(PBI);
2606 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002607 }
Devang Pateld715ec82011-04-06 22:37:20 +00002608
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002609 // TODO: If BB is reachable from all paths through PredBlock, then we
2610 // could replace PBI's branch probabilities with BI's.
2611
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002612 // Copy any debug value intrinsics into the end of PredBlock.
Benjamin Kramer135f7352016-06-26 12:28:59 +00002613 for (Instruction &I : *BB)
2614 if (isa<DbgInfoIntrinsic>(I))
2615 I.clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002616
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002617 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002618 }
2619 return false;
2620}
2621
James Molloy4de84dd2015-11-04 15:28:04 +00002622// If there is only one store in BB1 and BB2, return it, otherwise return
2623// nullptr.
2624static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2625 StoreInst *S = nullptr;
2626 for (auto *BB : {BB1, BB2}) {
2627 if (!BB)
2628 continue;
2629 for (auto &I : *BB)
2630 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2631 if (S)
2632 // Multiple stores seen.
2633 return nullptr;
2634 else
2635 S = SI;
2636 }
2637 }
2638 return S;
2639}
2640
2641static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2642 Value *AlternativeV = nullptr) {
2643 // PHI is going to be a PHI node that allows the value V that is defined in
2644 // BB to be referenced in BB's only successor.
2645 //
2646 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2647 // doesn't matter to us what the other operand is (it'll never get used). We
2648 // could just create a new PHI with an undef incoming value, but that could
2649 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2650 // other PHI. So here we directly look for some PHI in BB's successor with V
2651 // as an incoming operand. If we find one, we use it, else we create a new
2652 // one.
2653 //
2654 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2655 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2656 // where OtherBB is the single other predecessor of BB's only successor.
2657 PHINode *PHI = nullptr;
2658 BasicBlock *Succ = BB->getSingleSuccessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00002659
James Molloy4de84dd2015-11-04 15:28:04 +00002660 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2661 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2662 PHI = cast<PHINode>(I);
2663 if (!AlternativeV)
2664 break;
2665
2666 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2667 auto PredI = pred_begin(Succ);
2668 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2669 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2670 break;
2671 PHI = nullptr;
2672 }
2673 if (PHI)
2674 return PHI;
2675
James Molloy3d21dcf2015-12-16 14:12:44 +00002676 // If V is not an instruction defined in BB, just return it.
2677 if (!AlternativeV &&
2678 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2679 return V;
2680
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002681 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
James Molloy4de84dd2015-11-04 15:28:04 +00002682 PHI->addIncoming(V, BB);
2683 for (BasicBlock *PredBB : predecessors(Succ))
2684 if (PredBB != BB)
Dehao Chenf6c00832016-05-18 19:44:21 +00002685 PHI->addIncoming(
2686 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
James Molloy4de84dd2015-11-04 15:28:04 +00002687 return PHI;
2688}
2689
2690static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2691 BasicBlock *QTB, BasicBlock *QFB,
2692 BasicBlock *PostBB, Value *Address,
2693 bool InvertPCond, bool InvertQCond) {
2694 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2695 return Operator::getOpcode(&I) == Instruction::BitCast &&
2696 I.getType()->isPointerTy();
2697 };
2698
2699 // If we're not in aggressive mode, we only optimize if we have some
2700 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2701 auto IsWorthwhile = [&](BasicBlock *BB) {
2702 if (!BB)
2703 return true;
2704 // Heuristic: if the block can be if-converted/phi-folded and the
2705 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2706 // thread this store.
James Molloy9e959ac2015-11-05 08:40:19 +00002707 unsigned N = 0;
2708 for (auto &I : *BB) {
2709 // Cheap instructions viable for folding.
2710 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2711 isa<StoreInst>(I))
2712 ++N;
2713 // Free instructions.
2714 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2715 IsaBitcastOfPointerType(I))
2716 continue;
2717 else
James Molloy4de84dd2015-11-04 15:28:04 +00002718 return false;
James Molloy9e959ac2015-11-05 08:40:19 +00002719 }
2720 return N <= PHINodeFoldingThreshold;
James Molloy4de84dd2015-11-04 15:28:04 +00002721 };
2722
Dehao Chenf6c00832016-05-18 19:44:21 +00002723 if (!MergeCondStoresAggressively &&
2724 (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
2725 !IsWorthwhile(QFB)))
James Molloy4de84dd2015-11-04 15:28:04 +00002726 return false;
2727
2728 // For every pointer, there must be exactly two stores, one coming from
2729 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2730 // store (to any address) in PTB,PFB or QTB,QFB.
2731 // FIXME: We could relax this restriction with a bit more work and performance
2732 // testing.
2733 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2734 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2735 if (!PStore || !QStore)
2736 return false;
2737
2738 // Now check the stores are compatible.
2739 if (!QStore->isUnordered() || !PStore->isUnordered())
2740 return false;
2741
2742 // Check that sinking the store won't cause program behavior changes. Sinking
2743 // the store out of the Q blocks won't change any behavior as we're sinking
2744 // from a block to its unconditional successor. But we're moving a store from
2745 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2746 // So we need to check that there are no aliasing loads or stores in
2747 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2748 // operations between PStore and the end of its parent block.
2749 //
2750 // The ideal way to do this is to query AliasAnalysis, but we don't
2751 // preserve AA currently so that is dangerous. Be super safe and just
2752 // check there are no other memory operations at all.
2753 for (auto &I : *QFB->getSinglePredecessor())
2754 if (I.mayReadOrWriteMemory())
2755 return false;
2756 for (auto &I : *QFB)
2757 if (&I != QStore && I.mayReadOrWriteMemory())
2758 return false;
2759 if (QTB)
2760 for (auto &I : *QTB)
2761 if (&I != QStore && I.mayReadOrWriteMemory())
2762 return false;
2763 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2764 I != E; ++I)
2765 if (&*I != PStore && I->mayReadOrWriteMemory())
2766 return false;
2767
2768 // OK, we're going to sink the stores to PostBB. The store has to be
2769 // conditional though, so first create the predicate.
2770 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2771 ->getCondition();
2772 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2773 ->getCondition();
2774
2775 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2776 PStore->getParent());
2777 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2778 QStore->getParent(), PPHI);
2779
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002780 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2781
James Molloy4de84dd2015-11-04 15:28:04 +00002782 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2783 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2784
2785 if (InvertPCond)
2786 PPred = QB.CreateNot(PPred);
2787 if (InvertQCond)
2788 QPred = QB.CreateNot(QPred);
2789 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2790
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002791 auto *T =
2792 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
James Molloy4de84dd2015-11-04 15:28:04 +00002793 QB.SetInsertPoint(T);
2794 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2795 AAMDNodes AAMD;
2796 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2797 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2798 SI->setAAMetadata(AAMD);
2799
2800 QStore->eraseFromParent();
2801 PStore->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00002802
James Molloy4de84dd2015-11-04 15:28:04 +00002803 return true;
2804}
2805
2806static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) {
2807 // The intention here is to find diamonds or triangles (see below) where each
2808 // conditional block contains a store to the same address. Both of these
2809 // stores are conditional, so they can't be unconditionally sunk. But it may
2810 // be profitable to speculatively sink the stores into one merged store at the
2811 // end, and predicate the merged store on the union of the two conditions of
2812 // PBI and QBI.
2813 //
2814 // This can reduce the number of stores executed if both of the conditions are
2815 // true, and can allow the blocks to become small enough to be if-converted.
2816 // This optimization will also chain, so that ladders of test-and-set
2817 // sequences can be if-converted away.
2818 //
2819 // We only deal with simple diamonds or triangles:
2820 //
2821 // PBI or PBI or a combination of the two
2822 // / \ | \
2823 // PTB PFB | PFB
2824 // \ / | /
2825 // QBI QBI
2826 // / \ | \
2827 // QTB QFB | QFB
2828 // \ / | /
2829 // PostBB PostBB
2830 //
2831 // We model triangles as a type of diamond with a nullptr "true" block.
2832 // Triangles are canonicalized so that the fallthrough edge is represented by
2833 // a true condition, as in the diagram above.
Dehao Chenf6c00832016-05-18 19:44:21 +00002834 //
James Molloy4de84dd2015-11-04 15:28:04 +00002835 BasicBlock *PTB = PBI->getSuccessor(0);
2836 BasicBlock *PFB = PBI->getSuccessor(1);
2837 BasicBlock *QTB = QBI->getSuccessor(0);
2838 BasicBlock *QFB = QBI->getSuccessor(1);
2839 BasicBlock *PostBB = QFB->getSingleSuccessor();
2840
2841 bool InvertPCond = false, InvertQCond = false;
2842 // Canonicalize fallthroughs to the true branches.
2843 if (PFB == QBI->getParent()) {
2844 std::swap(PFB, PTB);
2845 InvertPCond = true;
2846 }
2847 if (QFB == PostBB) {
2848 std::swap(QFB, QTB);
2849 InvertQCond = true;
2850 }
2851
2852 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
2853 // and QFB may not. Model fallthroughs as a nullptr block.
2854 if (PTB == QBI->getParent())
2855 PTB = nullptr;
2856 if (QTB == PostBB)
2857 QTB = nullptr;
2858
2859 // Legality bailouts. We must have at least the non-fallthrough blocks and
2860 // the post-dominating block, and the non-fallthroughs must only have one
2861 // predecessor.
2862 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002863 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
James Molloy4de84dd2015-11-04 15:28:04 +00002864 };
2865 if (!PostBB ||
2866 !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
2867 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
2868 return false;
2869 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
2870 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
2871 return false;
2872 if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2)
2873 return false;
2874
2875 // OK, this is a sequence of two diamonds or triangles.
2876 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
Dehao Chenf6c00832016-05-18 19:44:21 +00002877 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
James Molloy4de84dd2015-11-04 15:28:04 +00002878 for (auto *BB : {PTB, PFB}) {
2879 if (!BB)
2880 continue;
2881 for (auto &I : *BB)
2882 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2883 PStoreAddresses.insert(SI->getPointerOperand());
2884 }
2885 for (auto *BB : {QTB, QFB}) {
2886 if (!BB)
2887 continue;
2888 for (auto &I : *BB)
2889 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2890 QStoreAddresses.insert(SI->getPointerOperand());
2891 }
Dehao Chenf6c00832016-05-18 19:44:21 +00002892
James Molloy4de84dd2015-11-04 15:28:04 +00002893 set_intersect(PStoreAddresses, QStoreAddresses);
2894 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
2895 // clear what it contains.
2896 auto &CommonAddresses = PStoreAddresses;
2897
2898 bool Changed = false;
2899 for (auto *Address : CommonAddresses)
2900 Changed |= mergeConditionalStoreToAddress(
2901 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond);
2902 return Changed;
2903}
2904
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002905/// If we have a conditional branch as a predecessor of another block,
2906/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00002907/// that PBI and BI are both conditional branches, and BI is in one of the
2908/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00002909static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
2910 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00002911 assert(PBI->isConditional() && BI->isConditional());
2912 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002913
Chris Lattner9aada1d2008-07-13 21:53:26 +00002914 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002915 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002916 // this conditional branch redundant.
2917 if (PBI->getCondition() == BI->getCondition() &&
2918 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2919 // Okay, the outcome of this conditional branch is statically
2920 // knowable. If this block had a single pred, handle specially.
2921 if (BB->getSinglePredecessor()) {
2922 // Turn this into a branch on constant.
2923 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Dehao Chenf6c00832016-05-18 19:44:21 +00002924 BI->setCondition(
2925 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
2926 return true; // Nuke the branch on constant.
Chris Lattner9aada1d2008-07-13 21:53:26 +00002927 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002928
Chris Lattner9aada1d2008-07-13 21:53:26 +00002929 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2930 // in the constant and simplify the block result. Subsequent passes of
2931 // simplifycfg will thread the block.
2932 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002933 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002934 PHINode *NewPN = PHINode::Create(
2935 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
2936 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00002937 // Okay, we're going to insert the PHI node. Since PBI is not the only
2938 // predecessor, compute the PHI'd conditional value for all of the preds.
2939 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002940 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002941 BasicBlock *P = *PI;
Dehao Chenf6c00832016-05-18 19:44:21 +00002942 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
2943 PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002944 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2945 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Dehao Chenf6c00832016-05-18 19:44:21 +00002946 NewPN->addIncoming(
2947 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
2948 P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002949 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002950 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002951 }
Gabor Greif8629f122010-07-12 10:59:23 +00002952 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002953
Chris Lattner9aada1d2008-07-13 21:53:26 +00002954 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002955 return true;
2956 }
2957 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002958
Philip Reamesb42db212015-10-14 22:46:19 +00002959 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2960 if (CE->canTrap())
2961 return false;
2962
James Molloy4de84dd2015-11-04 15:28:04 +00002963 // If both branches are conditional and both contain stores to the same
2964 // address, remove the stores from the conditionals and create a conditional
2965 // merged store at the end.
2966 if (MergeCondStores && mergeConditionalStores(PBI, BI))
2967 return true;
2968
Chris Lattner9aada1d2008-07-13 21:53:26 +00002969 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002970 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002971 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002972 BasicBlock::iterator BBI = BB->begin();
2973 // Ignore dbg intrinsics.
2974 while (isa<DbgInfoIntrinsic>(BBI))
2975 ++BBI;
2976 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002977 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002978
Chris Lattner834ab4e2008-07-13 22:04:41 +00002979 int PBIOp, BIOp;
Richard Trieu7a083812016-02-18 22:09:30 +00002980 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
2981 PBIOp = 0;
2982 BIOp = 0;
2983 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
2984 PBIOp = 0;
2985 BIOp = 1;
2986 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
2987 PBIOp = 1;
2988 BIOp = 0;
2989 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
2990 PBIOp = 1;
2991 BIOp = 1;
2992 } else {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002993 return false;
Richard Trieu7a083812016-02-18 22:09:30 +00002994 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002995
Chris Lattner834ab4e2008-07-13 22:04:41 +00002996 // Check to make sure that the other destination of this branch
2997 // isn't BB itself. If so, this is an infinite loop that will
2998 // keep getting unwound.
2999 if (PBI->getSuccessor(PBIOp) == BB)
3000 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003001
3002 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00003003 // insertion of a large number of select instructions. For targets
3004 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003005
Sanjay Patela932da82014-07-07 21:19:00 +00003006 // Also do not perform this transformation if any phi node in the common
3007 // destination block can trap when reached by BB or PBB (PR17073). In that
3008 // case, it would be unsafe to hoist the operation into a select instruction.
3009
3010 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00003011 unsigned NumPhis = 0;
Dehao Chenf6c00832016-05-18 19:44:21 +00003012 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
3013 ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00003014 if (NumPhis > 2) // Disable this xform.
3015 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003016
Sanjay Patela932da82014-07-07 21:19:00 +00003017 PHINode *PN = cast<PHINode>(II);
3018 Value *BIV = PN->getIncomingValueForBlock(BB);
3019 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
3020 if (CE->canTrap())
3021 return false;
3022
3023 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3024 Value *PBIV = PN->getIncomingValue(PBBIdx);
3025 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
3026 if (CE->canTrap())
3027 return false;
3028 }
3029
Chris Lattner834ab4e2008-07-13 22:04:41 +00003030 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00003031 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003032
David Greene725c7c32010-01-05 01:26:52 +00003033 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00003034 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003035
Chris Lattner80b03a12008-07-13 22:23:11 +00003036 // If OtherDest *is* BB, then BB is a basic block with a single conditional
3037 // branch in it, where one edge (OtherDest) goes back to itself but the other
3038 // exits. We don't *know* that the program avoids the infinite loop
3039 // (even though that seems likely). If we do this xform naively, we'll end up
3040 // recursively unpeeling the loop. Since we know that (after the xform is
3041 // done) that the block *is* infinite if reached, we just make it an obviously
3042 // infinite loop with no cond branch.
3043 if (OtherDest == BB) {
3044 // Insert it at the end of the function, because it's either code,
3045 // or it won't matter if it's hot. :)
Dehao Chenf6c00832016-05-18 19:44:21 +00003046 BasicBlock *InfLoopBlock =
3047 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00003048 BranchInst::Create(InfLoopBlock, InfLoopBlock);
3049 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003050 }
3051
David Greene725c7c32010-01-05 01:26:52 +00003052 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00003053
Chris Lattner834ab4e2008-07-13 22:04:41 +00003054 // BI may have other predecessors. Because of this, we leave
3055 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003056
Chris Lattner834ab4e2008-07-13 22:04:41 +00003057 // Make sure we get to CommonDest on True&True directions.
3058 Value *PBICond = PBI->getCondition();
Mehdi Aminiba9fba82016-03-13 21:05:13 +00003059 IRBuilder<NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00003060 if (PBIOp)
Dehao Chenf6c00832016-05-18 19:44:21 +00003061 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
Devang Patel1407fb42011-05-19 20:52:46 +00003062
Chris Lattner834ab4e2008-07-13 22:04:41 +00003063 Value *BICond = BI->getCondition();
3064 if (BIOp)
Dehao Chenf6c00832016-05-18 19:44:21 +00003065 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
Devang Patel1407fb42011-05-19 20:52:46 +00003066
Chris Lattner834ab4e2008-07-13 22:04:41 +00003067 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00003068 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00003069
Chris Lattner834ab4e2008-07-13 22:04:41 +00003070 // Modify PBI to branch on the new condition to the new dests.
3071 PBI->setCondition(Cond);
3072 PBI->setSuccessor(0, CommonDest);
3073 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003074
Manman Ren2d4c10f2012-09-17 21:30:40 +00003075 // Update branch weight for PBI.
3076 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Dehao Chenb76e5d92016-05-10 23:07:19 +00003077 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
Dehao Chenf16376b2016-05-18 22:41:03 +00003078 bool HasWeights =
3079 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3080 SuccTrueWeight, SuccFalseWeight);
Dehao Chenb76e5d92016-05-10 23:07:19 +00003081 if (HasWeights) {
Dehao Chenb76e5d92016-05-10 23:07:19 +00003082 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3083 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3084 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3085 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
Manman Ren2d4c10f2012-09-17 21:30:40 +00003086 // The weight to CommonDest should be PredCommon * SuccTotal +
3087 // PredOther * SuccCommon.
3088 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00003089 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3090 PredOther * SuccCommon,
3091 PredOther * SuccOther};
Sanjay Patel84a0bf62016-05-06 17:51:37 +00003092 // Halve the weights if any of them cannot fit in an uint32_t
Manman Ren2d4c10f2012-09-17 21:30:40 +00003093 FitWeights(NewWeights);
3094
Manman Ren2d4c10f2012-09-17 21:30:40 +00003095 PBI->setMetadata(LLVMContext::MD_prof,
Sanjay Patel84a0bf62016-05-06 17:51:37 +00003096 MDBuilder(BI->getContext())
3097 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00003098 }
3099
Chris Lattner834ab4e2008-07-13 22:04:41 +00003100 // OtherDest may have phi nodes. If so, add an entry from PBI's
3101 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003102 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003103
Chris Lattner834ab4e2008-07-13 22:04:41 +00003104 // We know that the CommonDest already had an edge from PBI to
3105 // it. If it has PHIs though, the PHIs may have different
3106 // entries for BB and PBI's BB. If so, insert a select to make
3107 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003108 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00003109 for (BasicBlock::iterator II = CommonDest->begin();
3110 (PN = dyn_cast<PHINode>(II)); ++II) {
3111 Value *BIV = PN->getIncomingValueForBlock(BB);
3112 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3113 Value *PBIV = PN->getIncomingValue(PBBIdx);
3114 if (BIV != PBIV) {
3115 // Insert a select in PBI to pick the right value.
Dehao Chenf6c00832016-05-18 19:44:21 +00003116 SelectInst *NV = cast<SelectInst>(
3117 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00003118 PN->setIncomingValue(PBBIdx, NV);
Sanjay Patel1cb62412016-05-06 18:07:46 +00003119 // Although the select has the same condition as PBI, the original branch
3120 // weights for PBI do not apply to the new select because the select's
3121 // 'logical' edges are incoming edges of the phi that is eliminated, not
3122 // the outgoing edges of PBI.
Dehao Chenf16376b2016-05-18 22:41:03 +00003123 if (HasWeights) {
Sanjay Patel1cb62412016-05-06 18:07:46 +00003124 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3125 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3126 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3127 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3128 // The weight to PredCommonDest should be PredCommon * SuccTotal.
3129 // The weight to PredOtherDest should be PredOther * SuccCommon.
3130 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3131 PredOther * SuccCommon};
3132
3133 FitWeights(NewWeights);
3134
3135 NV->setMetadata(LLVMContext::MD_prof,
3136 MDBuilder(BI->getContext())
3137 .createBranchWeights(NewWeights[0], NewWeights[1]));
3138 }
Chris Lattner9aada1d2008-07-13 21:53:26 +00003139 }
3140 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003141
David Greene725c7c32010-01-05 01:26:52 +00003142 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
3143 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003144
Chris Lattner834ab4e2008-07-13 22:04:41 +00003145 // This basic block is probably dead. We know it has at least
3146 // one fewer predecessor.
3147 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00003148}
3149
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003150// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
3151// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00003152// Takes care of updating the successors and removing the old terminator.
3153// Also makes sure not to introduce new successors by assuming that edges to
3154// non-successor TrueBBs and FalseBBs aren't reachable.
3155static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00003156 BasicBlock *TrueBB, BasicBlock *FalseBB,
3157 uint32_t TrueWeight,
Dehao Chenf6c00832016-05-18 19:44:21 +00003158 uint32_t FalseWeight) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003159 // Remove any superfluous successor edges from the CFG.
3160 // First, figure out which successors to preserve.
3161 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
3162 // successor.
3163 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00003164 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003165
3166 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00003167 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003168 // Make sure only to keep exactly one copy of each edge.
3169 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00003170 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003171 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00003172 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003173 else
David Majnemerdc3b67b2015-10-21 18:22:24 +00003174 Succ->removePredecessor(OldTerm->getParent(),
3175 /*DontDeleteUselessPHIs=*/true);
Frits van Bommel8e158492011-01-11 12:52:11 +00003176 }
3177
Devang Patel2c2ea222011-05-18 18:43:31 +00003178 IRBuilder<> Builder(OldTerm);
3179 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
3180
Frits van Bommel8e158492011-01-11 12:52:11 +00003181 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00003182 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003183 if (TrueBB == FalseBB)
3184 // We were only looking for one successor, and it was present.
3185 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00003186 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00003187 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00003188 // We found both of the successors we were looking for.
3189 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00003190 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
3191 if (TrueWeight != FalseWeight)
3192 NewBI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00003193 MDBuilder(OldTerm->getContext())
3194 .createBranchWeights(TrueWeight, FalseWeight));
Manman Ren774246a2012-09-17 22:28:55 +00003195 }
Frits van Bommel8e158492011-01-11 12:52:11 +00003196 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3197 // Neither of the selected blocks were successors, so this
3198 // terminator must be unreachable.
3199 new UnreachableInst(OldTerm->getContext(), OldTerm);
3200 } else {
3201 // One of the selected values was a successor, but the other wasn't.
3202 // Insert an unconditional branch to the one that was found;
3203 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00003204 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00003205 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00003206 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00003207 else
3208 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00003209 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00003210 }
3211
3212 EraseTerminatorInstAndDCECond(OldTerm);
3213 return true;
3214}
3215
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003216// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00003217// (switch (select cond, X, Y)) on constant X, Y
3218// with a branch - conditional if X and Y lead to distinct BBs,
3219// unconditional otherwise.
3220static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
3221 // Check for constant integer values in the select.
3222 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
3223 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
3224 if (!TrueVal || !FalseVal)
3225 return false;
3226
3227 // Find the relevant condition and destinations.
3228 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003229 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
3230 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00003231
Manman Ren774246a2012-09-17 22:28:55 +00003232 // Get weight for TrueBB and FalseBB.
3233 uint32_t TrueWeight = 0, FalseWeight = 0;
3234 SmallVector<uint64_t, 8> Weights;
3235 bool HasWeights = HasBranchWeights(SI);
3236 if (HasWeights) {
3237 GetBranchWeights(SI, Weights);
3238 if (Weights.size() == 1 + SI->getNumCases()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00003239 TrueWeight =
3240 (uint32_t)Weights[SI->findCaseValue(TrueVal).getSuccessorIndex()];
3241 FalseWeight =
3242 (uint32_t)Weights[SI->findCaseValue(FalseVal).getSuccessorIndex()];
Manman Ren774246a2012-09-17 22:28:55 +00003243 }
3244 }
3245
Frits van Bommel8ae07992011-02-28 09:44:07 +00003246 // Perform the actual simplification.
Dehao Chenf6c00832016-05-18 19:44:21 +00003247 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
3248 FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00003249}
3250
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003251// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003252// (indirectbr (select cond, blockaddress(@fn, BlockA),
3253// blockaddress(@fn, BlockB)))
3254// with
3255// (br cond, BlockA, BlockB).
3256static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
3257 // Check that both operands of the select are block addresses.
3258 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3259 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3260 if (!TBA || !FBA)
3261 return false;
3262
3263 // Extract the actual blocks.
3264 BasicBlock *TrueBB = TBA->getBasicBlock();
3265 BasicBlock *FalseBB = FBA->getBasicBlock();
3266
Frits van Bommel8e158492011-01-11 12:52:11 +00003267 // Perform the actual simplification.
Dehao Chenf6c00832016-05-18 19:44:21 +00003268 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
3269 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003270}
3271
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003272/// This is called when we find an icmp instruction
3273/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003274/// block that ends with an uncond branch. We are looking for a very specific
3275/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3276/// this case, we merge the first two "or's of icmp" into a switch, but then the
3277/// default value goes to an uncond block with a seteq in it, we get something
3278/// like:
3279///
3280/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3281/// DEFAULT:
3282/// %tmp = icmp eq i8 %A, 92
3283/// br label %end
3284/// end:
3285/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00003286///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003287/// We prefer to split the edge to 'end' so that there is a true/false entry to
3288/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003289static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003290 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
3291 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
3292 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003293 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00003294
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003295 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3296 // complex.
Dehao Chenf6c00832016-05-18 19:44:21 +00003297 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
3298 return false;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003299
3300 Value *V = ICI->getOperand(0);
3301 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00003302
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003303 // The pattern we're looking for is where our only predecessor is a switch on
3304 // 'V' and this block is the default case for the switch. In this case we can
3305 // fold the compared value into the switch to simplify things.
3306 BasicBlock *Pred = BB->getSinglePredecessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00003307 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3308 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003309
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003310 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3311 if (SI->getCondition() != V)
3312 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003313
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003314 // If BB is reachable on a non-default case, then we simply know the value of
3315 // V in this block. Substitute it and constant fold the icmp instruction
3316 // away.
3317 if (SI->getDefaultDest() != BB) {
3318 ConstantInt *VVal = SI->findCaseDest(BB);
3319 assert(VVal && "Should have a unique destination value");
3320 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003321
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003322 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00003323 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003324 ICI->eraseFromParent();
3325 }
3326 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003327 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003328 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003329
Chris Lattner62cc76e2010-12-13 03:43:57 +00003330 // Ok, the block is reachable from the default dest. If the constant we're
3331 // comparing exists in one of the other edges, then we can constant fold ICI
3332 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003333 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00003334 Value *V;
3335 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3336 V = ConstantInt::getFalse(BB->getContext());
3337 else
3338 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003339
Chris Lattner62cc76e2010-12-13 03:43:57 +00003340 ICI->replaceAllUsesWith(V);
3341 ICI->eraseFromParent();
3342 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003343 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00003344 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003345
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003346 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3347 // the block.
3348 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003349 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00003350 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003351 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3352 return false;
3353
3354 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3355 // true in the PHI.
3356 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
Dehao Chenf6c00832016-05-18 19:44:21 +00003357 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003358
3359 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3360 std::swap(DefaultCst, NewCst);
3361
3362 // Replace ICI (which is used by the PHI for the default value) with true or
3363 // false depending on if it is EQ or NE.
3364 ICI->replaceAllUsesWith(DefaultCst);
3365 ICI->eraseFromParent();
3366
3367 // Okay, the switch goes to this block on a default value. Add an edge from
3368 // the switch to the merge point on the compared value.
Dehao Chenf6c00832016-05-18 19:44:21 +00003369 BasicBlock *NewBB =
3370 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00003371 SmallVector<uint64_t, 8> Weights;
3372 bool HasWeights = HasBranchWeights(SI);
3373 if (HasWeights) {
3374 GetBranchWeights(SI, Weights);
3375 if (Weights.size() == 1 + SI->getNumCases()) {
3376 // Split weight for default case to case for "Cst".
Dehao Chenf6c00832016-05-18 19:44:21 +00003377 Weights[0] = (Weights[0] + 1) >> 1;
Manman Rence48ea72012-09-17 23:07:43 +00003378 Weights.push_back(Weights[0]);
3379
3380 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
Dehao Chenf6c00832016-05-18 19:44:21 +00003381 SI->setMetadata(
3382 LLVMContext::MD_prof,
3383 MDBuilder(SI->getContext()).createBranchWeights(MDWeights));
Manman Rence48ea72012-09-17 23:07:43 +00003384 }
3385 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003386 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003387
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003388 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00003389 Builder.SetInsertPoint(NewBB);
3390 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3391 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003392 PHIUse->addIncoming(NewCst, NewBB);
3393 return true;
3394}
3395
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003396/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003397/// Check to see if it is branching on an or/and chain of icmp instructions, and
3398/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003399static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3400 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003401 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Dehao Chenf6c00832016-05-18 19:44:21 +00003402 if (!Cond)
3403 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003404
Chris Lattnera69c4432010-12-13 05:03:41 +00003405 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3406 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3407 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003408
Mehdi Amini9a25cb82014-11-19 20:09:11 +00003409 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00003410 ConstantComparesGatherer ConstantCompare(Cond, DL);
3411 // Unpack the result
Dehao Chenf6c00832016-05-18 19:44:21 +00003412 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
Mehdi Aminiffd01002014-11-20 22:40:25 +00003413 Value *CompVal = ConstantCompare.CompValue;
3414 unsigned UsedICmps = ConstantCompare.UsedICmps;
3415 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003416
Chris Lattnera69c4432010-12-13 05:03:41 +00003417 // If we didn't have a multiply compared value, fail.
Dehao Chenf6c00832016-05-18 19:44:21 +00003418 if (!CompVal)
3419 return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00003420
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003421 // Avoid turning single icmps into a switch.
3422 if (UsedICmps <= 1)
3423 return false;
3424
Mehdi Aminiffd01002014-11-20 22:40:25 +00003425 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3426
Chris Lattnera69c4432010-12-13 05:03:41 +00003427 // There might be duplicate constants in the list, which the switch
3428 // instruction can't handle, remove them now.
3429 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3430 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003431
Chris Lattnera69c4432010-12-13 05:03:41 +00003432 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00003433 // transformation. A switch with one value is just a conditional branch.
Dehao Chenf6c00832016-05-18 19:44:21 +00003434 if (ExtraCase && Values.size() < 2)
3435 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003436
Andrew Trick3051aa12012-08-29 21:46:38 +00003437 // TODO: Preserve branch weight metadata, similarly to how
3438 // FoldValueComparisonIntoPredecessors preserves it.
3439
Chris Lattnera69c4432010-12-13 05:03:41 +00003440 // Figure out which block is which destination.
3441 BasicBlock *DefaultBB = BI->getSuccessor(1);
Dehao Chenf6c00832016-05-18 19:44:21 +00003442 BasicBlock *EdgeBB = BI->getSuccessor(0);
3443 if (!TrueWhenEqual)
3444 std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003445
Chris Lattnera69c4432010-12-13 05:03:41 +00003446 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003447
Chris Lattnerd7beca32010-12-14 06:17:25 +00003448 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Dehao Chenf6c00832016-05-18 19:44:21 +00003449 << " cases into SWITCH. BB is:\n"
3450 << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003451
Chris Lattnera69c4432010-12-13 05:03:41 +00003452 // If there are any extra values that couldn't be folded into the switch
3453 // then we evaluate them with an explicit branch first. Split the block
3454 // right before the condbr to handle it.
3455 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003456 BasicBlock *NewBB =
3457 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00003458 // Remove the uncond branch added to the old block.
3459 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00003460 Builder.SetInsertPoint(OldTI);
3461
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003462 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00003463 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003464 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00003465 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003466
Chris Lattnera69c4432010-12-13 05:03:41 +00003467 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003468
Chris Lattnercb570f82010-12-13 05:34:18 +00003469 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3470 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003471 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003472
Chris Lattnerd7beca32010-12-14 06:17:25 +00003473 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
Dehao Chenf6c00832016-05-18 19:44:21 +00003474 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00003475 BB = NewBB;
3476 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00003477
3478 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00003479 // Convert pointer to int before we switch.
3480 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003481 CompVal = Builder.CreatePtrToInt(
3482 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00003483 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003484
Chris Lattnera69c4432010-12-13 05:03:41 +00003485 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00003486 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00003487
Chris Lattnera69c4432010-12-13 05:03:41 +00003488 // Add all of the 'cases' to the switch instruction.
3489 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3490 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003491
Chris Lattnera69c4432010-12-13 05:03:41 +00003492 // We added edges from PI to the EdgeBB. As such, if there were any
3493 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3494 // the number of edges added.
Dehao Chenf6c00832016-05-18 19:44:21 +00003495 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003496 PHINode *PN = cast<PHINode>(BBI);
3497 Value *InVal = PN->getIncomingValueForBlock(BB);
Dehao Chenf6c00832016-05-18 19:44:21 +00003498 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
Chris Lattnera69c4432010-12-13 05:03:41 +00003499 PN->addIncoming(InVal, BB);
3500 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003501
Chris Lattnera69c4432010-12-13 05:03:41 +00003502 // Erase the old branch instruction.
3503 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003504
Chris Lattnerd7beca32010-12-14 06:17:25 +00003505 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00003506 return true;
3507}
3508
Duncan Sands29192d02011-09-05 12:57:57 +00003509bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
Chen Li1689c2f2016-01-10 05:48:01 +00003510 if (isa<PHINode>(RI->getValue()))
3511 return SimplifyCommonResume(RI);
3512 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3513 RI->getValue() == RI->getParent()->getFirstNonPHI())
3514 // The resume must unwind the exception that caused control to branch here.
3515 return SimplifySingleResume(RI);
Chen Li509ff212016-01-11 19:20:53 +00003516
3517 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003518}
3519
3520// Simplify resume that is shared by several landing pads (phi of landing pad).
3521bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3522 BasicBlock *BB = RI->getParent();
3523
3524 // Check that there are no other instructions except for debug intrinsics
3525 // between the phi of landing pads (RI->getValue()) and resume instruction.
3526 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
Dehao Chenf6c00832016-05-18 19:44:21 +00003527 E = RI->getIterator();
Chen Li1689c2f2016-01-10 05:48:01 +00003528 while (++I != E)
3529 if (!isa<DbgInfoIntrinsic>(I))
3530 return false;
3531
3532 SmallSet<BasicBlock *, 4> TrivialUnwindBlocks;
3533 auto *PhiLPInst = cast<PHINode>(RI->getValue());
3534
3535 // Check incoming blocks to see if any of them are trivial.
Dehao Chenf6c00832016-05-18 19:44:21 +00003536 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
3537 Idx++) {
Chen Li1689c2f2016-01-10 05:48:01 +00003538 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3539 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3540
3541 // If the block has other successors, we can not delete it because
3542 // it has other dependents.
3543 if (IncomingBB->getUniqueSuccessor() != BB)
3544 continue;
3545
Dehao Chenf6c00832016-05-18 19:44:21 +00003546 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
Chen Li1689c2f2016-01-10 05:48:01 +00003547 // Not the landing pad that caused the control to branch here.
3548 if (IncomingValue != LandingPad)
3549 continue;
3550
3551 bool isTrivial = true;
3552
3553 I = IncomingBB->getFirstNonPHI()->getIterator();
3554 E = IncomingBB->getTerminator()->getIterator();
3555 while (++I != E)
3556 if (!isa<DbgInfoIntrinsic>(I)) {
3557 isTrivial = false;
3558 break;
3559 }
3560
3561 if (isTrivial)
3562 TrivialUnwindBlocks.insert(IncomingBB);
3563 }
3564
3565 // If no trivial unwind blocks, don't do any simplifications.
Dehao Chenf6c00832016-05-18 19:44:21 +00003566 if (TrivialUnwindBlocks.empty())
3567 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003568
3569 // Turn all invokes that unwind here into calls.
3570 for (auto *TrivialBB : TrivialUnwindBlocks) {
3571 // Blocks that will be simplified should be removed from the phi node.
3572 // Note there could be multiple edges to the resume block, and we need
3573 // to remove them all.
3574 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3575 BB->removePredecessor(TrivialBB, true);
3576
3577 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3578 PI != PE;) {
3579 BasicBlock *Pred = *PI++;
3580 removeUnwindEdge(Pred);
3581 }
3582
3583 // In each SimplifyCFG run, only the current processed block can be erased.
3584 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3585 // of erasing TrivialBB, we only remove the branch to the common resume
3586 // block so that we can later erase the resume block since it has no
3587 // predecessors.
3588 TrivialBB->getTerminator()->eraseFromParent();
3589 new UnreachableInst(RI->getContext(), TrivialBB);
3590 }
3591
3592 // Delete the resume block if all its predecessors have been removed.
3593 if (pred_empty(BB))
3594 BB->eraseFromParent();
3595
3596 return !TrivialUnwindBlocks.empty();
3597}
3598
3599// Simplify resume that is only used by a single (non-phi) landing pad.
3600bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
Duncan Sands29192d02011-09-05 12:57:57 +00003601 BasicBlock *BB = RI->getParent();
3602 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
Dehao Chenf6c00832016-05-18 19:44:21 +00003603 assert(RI->getValue() == LPInst &&
3604 "Resume must unwind the exception that caused control to here");
Duncan Sands29192d02011-09-05 12:57:57 +00003605
Chen Li7009cd32015-10-23 21:13:01 +00003606 // Check that there are no other instructions except for debug intrinsics.
3607 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
Duncan Sands29192d02011-09-05 12:57:57 +00003608 while (++I != E)
3609 if (!isa<DbgInfoIntrinsic>(I))
3610 return false;
3611
Chen Lic6e28782015-10-22 20:48:38 +00003612 // Turn all invokes that unwind here into calls and delete the basic block.
Chen Li7009cd32015-10-23 21:13:01 +00003613 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3614 BasicBlock *Pred = *PI++;
3615 removeUnwindEdge(Pred);
Chen Lic6e28782015-10-22 20:48:38 +00003616 }
3617
Chen Li7009cd32015-10-23 21:13:01 +00003618 // The landingpad is now unreachable. Zap it.
3619 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00003620 if (LoopHeaders)
3621 LoopHeaders->erase(BB);
Chen Li7009cd32015-10-23 21:13:01 +00003622 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00003623}
3624
David Majnemer1efa23d2016-02-20 01:07:45 +00003625static bool removeEmptyCleanup(CleanupReturnInst *RI) {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003626 // If this is a trivial cleanup pad that executes no instructions, it can be
3627 // eliminated. If the cleanup pad continues to the caller, any predecessor
3628 // that is an EH pad will be updated to continue to the caller and any
3629 // predecessor that terminates with an invoke instruction will have its invoke
3630 // instruction converted to a call instruction. If the cleanup pad being
3631 // simplified does not continue to the caller, each predecessor will be
3632 // updated to continue to the unwind destination of the cleanup pad being
3633 // simplified.
3634 BasicBlock *BB = RI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003635 CleanupPadInst *CPInst = RI->getCleanupPad();
3636 if (CPInst->getParent() != BB)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003637 // This isn't an empty cleanup.
3638 return false;
3639
David Majnemer2482e1c2016-06-04 23:50:03 +00003640 // We cannot kill the pad if it has multiple uses. This typically arises
3641 // from unreachable basic blocks.
3642 if (!CPInst->hasOneUse())
3643 return false;
3644
David Majnemer9f92f4c2016-05-21 05:12:32 +00003645 // Check that there are no other instructions except for benign intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003646 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
David Majnemer9f92f4c2016-05-21 05:12:32 +00003647 while (++I != E) {
3648 auto *II = dyn_cast<IntrinsicInst>(I);
3649 if (!II)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003650 return false;
3651
David Majnemer9f92f4c2016-05-21 05:12:32 +00003652 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
3653 switch (IntrinsicID) {
3654 case Intrinsic::dbg_declare:
3655 case Intrinsic::dbg_value:
3656 case Intrinsic::lifetime_end:
3657 break;
3658 default:
3659 return false;
3660 }
3661 }
3662
David Majnemer8a1c45d2015-12-12 05:38:55 +00003663 // If the cleanup return we are simplifying unwinds to the caller, this will
3664 // set UnwindDest to nullptr.
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003665 BasicBlock *UnwindDest = RI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003666 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003667
3668 // We're about to remove BB from the control flow. Before we do, sink any
3669 // PHINodes into the unwind destination. Doing this before changing the
3670 // control flow avoids some potentially slow checks, since we can currently
3671 // be certain that UnwindDest and BB have no common predecessors (since they
3672 // are both EH pads).
3673 if (UnwindDest) {
3674 // First, go through the PHI nodes in UnwindDest and update any nodes that
3675 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003676 for (BasicBlock::iterator I = UnwindDest->begin(),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003677 IE = DestEHPad->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003678 I != IE; ++I) {
3679 PHINode *DestPN = cast<PHINode>(I);
James Molloy4de84dd2015-11-04 15:28:04 +00003680
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003681 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003682 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003683 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003684 // This PHI node has an incoming value that corresponds to a control
3685 // path through the cleanup pad we are removing. If the incoming
3686 // value is in the cleanup pad, it must be a PHINode (because we
3687 // verified above that the block is otherwise empty). Otherwise, the
3688 // value is either a constant or a value that dominates the cleanup
3689 // pad being removed.
3690 //
3691 // Because BB and UnwindDest are both EH pads, all of their
3692 // predecessors must unwind to these blocks, and since no instruction
3693 // can have multiple unwind destinations, there will be no overlap in
3694 // incoming blocks between SrcPN and DestPN.
3695 Value *SrcVal = DestPN->getIncomingValue(Idx);
3696 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3697
3698 // Remove the entry for the block we are deleting.
3699 DestPN->removeIncomingValue(Idx, false);
3700
3701 if (SrcPN && SrcPN->getParent() == BB) {
3702 // If the incoming value was a PHI node in the cleanup pad we are
3703 // removing, we need to merge that PHI node's incoming values into
3704 // DestPN.
James Molloy4de84dd2015-11-04 15:28:04 +00003705 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
Dehao Chenf6c00832016-05-18 19:44:21 +00003706 SrcIdx != SrcE; ++SrcIdx) {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003707 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3708 SrcPN->getIncomingBlock(SrcIdx));
3709 }
3710 } else {
3711 // Otherwise, the incoming value came from above BB and
3712 // so we can just reuse it. We must associate all of BB's
3713 // predecessors with this value.
3714 for (auto *pred : predecessors(BB)) {
3715 DestPN->addIncoming(SrcVal, pred);
3716 }
3717 }
3718 }
3719
3720 // Sink any remaining PHI nodes directly into UnwindDest.
David Majnemer8a1c45d2015-12-12 05:38:55 +00003721 Instruction *InsertPt = DestEHPad;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003722 for (BasicBlock::iterator I = BB->begin(),
3723 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003724 I != IE;) {
3725 // The iterator must be incremented here because the instructions are
3726 // being moved to another block.
3727 PHINode *PN = cast<PHINode>(I++);
3728 if (PN->use_empty())
3729 // If the PHI node has no uses, just leave it. It will be erased
3730 // when we erase BB below.
3731 continue;
3732
3733 // Otherwise, sink this PHI node into UnwindDest.
3734 // Any predecessors to UnwindDest which are not already represented
3735 // must be back edges which inherit the value from the path through
3736 // BB. In this case, the PHI value must reference itself.
3737 for (auto *pred : predecessors(UnwindDest))
3738 if (pred != BB)
3739 PN->addIncoming(PN, pred);
3740 PN->moveBefore(InsertPt);
3741 }
3742 }
3743
3744 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3745 // The iterator must be updated here because we are removing this pred.
3746 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003747 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003748 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003749 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003750 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003751 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003752 }
3753 }
3754
3755 // The cleanup pad is now unreachable. Zap it.
3756 BB->eraseFromParent();
3757 return true;
3758}
3759
David Majnemer1efa23d2016-02-20 01:07:45 +00003760// Try to merge two cleanuppads together.
3761static bool mergeCleanupPad(CleanupReturnInst *RI) {
3762 // Skip any cleanuprets which unwind to caller, there is nothing to merge
3763 // with.
3764 BasicBlock *UnwindDest = RI->getUnwindDest();
3765 if (!UnwindDest)
3766 return false;
3767
3768 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
3769 // be safe to merge without code duplication.
3770 if (UnwindDest->getSinglePredecessor() != RI->getParent())
3771 return false;
3772
3773 // Verify that our cleanuppad's unwind destination is another cleanuppad.
3774 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
3775 if (!SuccessorCleanupPad)
3776 return false;
3777
3778 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
3779 // Replace any uses of the successor cleanupad with the predecessor pad
3780 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
3781 // funclet bundle operands.
3782 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
3783 // Remove the old cleanuppad.
3784 SuccessorCleanupPad->eraseFromParent();
3785 // Now, we simply replace the cleanupret with a branch to the unwind
3786 // destination.
3787 BranchInst::Create(UnwindDest, RI->getParent());
3788 RI->eraseFromParent();
3789
3790 return true;
3791}
3792
3793bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00003794 // It is possible to transiantly have an undef cleanuppad operand because we
3795 // have deleted some, but not all, dead blocks.
3796 // Eventually, this block will be deleted.
3797 if (isa<UndefValue>(RI->getOperand(0)))
3798 return false;
3799
David Majnemer9f92f4c2016-05-21 05:12:32 +00003800 if (mergeCleanupPad(RI))
David Majnemer1efa23d2016-02-20 01:07:45 +00003801 return true;
3802
David Majnemer9f92f4c2016-05-21 05:12:32 +00003803 if (removeEmptyCleanup(RI))
David Majnemer1efa23d2016-02-20 01:07:45 +00003804 return true;
3805
3806 return false;
3807}
3808
Devang Pateldd14e0f2011-05-18 21:33:11 +00003809bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003810 BasicBlock *BB = RI->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00003811 if (!BB->getFirstNonPHIOrDbg()->isTerminator())
3812 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003813
Chris Lattner25c3af32010-12-13 06:25:44 +00003814 // Find predecessors that end with branches.
Dehao Chenf6c00832016-05-18 19:44:21 +00003815 SmallVector<BasicBlock *, 8> UncondBranchPreds;
3816 SmallVector<BranchInst *, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003817 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3818 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003819 TerminatorInst *PTI = P->getTerminator();
3820 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3821 if (BI->isUnconditional())
3822 UncondBranchPreds.push_back(P);
3823 else
3824 CondBranchPreds.push_back(BI);
3825 }
3826 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003827
Chris Lattner25c3af32010-12-13 06:25:44 +00003828 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00003829 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003830 while (!UncondBranchPreds.empty()) {
3831 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3832 DEBUG(dbgs() << "FOLDING: " << *BB
Dehao Chenf6c00832016-05-18 19:44:21 +00003833 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00003834 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00003835 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003836
Chris Lattner25c3af32010-12-13 06:25:44 +00003837 // If we eliminated all predecessors of the block, delete the block now.
Hyojin Sung4673f102016-03-29 04:08:57 +00003838 if (pred_empty(BB)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003839 // We know there are no successors, so just nuke the block.
3840 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00003841 if (LoopHeaders)
3842 LoopHeaders->erase(BB);
Hyojin Sung4673f102016-03-29 04:08:57 +00003843 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003844
Chris Lattner25c3af32010-12-13 06:25:44 +00003845 return true;
3846 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003847
Chris Lattner25c3af32010-12-13 06:25:44 +00003848 // Check out all of the conditional branches going to this return
3849 // instruction. If any of them just select between returns, change the
3850 // branch itself into a select/return pair.
3851 while (!CondBranchPreds.empty()) {
3852 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003853
Chris Lattner25c3af32010-12-13 06:25:44 +00003854 // Check to see if the non-BB successor is also a return block.
3855 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3856 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003857 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003858 return true;
3859 }
3860 return false;
3861}
3862
Chris Lattner25c3af32010-12-13 06:25:44 +00003863bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3864 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003865
Chris Lattner25c3af32010-12-13 06:25:44 +00003866 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003867
Chris Lattner25c3af32010-12-13 06:25:44 +00003868 // If there are any instructions immediately before the unreachable that can
3869 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003870 while (UI->getIterator() != BB->begin()) {
3871 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00003872 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003873 // Do not delete instructions that can have side effects which might cause
3874 // the unreachable to not be reachable; specifically, calls and volatile
3875 // operations may have this effect.
Dehao Chenf6c00832016-05-18 19:44:21 +00003876 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
3877 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003878
3879 if (BBI->mayHaveSideEffects()) {
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003880 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003881 if (SI->isVolatile())
3882 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003883 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003884 if (LI->isVolatile())
3885 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003886 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003887 if (RMWI->isVolatile())
3888 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003889 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003890 if (CXI->isVolatile())
3891 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003892 } else if (isa<CatchPadInst>(BBI)) {
3893 // A catchpad may invoke exception object constructors and such, which
3894 // in some languages can be arbitrary code, so be conservative by
3895 // default.
3896 // For CoreCLR, it just involves a type test, so can be removed.
3897 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
3898 EHPersonality::CoreCLR)
3899 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003900 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3901 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003902 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003903 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003904 // Note that deleting LandingPad's here is in fact okay, although it
3905 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3906 // all the predecessors of this block will be the unwind edges of Invokes,
3907 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003908 }
3909
Eli Friedmanaac35b32011-03-09 00:48:33 +00003910 // Delete this instruction (any uses are guaranteed to be dead)
3911 if (!BBI->use_empty())
3912 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003913 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003914 Changed = true;
3915 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003916
Chris Lattner25c3af32010-12-13 06:25:44 +00003917 // If the unreachable instruction is the first in the block, take a gander
3918 // at all of the predecessors of this instruction, and simplify them.
Dehao Chenf6c00832016-05-18 19:44:21 +00003919 if (&BB->front() != UI)
3920 return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003921
Dehao Chenf6c00832016-05-18 19:44:21 +00003922 SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner25c3af32010-12-13 06:25:44 +00003923 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3924 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003925 IRBuilder<> Builder(TI);
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003926 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003927 if (BI->isUnconditional()) {
3928 if (BI->getSuccessor(0) == BB) {
3929 new UnreachableInst(TI->getContext(), TI);
3930 TI->eraseFromParent();
3931 Changed = true;
3932 }
3933 } else {
3934 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003935 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003936 EraseTerminatorInstAndDCECond(BI);
3937 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003938 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003939 EraseTerminatorInstAndDCECond(BI);
3940 Changed = true;
3941 }
3942 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003943 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Dehao Chenf6c00832016-05-18 19:44:21 +00003944 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e;
3945 ++i)
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003946 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003947 BB->removePredecessor(SI->getParent());
3948 SI->removeCase(i);
Dehao Chenf6c00832016-05-18 19:44:21 +00003949 --i;
3950 --e;
Chris Lattner25c3af32010-12-13 06:25:44 +00003951 Changed = true;
3952 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003953 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
3954 if (II->getUnwindDest() == BB) {
3955 removeUnwindEdge(TI->getParent());
3956 Changed = true;
3957 }
3958 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
3959 if (CSI->getUnwindDest() == BB) {
3960 removeUnwindEdge(TI->getParent());
3961 Changed = true;
3962 continue;
3963 }
3964
3965 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
3966 E = CSI->handler_end();
3967 I != E; ++I) {
3968 if (*I == BB) {
3969 CSI->removeHandler(I);
3970 --I;
3971 --E;
3972 Changed = true;
3973 }
3974 }
3975 if (CSI->getNumHandlers() == 0) {
3976 BasicBlock *CatchSwitchBB = CSI->getParent();
3977 if (CSI->hasUnwindDest()) {
3978 // Redirect preds to the unwind dest
3979 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
3980 } else {
3981 // Rewrite all preds to unwind to caller (or from invoke to call).
3982 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
3983 for (BasicBlock *EHPred : EHPreds)
3984 removeUnwindEdge(EHPred);
3985 }
3986 // The catchswitch is no longer reachable.
3987 new UnreachableInst(CSI->getContext(), CSI);
3988 CSI->eraseFromParent();
3989 Changed = true;
3990 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00003991 } else if (isa<CleanupReturnInst>(TI)) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003992 new UnreachableInst(TI->getContext(), TI);
3993 TI->eraseFromParent();
3994 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00003995 }
3996 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003997
Chris Lattner25c3af32010-12-13 06:25:44 +00003998 // If this block is now dead, remove it.
Dehao Chenf6c00832016-05-18 19:44:21 +00003999 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004000 // We know there are no successors, so just nuke the block.
4001 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00004002 if (LoopHeaders)
4003 LoopHeaders->erase(BB);
Chris Lattner25c3af32010-12-13 06:25:44 +00004004 return true;
4005 }
4006
4007 return Changed;
4008}
4009
Hans Wennborg68000082015-01-26 19:52:32 +00004010static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
4011 assert(Cases.size() >= 1);
4012
4013 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
4014 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
4015 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
4016 return false;
4017 }
4018 return true;
4019}
4020
4021/// Turn a switch with two reachable destinations into an integer range
4022/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004023static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00004024 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004025
Hans Wennborg68000082015-01-26 19:52:32 +00004026 bool HasDefault =
4027 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00004028
Hans Wennborg68000082015-01-26 19:52:32 +00004029 // Partition the cases into two sets with different destinations.
4030 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
4031 BasicBlock *DestB = nullptr;
Dehao Chenf6c00832016-05-18 19:44:21 +00004032 SmallVector<ConstantInt *, 16> CasesA;
4033 SmallVector<ConstantInt *, 16> CasesB;
Hans Wennborg68000082015-01-26 19:52:32 +00004034
4035 for (SwitchInst::CaseIt I : SI->cases()) {
4036 BasicBlock *Dest = I.getCaseSuccessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00004037 if (!DestA)
4038 DestA = Dest;
Hans Wennborg68000082015-01-26 19:52:32 +00004039 if (Dest == DestA) {
4040 CasesA.push_back(I.getCaseValue());
4041 continue;
4042 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004043 if (!DestB)
4044 DestB = Dest;
Hans Wennborg68000082015-01-26 19:52:32 +00004045 if (Dest == DestB) {
4046 CasesB.push_back(I.getCaseValue());
4047 continue;
4048 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004049 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00004050 }
4051
Dehao Chenf6c00832016-05-18 19:44:21 +00004052 assert(DestA && DestB &&
4053 "Single-destination switch should have been folded.");
Hans Wennborg68000082015-01-26 19:52:32 +00004054 assert(DestA != DestB);
4055 assert(DestB != SI->getDefaultDest());
4056 assert(!CasesB.empty() && "There must be non-default cases.");
4057 assert(!CasesA.empty() || HasDefault);
4058
4059 // Figure out if one of the sets of cases form a contiguous range.
4060 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
4061 BasicBlock *ContiguousDest = nullptr;
4062 BasicBlock *OtherDest = nullptr;
4063 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
4064 ContiguousCases = &CasesA;
4065 ContiguousDest = DestA;
4066 OtherDest = DestB;
4067 } else if (CasesAreContiguous(CasesB)) {
4068 ContiguousCases = &CasesB;
4069 ContiguousDest = DestB;
4070 OtherDest = DestA;
4071 } else
4072 return false;
4073
4074 // Start building the compare and branch.
4075
4076 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
Dehao Chenf6c00832016-05-18 19:44:21 +00004077 Constant *NumCases =
4078 ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004079
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00004080 Value *Sub = SI->getCondition();
4081 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00004082 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
4083
Hans Wennborgc9e1d992013-04-16 08:35:36 +00004084 Value *Cmp;
4085 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00004086 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00004087 Cmp = ConstantInt::getTrue(SI->getContext());
4088 else
4089 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00004090 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004091
Manman Ren56575552012-09-18 00:47:33 +00004092 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00004093 if (HasBranchWeights(SI)) {
4094 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00004095 GetBranchWeights(SI, Weights);
4096 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00004097 uint64_t TrueWeight = 0;
4098 uint64_t FalseWeight = 0;
4099 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
4100 if (SI->getSuccessor(I) == ContiguousDest)
4101 TrueWeight += Weights[I];
4102 else
4103 FalseWeight += Weights[I];
4104 }
4105 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4106 TrueWeight /= 2;
4107 FalseWeight /= 2;
4108 }
Manman Ren56575552012-09-18 00:47:33 +00004109 NewBI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00004110 MDBuilder(SI->getContext())
4111 .createBranchWeights((uint32_t)TrueWeight,
4112 (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00004113 }
4114 }
4115
Hans Wennborg68000082015-01-26 19:52:32 +00004116 // Prune obsolete incoming values off the successors' PHI nodes.
4117 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
4118 unsigned PreviousEdges = ContiguousCases->size();
Dehao Chenf6c00832016-05-18 19:44:21 +00004119 if (ContiguousDest == SI->getDefaultDest())
4120 ++PreviousEdges;
Hans Wennborg68000082015-01-26 19:52:32 +00004121 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004122 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4123 }
Hans Wennborg68000082015-01-26 19:52:32 +00004124 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
4125 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
Dehao Chenf6c00832016-05-18 19:44:21 +00004126 if (OtherDest == SI->getDefaultDest())
4127 ++PreviousEdges;
Hans Wennborg68000082015-01-26 19:52:32 +00004128 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4129 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4130 }
4131
4132 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004133 SI->eraseFromParent();
4134
4135 return true;
4136}
Chris Lattner25c3af32010-12-13 06:25:44 +00004137
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004138/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004139/// and use it to remove dead cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004140static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
4141 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004142 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00004143 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004144 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00004145 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004146
Sanjay Patel75892a12016-05-20 14:53:09 +00004147 // We can also eliminate cases by determining that their values are outside of
4148 // the limited range of the condition based on how many significant (non-sign)
4149 // bits are in the condition value.
4150 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
4151 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4152
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004153 // Gather dead cases.
Dehao Chenf6c00832016-05-18 19:44:21 +00004154 SmallVector<ConstantInt *, 8> DeadCases;
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004155 for (auto &Case : SI->cases()) {
Sanjay Patel75892a12016-05-20 14:53:09 +00004156 APInt CaseVal = Case.getCaseValue()->getValue();
4157 if ((CaseVal & KnownZero) != 0 || (CaseVal & KnownOne) != KnownOne ||
4158 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004159 DeadCases.push_back(Case.getCaseValue());
Sanjay Patel75892a12016-05-20 14:53:09 +00004160 DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal << " is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004161 }
4162 }
4163
Dehao Chenf6c00832016-05-18 19:44:21 +00004164 // If we can prove that the cases must cover all possible values, the
4165 // default destination becomes dead and we can remove it. If we know some
Philip Reames05370132015-09-10 17:44:47 +00004166 // of the bits in the value, we can use that to more precisely compute the
4167 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00004168 bool HasDefault =
Dehao Chenf6c00832016-05-18 19:44:21 +00004169 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4170 const unsigned NumUnknownBits =
4171 Bits - (KnownZero.Or(KnownOne)).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00004172 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00004173 if (HasDefault && DeadCases.empty() &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004174 NumUnknownBits < 64 /* avoid overflow */ &&
Philip Reames05370132015-09-10 17:44:47 +00004175 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00004176 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
Dehao Chenf6c00832016-05-18 19:44:21 +00004177 BasicBlock *NewDefault =
4178 SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004179 SI->setDefaultDest(&*NewDefault);
4180 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00004181 auto *OldTI = NewDefault->getTerminator();
4182 new UnreachableInst(SI->getContext(), OldTI);
4183 EraseTerminatorInstAndDCECond(OldTI);
4184 return true;
4185 }
4186
Manman Ren56575552012-09-18 00:47:33 +00004187 SmallVector<uint64_t, 8> Weights;
4188 bool HasWeight = HasBranchWeights(SI);
4189 if (HasWeight) {
4190 GetBranchWeights(SI, Weights);
4191 HasWeight = (Weights.size() == 1 + SI->getNumCases());
4192 }
4193
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004194 // Remove dead cases from the switch.
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004195 for (ConstantInt *DeadCase : DeadCases) {
4196 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCase);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00004197 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00004198 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00004199 if (HasWeight) {
Dehao Chenf6c00832016-05-18 19:44:21 +00004200 std::swap(Weights[Case.getCaseIndex() + 1], Weights.back());
Manman Ren56575552012-09-18 00:47:33 +00004201 Weights.pop_back();
4202 }
4203
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004204 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00004205 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004206 SI->removeCase(Case);
4207 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00004208 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00004209 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
4210 SI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00004211 MDBuilder(SI->getParent()->getContext())
4212 .createBranchWeights(MDWeights));
Manman Ren56575552012-09-18 00:47:33 +00004213 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004214
4215 return !DeadCases.empty();
4216}
4217
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004218/// If BB would be eligible for simplification by
4219/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004220/// by an unconditional branch), look at the phi node for BB in the successor
4221/// block and see if the incoming value is equal to CaseValue. If so, return
4222/// the phi node, and set PhiIndex to BB's index in the phi node.
4223static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
Dehao Chenf6c00832016-05-18 19:44:21 +00004224 BasicBlock *BB, int *PhiIndex) {
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004225 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00004226 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004227 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00004228 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004229
4230 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
4231 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00004232 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004233
4234 BasicBlock *Succ = Branch->getSuccessor(0);
4235
4236 BasicBlock::iterator I = Succ->begin();
4237 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4238 int Idx = PHI->getBasicBlockIndex(BB);
4239 assert(Idx >= 0 && "PHI has no entry for predecessor?");
4240
4241 Value *InValue = PHI->getIncomingValue(Idx);
Dehao Chenf6c00832016-05-18 19:44:21 +00004242 if (InValue != CaseValue)
4243 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004244
4245 *PhiIndex = Idx;
4246 return PHI;
4247 }
4248
Craig Topperf40110f2014-04-25 05:29:35 +00004249 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004250}
4251
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004252/// Try to forward the condition of a switch instruction to a phi node
4253/// dominated by the switch, if that would mean that some of the destination
4254/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004255/// Returns true if a change is made.
4256static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
Dehao Chenf6c00832016-05-18 19:44:21 +00004257 typedef DenseMap<PHINode *, SmallVector<int, 4>> ForwardingNodesMap;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004258 ForwardingNodesMap ForwardingNodes;
4259
Dehao Chenf6c00832016-05-18 19:44:21 +00004260 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E;
4261 ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00004262 ConstantInt *CaseValue = I.getCaseValue();
4263 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004264
4265 int PhiIndex;
Dehao Chenf6c00832016-05-18 19:44:21 +00004266 PHINode *PHI =
4267 FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIndex);
4268 if (!PHI)
4269 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004270
4271 ForwardingNodes[PHI].push_back(PhiIndex);
4272 }
4273
4274 bool Changed = false;
4275
4276 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
Dehao Chenf6c00832016-05-18 19:44:21 +00004277 E = ForwardingNodes.end();
4278 I != E; ++I) {
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004279 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00004280 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004281
Dehao Chenf6c00832016-05-18 19:44:21 +00004282 if (Indexes.size() < 2)
4283 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004284
4285 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
4286 Phi->setIncomingValue(Indexes[I], SI->getCondition());
4287 Changed = true;
4288 }
4289
4290 return Changed;
4291}
4292
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004293/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004294/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00004295static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00004296 if (C->isThreadDependent())
4297 return false;
4298 if (C->isDLLImportDependent())
4299 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004300
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00004301 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
4302 return CE->isGEPWithNoNotionalOverIndexing();
4303
Dehao Chenf6c00832016-05-18 19:44:21 +00004304 return isa<ConstantFP>(C) || isa<ConstantInt>(C) ||
4305 isa<ConstantPointerNull>(C) || isa<GlobalValue>(C) ||
4306 isa<UndefValue>(C);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004307}
4308
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004309/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004310/// its constant value in ConstantPool, returning 0 if it's not there.
Dehao Chenf6c00832016-05-18 19:44:21 +00004311static Constant *
4312LookupConstant(Value *V,
4313 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00004314 if (Constant *C = dyn_cast<Constant>(V))
4315 return C;
4316 return ConstantPool.lookup(V);
4317}
4318
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004319/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004320/// simple instructions such as binary operations where both operands are
4321/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004322/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00004323static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004324ConstantFold(Instruction *I, const DataLayout &DL,
4325 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004326 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00004327 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
4328 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00004329 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00004330 if (A->isAllOnesValue())
4331 return LookupConstant(Select->getTrueValue(), ConstantPool);
4332 if (A->isNullValue())
4333 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00004334 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004335 }
4336
Benjamin Kramer7c302602013-11-12 12:24:36 +00004337 SmallVector<Constant *, 4> COps;
4338 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
4339 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
4340 COps.push_back(A);
4341 else
Craig Topperf40110f2014-04-25 05:29:35 +00004342 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004343 }
4344
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004345 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00004346 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4347 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004348 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00004349
Manuel Jacobe9024592016-01-21 06:33:22 +00004350 return ConstantFoldInstOperands(I, COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004351}
4352
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004353/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004354/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004355/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004356/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00004357static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004358GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00004359 BasicBlock **CommonDest,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004360 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
4361 const DataLayout &DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004362 // The block from which we enter the common destination.
4363 BasicBlock *Pred = SI->getParent();
4364
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004365 // If CaseDest is empty except for some side-effect free instructions through
4366 // which we can constant-propagate the CaseVal, continue to its successor.
Dehao Chenf6c00832016-05-18 19:44:21 +00004367 SmallDenseMap<Value *, Constant *> ConstantPool;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004368 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4369 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4370 ++I) {
4371 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4372 // If the terminator is a simple branch, continue to the next block.
4373 if (T->getNumSuccessors() != 1)
4374 return false;
4375 Pred = CaseDest;
4376 CaseDest = T->getSuccessor(0);
4377 } else if (isa<DbgInfoIntrinsic>(I)) {
4378 // Skip debug intrinsic.
4379 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004380 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004381 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00004382
4383 // If the instruction has uses outside this block or a phi node slot for
4384 // the block, it is not safe to bypass the instruction since it would then
4385 // no longer dominate all its uses.
4386 for (auto &Use : I->uses()) {
4387 User *User = Use.getUser();
4388 if (Instruction *I = dyn_cast<Instruction>(User))
4389 if (I->getParent() == CaseDest)
4390 continue;
4391 if (PHINode *Phi = dyn_cast<PHINode>(User))
4392 if (Phi->getIncomingBlock(Use) == CaseDest)
4393 continue;
4394 return false;
4395 }
4396
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004397 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004398 } else {
4399 break;
4400 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004401 }
4402
4403 // If we did not have a CommonDest before, use the current one.
4404 if (!*CommonDest)
4405 *CommonDest = CaseDest;
4406 // If the destination isn't the common one, abort.
4407 if (CaseDest != *CommonDest)
4408 return false;
4409
4410 // Get the values for this case from phi nodes in the destination block.
4411 BasicBlock::iterator I = (*CommonDest)->begin();
4412 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4413 int Idx = PHI->getBasicBlockIndex(Pred);
4414 if (Idx == -1)
4415 continue;
4416
Dehao Chenf6c00832016-05-18 19:44:21 +00004417 Constant *ConstVal =
4418 LookupConstant(PHI->getIncomingValue(Idx), ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004419 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004420 return false;
4421
4422 // Be conservative about which kinds of constants we support.
4423 if (!ValidLookupTableConstant(ConstVal))
4424 return false;
4425
4426 Res.push_back(std::make_pair(PHI, ConstVal));
4427 }
4428
Hans Wennborgac114a32014-01-12 00:44:41 +00004429 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004430}
4431
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004432// Helper function used to add CaseVal to the list of cases that generate
4433// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004434static void MapCaseToResult(ConstantInt *CaseVal,
Dehao Chenf6c00832016-05-18 19:44:21 +00004435 SwitchCaseResultVectorTy &UniqueResults,
4436 Constant *Result) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004437 for (auto &I : UniqueResults) {
4438 if (I.first == Result) {
4439 I.second.push_back(CaseVal);
4440 return;
4441 }
4442 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004443 UniqueResults.push_back(
4444 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004445}
4446
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004447// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004448// results for the PHI node of the common destination block for a switch
4449// instruction. Returns false if multiple PHI nodes have been found or if
4450// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004451static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4452 BasicBlock *&CommonDest,
4453 SwitchCaseResultVectorTy &UniqueResults,
4454 Constant *&DefaultResult,
4455 const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004456 for (auto &I : SI->cases()) {
4457 ConstantInt *CaseVal = I.getCaseValue();
4458
4459 // Resulting value at phi nodes for this case value.
4460 SwitchCaseResultsTy Results;
4461 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4462 DL))
4463 return false;
4464
4465 // Only one value per case is permitted
4466 if (Results.size() > 1)
4467 return false;
4468 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4469
4470 // Check the PHI consistency.
4471 if (!PHI)
4472 PHI = Results[0].first;
4473 else if (PHI != Results[0].first)
4474 return false;
4475 }
4476 // Find the default result value.
4477 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4478 BasicBlock *DefaultDest = SI->getDefaultDest();
4479 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4480 DL);
4481 // If the default value is not found abort unless the default destination
4482 // is unreachable.
4483 DefaultResult =
4484 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4485 if ((!DefaultResult &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004486 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004487 return false;
4488
4489 return true;
4490}
4491
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004492// Helper function that checks if it is possible to transform a switch with only
4493// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004494// Example:
4495// switch (a) {
4496// case 10: %0 = icmp eq i32 %a, 10
4497// return 10; %1 = select i1 %0, i32 10, i32 4
4498// case 20: ----> %2 = icmp eq i32 %a, 20
4499// return 2; %3 = select i1 %2, i32 2, i32 %1
4500// default:
4501// return 4;
4502// }
Dehao Chenf6c00832016-05-18 19:44:21 +00004503static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4504 Constant *DefaultResult, Value *Condition,
4505 IRBuilder<> &Builder) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004506 assert(ResultVector.size() == 2 &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004507 "We should have exactly two unique results at this point");
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004508 // If we are selecting between only two cases transform into a simple
4509 // select or a two-way select if default is possible.
4510 if (ResultVector[0].second.size() == 1 &&
4511 ResultVector[1].second.size() == 1) {
4512 ConstantInt *const FirstCase = ResultVector[0].second[0];
4513 ConstantInt *const SecondCase = ResultVector[1].second[0];
4514
4515 bool DefaultCanTrigger = DefaultResult;
4516 Value *SelectValue = ResultVector[1].first;
4517 if (DefaultCanTrigger) {
4518 Value *const ValueCompare =
4519 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4520 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4521 DefaultResult, "switch.select");
4522 }
4523 Value *const ValueCompare =
4524 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
Dehao Chenf6c00832016-05-18 19:44:21 +00004525 return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
4526 SelectValue, "switch.select");
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004527 }
4528
4529 return nullptr;
4530}
4531
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004532// Helper function to cleanup a switch instruction that has been converted into
4533// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004534static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4535 Value *SelectValue,
4536 IRBuilder<> &Builder) {
4537 BasicBlock *SelectBB = SI->getParent();
4538 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4539 PHI->removeIncomingValue(SelectBB);
4540 PHI->addIncoming(SelectValue, SelectBB);
4541
4542 Builder.CreateBr(PHI->getParent());
4543
4544 // Remove the switch.
4545 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4546 BasicBlock *Succ = SI->getSuccessor(i);
4547
4548 if (Succ == PHI->getParent())
4549 continue;
4550 Succ->removePredecessor(SelectBB);
4551 }
4552 SI->eraseFromParent();
4553}
4554
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004555/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004556/// phi nodes in a common successor block with only two different
4557/// constant values, replace the switch with select.
4558static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004559 AssumptionCache *AC, const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004560 Value *const Cond = SI->getCondition();
4561 PHINode *PHI = nullptr;
4562 BasicBlock *CommonDest = nullptr;
4563 Constant *DefaultResult;
4564 SwitchCaseResultVectorTy UniqueResults;
4565 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004566 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4567 DL))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004568 return false;
4569 // Selects choose between maximum two values.
4570 if (UniqueResults.size() != 2)
4571 return false;
4572 assert(PHI != nullptr && "PHI for value select not found");
4573
4574 Builder.SetInsertPoint(SI);
Dehao Chenf6c00832016-05-18 19:44:21 +00004575 Value *SelectValue =
4576 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004577 if (SelectValue) {
4578 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4579 return true;
4580 }
4581 // The switch couldn't be converted into a select.
4582 return false;
4583}
4584
Hans Wennborg776d7122012-09-26 09:34:53 +00004585namespace {
Dehao Chenf6c00832016-05-18 19:44:21 +00004586/// This class represents a lookup table that can be used to replace a switch.
4587class SwitchLookupTable {
4588public:
4589 /// Create a lookup table to use as a switch replacement with the contents
4590 /// of Values, using DefaultValue to fill any holes in the table.
4591 SwitchLookupTable(
4592 Module &M, uint64_t TableSize, ConstantInt *Offset,
4593 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4594 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004595
Dehao Chenf6c00832016-05-18 19:44:21 +00004596 /// Build instructions with Builder to retrieve the value at
4597 /// the position given by Index in the lookup table.
4598 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00004599
Dehao Chenf6c00832016-05-18 19:44:21 +00004600 /// Return true if a table with TableSize elements of
4601 /// type ElementType would fit in a target-legal register.
4602 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
4603 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004604
Dehao Chenf6c00832016-05-18 19:44:21 +00004605private:
4606 // Depending on the contents of the table, it can be represented in
4607 // different ways.
4608 enum {
4609 // For tables where each element contains the same value, we just have to
4610 // store that single value and return it for each lookup.
4611 SingleValueKind,
Hans Wennborg776d7122012-09-26 09:34:53 +00004612
Dehao Chenf6c00832016-05-18 19:44:21 +00004613 // For tables where there is a linear relationship between table index
4614 // and values. We calculate the result with a simple multiplication
4615 // and addition instead of a table lookup.
4616 LinearMapKind,
Erik Eckstein105374f2014-11-17 09:13:57 +00004617
Dehao Chenf6c00832016-05-18 19:44:21 +00004618 // For small tables with integer elements, we can pack them into a bitmap
4619 // that fits into a target-legal register. Values are retrieved by
4620 // shift and mask operations.
4621 BitMapKind,
Hans Wennborg39583b82012-09-26 09:44:49 +00004622
Dehao Chenf6c00832016-05-18 19:44:21 +00004623 // The table is stored as an array of values. Values are retrieved by load
4624 // instructions from the table.
4625 ArrayKind
4626 } Kind;
Hans Wennborg776d7122012-09-26 09:34:53 +00004627
Dehao Chenf6c00832016-05-18 19:44:21 +00004628 // For SingleValueKind, this is the single value.
4629 Constant *SingleValue;
Hans Wennborg776d7122012-09-26 09:34:53 +00004630
Dehao Chenf6c00832016-05-18 19:44:21 +00004631 // For BitMapKind, this is the bitmap.
4632 ConstantInt *BitMap;
4633 IntegerType *BitMapElementTy;
Hans Wennborg39583b82012-09-26 09:44:49 +00004634
Dehao Chenf6c00832016-05-18 19:44:21 +00004635 // For LinearMapKind, these are the constants used to derive the value.
4636 ConstantInt *LinearOffset;
4637 ConstantInt *LinearMultiplier;
Erik Eckstein105374f2014-11-17 09:13:57 +00004638
Dehao Chenf6c00832016-05-18 19:44:21 +00004639 // For ArrayKind, this is the array.
4640 GlobalVariable *Array;
4641};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00004642}
Hans Wennborg776d7122012-09-26 09:34:53 +00004643
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004644SwitchLookupTable::SwitchLookupTable(
4645 Module &M, uint64_t TableSize, ConstantInt *Offset,
4646 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4647 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00004648 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00004649 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004650 assert(Values.size() && "Can't build lookup table without values!");
4651 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004652
4653 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00004654 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004655
Hans Wennborgac114a32014-01-12 00:44:41 +00004656 Type *ValueType = Values.begin()->second->getType();
4657
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004658 // Build up the table contents.
Dehao Chenf6c00832016-05-18 19:44:21 +00004659 SmallVector<Constant *, 64> TableContents(TableSize);
Hans Wennborg776d7122012-09-26 09:34:53 +00004660 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4661 ConstantInt *CaseVal = Values[I].first;
4662 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00004663 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004664
Dehao Chenf6c00832016-05-18 19:44:21 +00004665 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004666 TableContents[Idx] = CaseRes;
4667
Hans Wennborg776d7122012-09-26 09:34:53 +00004668 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004669 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004670 }
4671
4672 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00004673 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00004674 assert(DefaultValue &&
4675 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00004676 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00004677 for (uint64_t I = 0; I < TableSize; ++I) {
4678 if (!TableContents[I])
4679 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004680 }
4681
Hans Wennborg776d7122012-09-26 09:34:53 +00004682 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004683 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004684 }
4685
Hans Wennborg776d7122012-09-26 09:34:53 +00004686 // If each element in the table contains the same value, we only need to store
4687 // that single value.
4688 if (SingleValue) {
4689 Kind = SingleValueKind;
4690 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004691 }
4692
Erik Eckstein105374f2014-11-17 09:13:57 +00004693 // Check if we can derive the value with a linear transformation from the
4694 // table index.
4695 if (isa<IntegerType>(ValueType)) {
4696 bool LinearMappingPossible = true;
4697 APInt PrevVal;
4698 APInt DistToPrev;
4699 assert(TableSize >= 2 && "Should be a SingleValue table.");
4700 // Check if there is the same distance between two consecutive values.
4701 for (uint64_t I = 0; I < TableSize; ++I) {
4702 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4703 if (!ConstVal) {
4704 // This is an undef. We could deal with it, but undefs in lookup tables
4705 // are very seldom. It's probably not worth the additional complexity.
4706 LinearMappingPossible = false;
4707 break;
4708 }
4709 APInt Val = ConstVal->getValue();
4710 if (I != 0) {
4711 APInt Dist = Val - PrevVal;
4712 if (I == 1) {
4713 DistToPrev = Dist;
4714 } else if (Dist != DistToPrev) {
4715 LinearMappingPossible = false;
4716 break;
4717 }
4718 }
4719 PrevVal = Val;
4720 }
4721 if (LinearMappingPossible) {
4722 LinearOffset = cast<ConstantInt>(TableContents[0]);
4723 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4724 Kind = LinearMapKind;
4725 ++NumLinearMaps;
4726 return;
4727 }
4728 }
4729
Hans Wennborg39583b82012-09-26 09:44:49 +00004730 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004731 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004732 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004733 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4734 for (uint64_t I = TableSize; I > 0; --I) {
4735 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00004736 // Insert values into the bitmap. Undef values are set to zero.
4737 if (!isa<UndefValue>(TableContents[I - 1])) {
4738 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4739 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4740 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004741 }
4742 BitMap = ConstantInt::get(M.getContext(), TableInt);
4743 BitMapElementTy = IT;
4744 Kind = BitMapKind;
4745 ++NumBitMaps;
4746 return;
4747 }
4748
Hans Wennborg776d7122012-09-26 09:34:53 +00004749 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004750 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004751 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4752
Dehao Chenf6c00832016-05-18 19:44:21 +00004753 Array = new GlobalVariable(M, ArrayTy, /*constant=*/true,
4754 GlobalVariable::PrivateLinkage, Initializer,
Hans Wennborg776d7122012-09-26 09:34:53 +00004755 "switch.table");
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004756 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Hans Wennborg776d7122012-09-26 09:34:53 +00004757 Kind = ArrayKind;
4758}
4759
Manman Ren4d189fb2014-07-24 21:13:20 +00004760Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004761 switch (Kind) {
Dehao Chenf6c00832016-05-18 19:44:21 +00004762 case SingleValueKind:
4763 return SingleValue;
4764 case LinearMapKind: {
4765 // Derive the result value from the input value.
4766 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4767 false, "switch.idx.cast");
4768 if (!LinearMultiplier->isOne())
4769 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4770 if (!LinearOffset->isZero())
4771 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4772 return Result;
4773 }
4774 case BitMapKind: {
4775 // Type of the bitmap (e.g. i59).
4776 IntegerType *MapTy = BitMap->getType();
Hans Wennborg39583b82012-09-26 09:44:49 +00004777
Dehao Chenf6c00832016-05-18 19:44:21 +00004778 // Cast Index to the same type as the bitmap.
4779 // Note: The Index is <= the number of elements in the table, so
4780 // truncating it to the width of the bitmask is safe.
4781 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004782
Dehao Chenf6c00832016-05-18 19:44:21 +00004783 // Multiply the shift amount by the element width.
4784 ShiftAmt = Builder.CreateMul(
4785 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4786 "switch.shiftamt");
Hans Wennborg39583b82012-09-26 09:44:49 +00004787
Dehao Chenf6c00832016-05-18 19:44:21 +00004788 // Shift down.
4789 Value *DownShifted =
4790 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
4791 // Mask off.
4792 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
4793 }
4794 case ArrayKind: {
4795 // Make sure the table index will not overflow when treated as signed.
4796 IntegerType *IT = cast<IntegerType>(Index->getType());
4797 uint64_t TableSize =
4798 Array->getInitializer()->getType()->getArrayNumElements();
4799 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4800 Index = Builder.CreateZExt(
4801 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
4802 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00004803
Dehao Chenf6c00832016-05-18 19:44:21 +00004804 Value *GEPIndices[] = {Builder.getInt32(0), Index};
4805 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4806 GEPIndices, "switch.gep");
4807 return Builder.CreateLoad(GEP, "switch.load");
4808 }
Hans Wennborg776d7122012-09-26 09:34:53 +00004809 }
4810 llvm_unreachable("Unknown lookup table kind!");
4811}
4812
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004813bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00004814 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004815 Type *ElementType) {
4816 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004817 if (!IT)
4818 return false;
4819 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4820 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004821
4822 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
Dehao Chenf6c00832016-05-18 19:44:21 +00004823 if (TableSize >= UINT_MAX / IT->getBitWidth())
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004824 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004825 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00004826}
4827
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004828/// Determine whether a lookup table should be built for this switch, based on
4829/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004830static bool
4831ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4832 const TargetTransformInfo &TTI, const DataLayout &DL,
4833 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004834 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4835 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00004836
Chandler Carruth77d433d2012-11-30 09:26:25 +00004837 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00004838 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00004839 for (const auto &I : ResultTypes) {
4840 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004841
4842 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004843 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004844
4845 // Saturate this flag to false.
Dehao Chenf6c00832016-05-18 19:44:21 +00004846 AllTablesFitInRegister =
4847 AllTablesFitInRegister &&
4848 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004849
4850 // If both flags saturate, we're done. NOTE: This *only* works with
4851 // saturating flags, and all flags have to saturate first due to the
4852 // non-deterministic behavior of iterating over a dense map.
4853 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00004854 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00004855 }
Evan Cheng65df8082012-11-30 02:02:42 +00004856
Chandler Carruth77d433d2012-11-30 09:26:25 +00004857 // If each table would fit in a register, we should build it anyway.
4858 if (AllTablesFitInRegister)
4859 return true;
4860
4861 // Don't build a table that doesn't fit in-register if it has illegal types.
4862 if (HasIllegalType)
4863 return false;
4864
4865 // The table density should be at least 40%. This is the same criterion as for
4866 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4867 // FIXME: Find the best cut-off.
4868 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004869}
4870
Erik Eckstein0d86c762014-11-27 15:13:14 +00004871/// Try to reuse the switch table index compare. Following pattern:
4872/// \code
4873/// if (idx < tablesize)
4874/// r = table[idx]; // table does not contain default_value
4875/// else
4876/// r = default_value;
4877/// if (r != default_value)
4878/// ...
4879/// \endcode
4880/// Is optimized to:
4881/// \code
4882/// cond = idx < tablesize;
4883/// if (cond)
4884/// r = table[idx];
4885/// else
4886/// r = default_value;
4887/// if (cond)
4888/// ...
4889/// \endcode
4890/// Jump threading will then eliminate the second if(cond).
Dehao Chenf6c00832016-05-18 19:44:21 +00004891static void reuseTableCompare(
4892 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
4893 Constant *DefaultValue,
4894 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
Erik Eckstein0d86c762014-11-27 15:13:14 +00004895
4896 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4897 if (!CmpInst)
4898 return;
4899
4900 // We require that the compare is in the same block as the phi so that jump
4901 // threading can do its work afterwards.
4902 if (CmpInst->getParent() != PhiBlock)
4903 return;
4904
4905 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4906 if (!CmpOp1)
4907 return;
4908
4909 Value *RangeCmp = RangeCheckBranch->getCondition();
4910 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4911 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4912
4913 // Check if the compare with the default value is constant true or false.
4914 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4915 DefaultValue, CmpOp1, true);
4916 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4917 return;
4918
4919 // Check if the compare with the case values is distinct from the default
4920 // compare result.
4921 for (auto ValuePair : Values) {
4922 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
Dehao Chenf6c00832016-05-18 19:44:21 +00004923 ValuePair.second, CmpOp1, true);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004924 if (!CaseConst || CaseConst == DefaultConst)
4925 return;
4926 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4927 "Expect true or false as compare result.");
4928 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004929
Erik Eckstein0d86c762014-11-27 15:13:14 +00004930 // Check if the branch instruction dominates the phi node. It's a simple
4931 // dominance check, but sufficient for our needs.
4932 // Although this check is invariant in the calling loops, it's better to do it
4933 // at this late stage. Practically we do it at most once for a switch.
4934 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4935 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4936 BasicBlock *Pred = *PI;
4937 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4938 return;
4939 }
4940
4941 if (DefaultConst == FalseConst) {
4942 // The compare yields the same result. We can replace it.
4943 CmpInst->replaceAllUsesWith(RangeCmp);
4944 ++NumTableCmpReuses;
4945 } else {
4946 // The compare yields the same result, just inverted. We can replace it.
Dehao Chenf6c00832016-05-18 19:44:21 +00004947 Value *InvertedTableCmp = BinaryOperator::CreateXor(
4948 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4949 RangeCheckBranch);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004950 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4951 ++NumTableCmpReuses;
4952 }
4953}
4954
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004955/// If the switch is only used to initialize one or more phi nodes in a common
4956/// successor block with different constant values, replace the switch with
4957/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004958static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4959 const DataLayout &DL,
4960 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004961 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004962
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004963 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004964 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004965 return false;
4966
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004967 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4968 // split off a dense part and build a lookup table for that.
4969
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004970 // FIXME: This creates arrays of GEPs to constant strings, which means each
4971 // GEP needs a runtime relocation in PIC code. We should just build one big
4972 // string and lookup indices into that.
4973
Dehao Chenf6c00832016-05-18 19:44:21 +00004974 // Ignore switches with less than three cases. Lookup tables will not make
4975 // them
Hans Wennborg4744ac12014-01-15 05:00:27 +00004976 // faster, so we don't analyze them.
4977 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004978 return false;
4979
4980 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00004981 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004982 assert(SI->case_begin() != SI->case_end());
4983 SwitchInst::CaseIt CI = SI->case_begin();
4984 ConstantInt *MinCaseVal = CI.getCaseValue();
4985 ConstantInt *MaxCaseVal = CI.getCaseValue();
4986
Craig Topperf40110f2014-04-25 05:29:35 +00004987 BasicBlock *CommonDest = nullptr;
Dehao Chenf6c00832016-05-18 19:44:21 +00004988 typedef SmallVector<std::pair<ConstantInt *, Constant *>, 4> ResultListTy;
4989 SmallDenseMap<PHINode *, ResultListTy> ResultLists;
4990 SmallDenseMap<PHINode *, Constant *> DefaultResults;
4991 SmallDenseMap<PHINode *, Type *> ResultTypes;
4992 SmallVector<PHINode *, 4> PHIs;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004993
4994 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4995 ConstantInt *CaseVal = CI.getCaseValue();
4996 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4997 MinCaseVal = CaseVal;
4998 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4999 MaxCaseVal = CaseVal;
5000
5001 // Resulting value at phi nodes for this case value.
Dehao Chenf6c00832016-05-18 19:44:21 +00005002 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> ResultsTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005003 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00005004 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005005 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005006 return false;
5007
5008 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00005009 for (const auto &I : Results) {
5010 PHINode *PHI = I.first;
5011 Constant *Value = I.second;
5012 if (!ResultLists.count(PHI))
5013 PHIs.push_back(PHI);
5014 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005015 }
5016 }
5017
Hans Wennborgac114a32014-01-12 00:44:41 +00005018 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00005019 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00005020 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5021 }
5022
5023 uint64_t NumResults = ResultLists[PHIs[0]].size();
5024 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
5025 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
5026 bool TableHasHoles = (NumResults < TableSize);
5027
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005028 // If the table has holes, we need a constant result for the default case
5029 // or a bitmask that fits in a register.
Dehao Chenf6c00832016-05-18 19:44:21 +00005030 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00005031 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005032 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00005033
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005034 bool NeedMask = (TableHasHoles && !HasDefaultResults);
5035 if (NeedMask) {
5036 // As an extra penalty for the validity test we require more cases.
Dehao Chenf6c00832016-05-18 19:44:21 +00005037 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005038 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005039 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005040 return false;
5041 }
Hans Wennborgac114a32014-01-12 00:44:41 +00005042
Hans Wennborga6a11a92014-11-18 02:37:11 +00005043 for (const auto &I : DefaultResultsList) {
5044 PHINode *PHI = I.first;
5045 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00005046 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005047 }
5048
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005049 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005050 return false;
5051
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005052 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00005053 Module &Mod = *CommonDest->getParent()->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00005054 BasicBlock *LookupBB = BasicBlock::Create(
5055 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005056
Michael Gottesmanc024f322013-10-20 07:04:37 +00005057 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005058 Builder.SetInsertPoint(SI);
Dehao Chenf6c00832016-05-18 19:44:21 +00005059 Value *TableIndex =
5060 Builder.CreateSub(SI->getCondition(), MinCaseVal, "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00005061
5062 // Compute the maximum table size representable by the integer type we are
5063 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005064 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00005065 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00005066 assert(MaxTableSize >= TableSize &&
5067 "It is impossible for a switch to have more entries than the max "
5068 "representable value of its input integer type's size.");
5069
Hans Wennborgb64cb272015-01-26 19:52:34 +00005070 // If the default destination is unreachable, or if the lookup table covers
5071 // all values of the conditional variable, branch directly to the lookup table
5072 // BB. Otherwise, check that the condition is within the case range.
5073 const bool DefaultIsReachable =
5074 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5075 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005076 BranchInst *RangeCheckBranch = nullptr;
5077
Hans Wennborgb64cb272015-01-26 19:52:34 +00005078 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00005079 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00005080 // Note: We call removeProdecessor later since we need to be able to get the
5081 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00005082 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00005083 Value *Cmp = Builder.CreateICmpULT(
5084 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
5085 RangeCheckBranch =
5086 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00005087 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005088
5089 // Populate the BB that does the lookups.
5090 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005091
5092 if (NeedMask) {
5093 // Before doing the lookup we do the hole check.
5094 // The LookupBB is therefore re-purposed to do the hole check
5095 // and we create a new LookupBB.
5096 BasicBlock *MaskBB = LookupBB;
5097 MaskBB->setName("switch.hole_check");
Dehao Chenf6c00832016-05-18 19:44:21 +00005098 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
5099 CommonDest->getParent(), CommonDest);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005100
Juergen Ributzkac9591e92014-11-17 19:39:56 +00005101 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
5102 // unnecessary illegal types.
5103 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
5104 APInt MaskInt(TableSizePowOf2, 0);
5105 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005106 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005107 const ResultListTy &ResultList = ResultLists[PHIs[0]];
5108 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005109 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
5110 .getLimitedValue();
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005111 MaskInt |= One << Idx;
5112 }
5113 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
5114
5115 // Get the TableIndex'th bit of the bitmask.
5116 // If this bit is 0 (meaning hole) jump to the default destination,
5117 // else continue with table lookup.
5118 IntegerType *MapTy = TableMask->getType();
Dehao Chenf6c00832016-05-18 19:44:21 +00005119 Value *MaskIndex =
5120 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
5121 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
5122 Value *LoBit = Builder.CreateTrunc(
5123 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005124 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
5125
5126 Builder.SetInsertPoint(LookupBB);
5127 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
5128 }
5129
Hans Wennborg86ac6302015-04-24 20:57:56 +00005130 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5131 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
5132 // do not delete PHINodes here.
5133 SI->getDefaultDest()->removePredecessor(SI->getParent(),
5134 /*DontDeleteUselessPHIs=*/true);
5135 }
5136
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005137 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00005138 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
5139 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00005140 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005141
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005142 // If using a bitmask, use any value to fill the lookup table holes.
5143 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00005144 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00005145
Manman Ren4d189fb2014-07-24 21:13:20 +00005146 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005147
Hans Wennborgf744fa92012-09-19 14:24:21 +00005148 // If the result is used to return immediately from the function, we want to
5149 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005150 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5151 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00005152 Builder.CreateRet(Result);
5153 ReturnedEarly = true;
5154 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005155 }
5156
Erik Eckstein0d86c762014-11-27 15:13:14 +00005157 // Do a small peephole optimization: re-use the switch table compare if
5158 // possible.
5159 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5160 BasicBlock *PhiBlock = PHI->getParent();
5161 // Search for compare instructions which use the phi.
5162 for (auto *User : PHI->users()) {
5163 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
5164 }
5165 }
5166
Hans Wennborgf744fa92012-09-19 14:24:21 +00005167 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005168 }
5169
5170 if (!ReturnedEarly)
5171 Builder.CreateBr(CommonDest);
5172
5173 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005174 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005175 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00005176
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005177 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00005178 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005179 Succ->removePredecessor(SI->getParent());
5180 }
5181 SI->eraseFromParent();
5182
5183 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005184 if (NeedMask)
5185 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005186 return true;
5187}
5188
James Molloyb2e436d2016-08-01 07:45:11 +00005189static bool isSwitchDense(ArrayRef<int64_t> Values) {
5190 // See also SelectionDAGBuilder::isDense(), which this function was based on.
5191 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
5192 uint64_t Range = Diff + 1;
5193 uint64_t NumCases = Values.size();
5194 // 40% is the default density for building a jump table in optsize/minsize mode.
5195 uint64_t MinDensity = 40;
Junmo Parkdb8f6ee2016-08-02 04:38:27 +00005196
James Molloyb2e436d2016-08-01 07:45:11 +00005197 return NumCases * 100 >= Range * MinDensity;
5198}
5199
5200// Try and transform a switch that has "holes" in it to a contiguous sequence
5201// of cases.
5202//
5203// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
5204// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
5205//
5206// This converts a sparse switch into a dense switch which allows better
5207// lowering and could also allow transforming into a lookup table.
5208static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
5209 const DataLayout &DL,
5210 const TargetTransformInfo &TTI) {
5211 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
5212 if (CondTy->getIntegerBitWidth() > 64 ||
5213 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
5214 return false;
5215 // Only bother with this optimization if there are more than 3 switch cases;
5216 // SDAG will only bother creating jump tables for 4 or more cases.
5217 if (SI->getNumCases() < 4)
5218 return false;
5219
5220 // This transform is agnostic to the signedness of the input or case values. We
5221 // can treat the case values as signed or unsigned. We can optimize more common
5222 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
5223 // as signed.
5224 SmallVector<int64_t,4> Values;
5225 for (auto &C : SI->cases())
5226 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
5227 std::sort(Values.begin(), Values.end());
5228
5229 // If the switch is already dense, there's nothing useful to do here.
5230 if (isSwitchDense(Values))
5231 return false;
5232
5233 // First, transform the values such that they start at zero and ascend.
5234 int64_t Base = Values[0];
5235 for (auto &V : Values)
5236 V -= Base;
5237
5238 // Now we have signed numbers that have been shifted so that, given enough
5239 // precision, there are no negative values. Since the rest of the transform
5240 // is bitwise only, we switch now to an unsigned representation.
5241 uint64_t GCD = 0;
5242 for (auto &V : Values)
5243 GCD = llvm::GreatestCommonDivisor64(GCD, (uint64_t)V);
5244
5245 // This transform can be done speculatively because it is so cheap - it results
5246 // in a single rotate operation being inserted. This can only happen if the
5247 // factor extracted is a power of 2.
5248 // FIXME: If the GCD is an odd number we can multiply by the multiplicative
5249 // inverse of GCD and then perform this transform.
5250 // FIXME: It's possible that optimizing a switch on powers of two might also
5251 // be beneficial - flag values are often powers of two and we could use a CLZ
5252 // as the key function.
5253 if (GCD <= 1 || !llvm::isPowerOf2_64(GCD))
5254 // No common divisor found or too expensive to compute key function.
5255 return false;
5256
5257 unsigned Shift = llvm::Log2_64(GCD);
5258 for (auto &V : Values)
5259 V = (int64_t)((uint64_t)V >> Shift);
5260
5261 if (!isSwitchDense(Values))
5262 // Transform didn't create a dense switch.
5263 return false;
5264
5265 // The obvious transform is to shift the switch condition right and emit a
5266 // check that the condition actually cleanly divided by GCD, i.e.
5267 // C & (1 << Shift - 1) == 0
5268 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
5269 //
5270 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
5271 // shift and puts the shifted-off bits in the uppermost bits. If any of these
5272 // are nonzero then the switch condition will be very large and will hit the
5273 // default case.
Junmo Parkdb8f6ee2016-08-02 04:38:27 +00005274
James Molloyb2e436d2016-08-01 07:45:11 +00005275 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
5276 Builder.SetInsertPoint(SI);
5277 auto *ShiftC = ConstantInt::get(Ty, Shift);
5278 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
Benjamin Krameraa160c22016-08-05 14:55:02 +00005279 auto *LShr = Builder.CreateLShr(Sub, ShiftC);
5280 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
5281 auto *Rot = Builder.CreateOr(LShr, Shl);
James Molloyb2e436d2016-08-01 07:45:11 +00005282 SI->replaceUsesOfWith(SI->getCondition(), Rot);
5283
James Molloybade86c2016-08-01 09:34:48 +00005284 for (SwitchInst::CaseIt C = SI->case_begin(), E = SI->case_end(); C != E;
5285 ++C) {
James Molloyb2e436d2016-08-01 07:45:11 +00005286 auto *Orig = C.getCaseValue();
5287 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
James Molloybade86c2016-08-01 09:34:48 +00005288 C.setValue(
5289 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
James Molloyb2e436d2016-08-01 07:45:11 +00005290 }
5291 return true;
5292}
5293
Devang Patela7ec47d2011-05-18 20:35:38 +00005294bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005295 BasicBlock *BB = SI->getParent();
5296
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005297 if (isValueEqualityComparison(SI)) {
5298 // If we only have one predecessor, and if it is a branch on this value,
5299 // see if that predecessor totally determines the outcome of this switch.
5300 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5301 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005302 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00005303
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005304 Value *Cond = SI->getCondition();
5305 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
5306 if (SimplifySwitchOnSelect(SI, Select))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005307 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00005308
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005309 // If the block only contains the switch, see if we can fold the block
5310 // away into any preds.
5311 BasicBlock::iterator BBI = BB->begin();
5312 // Ignore dbg intrinsics.
5313 while (isa<DbgInfoIntrinsic>(BBI))
5314 ++BBI;
5315 if (SI == &*BBI)
5316 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005317 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005318 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00005319
5320 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00005321 if (TurnSwitchRangeIntoICmp(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005322 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00005323
5324 // Remove unreachable cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005325 if (EliminateDeadSwitchCases(SI, AC, DL))
5326 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00005327
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005328 if (SwitchToSelect(SI, Builder, AC, DL))
5329 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00005330
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00005331 if (ForwardSwitchConditionToPHI(SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005332 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00005333
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005334 if (SwitchToLookupTable(SI, Builder, DL, TTI))
5335 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005336
James Molloyb2e436d2016-08-01 07:45:11 +00005337 if (ReduceSwitchRange(SI, Builder, DL, TTI))
5338 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5339
Chris Lattner25c3af32010-12-13 06:25:44 +00005340 return false;
5341}
5342
5343bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
5344 BasicBlock *BB = IBI->getParent();
5345 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005346
Chris Lattner25c3af32010-12-13 06:25:44 +00005347 // Eliminate redundant destinations.
5348 SmallPtrSet<Value *, 8> Succs;
5349 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
5350 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00005351 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005352 Dest->removePredecessor(BB);
5353 IBI->removeDestination(i);
Dehao Chenf6c00832016-05-18 19:44:21 +00005354 --i;
5355 --e;
Chris Lattner25c3af32010-12-13 06:25:44 +00005356 Changed = true;
5357 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005358 }
Chris Lattner25c3af32010-12-13 06:25:44 +00005359
5360 if (IBI->getNumDestinations() == 0) {
5361 // If the indirectbr has no successors, change it to unreachable.
5362 new UnreachableInst(IBI->getContext(), IBI);
5363 EraseTerminatorInstAndDCECond(IBI);
5364 return true;
5365 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005366
Chris Lattner25c3af32010-12-13 06:25:44 +00005367 if (IBI->getNumDestinations() == 1) {
5368 // If the indirectbr has one successor, change it to a direct branch.
5369 BranchInst::Create(IBI->getDestination(0), IBI);
5370 EraseTerminatorInstAndDCECond(IBI);
5371 return true;
5372 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005373
Chris Lattner25c3af32010-12-13 06:25:44 +00005374 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
5375 if (SimplifyIndirectBrOnSelect(IBI, SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005376 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005377 }
5378 return Changed;
5379}
5380
Philip Reames2b969d72015-03-24 22:28:45 +00005381/// Given an block with only a single landing pad and a unconditional branch
5382/// try to find another basic block which this one can be merged with. This
5383/// handles cases where we have multiple invokes with unique landing pads, but
5384/// a shared handler.
5385///
5386/// We specifically choose to not worry about merging non-empty blocks
5387/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
5388/// practice, the optimizer produces empty landing pad blocks quite frequently
5389/// when dealing with exception dense code. (see: instcombine, gvn, if-else
5390/// sinking in this file)
5391///
5392/// This is primarily a code size optimization. We need to avoid performing
5393/// any transform which might inhibit optimization (such as our ability to
5394/// specialize a particular handler via tail commoning). We do this by not
5395/// merging any blocks which require us to introduce a phi. Since the same
5396/// values are flowing through both blocks, we don't loose any ability to
5397/// specialize. If anything, we make such specialization more likely.
5398///
5399/// TODO - This transformation could remove entries from a phi in the target
5400/// block when the inputs in the phi are the same for the two blocks being
5401/// merged. In some cases, this could result in removal of the PHI entirely.
5402static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
5403 BasicBlock *BB) {
5404 auto Succ = BB->getUniqueSuccessor();
5405 assert(Succ);
5406 // If there's a phi in the successor block, we'd likely have to introduce
5407 // a phi into the merged landing pad block.
5408 if (isa<PHINode>(*Succ->begin()))
5409 return false;
5410
5411 for (BasicBlock *OtherPred : predecessors(Succ)) {
5412 if (BB == OtherPred)
5413 continue;
5414 BasicBlock::iterator I = OtherPred->begin();
5415 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
5416 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
5417 continue;
Dehao Chenf6c00832016-05-18 19:44:21 +00005418 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {
5419 }
Philip Reames2b969d72015-03-24 22:28:45 +00005420 BranchInst *BI2 = dyn_cast<BranchInst>(I);
5421 if (!BI2 || !BI2->isIdenticalTo(BI))
5422 continue;
5423
David Majnemer1efa23d2016-02-20 01:07:45 +00005424 // We've found an identical block. Update our predecessors to take that
Philip Reames2b969d72015-03-24 22:28:45 +00005425 // path instead and make ourselves dead.
5426 SmallSet<BasicBlock *, 16> Preds;
5427 Preds.insert(pred_begin(BB), pred_end(BB));
5428 for (BasicBlock *Pred : Preds) {
5429 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
Dehao Chenf6c00832016-05-18 19:44:21 +00005430 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
5431 "unexpected successor");
Philip Reames2b969d72015-03-24 22:28:45 +00005432 II->setUnwindDest(OtherPred);
5433 }
5434
5435 // The debug info in OtherPred doesn't cover the merged control flow that
5436 // used to go through BB. We need to delete it or update it.
Dehao Chenf6c00832016-05-18 19:44:21 +00005437 for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
5438 Instruction &Inst = *I;
5439 I++;
Philip Reames2b969d72015-03-24 22:28:45 +00005440 if (isa<DbgInfoIntrinsic>(Inst))
5441 Inst.eraseFromParent();
5442 }
5443
5444 SmallSet<BasicBlock *, 16> Succs;
5445 Succs.insert(succ_begin(BB), succ_end(BB));
5446 for (BasicBlock *Succ : Succs) {
5447 Succ->removePredecessor(BB);
5448 }
5449
5450 IRBuilder<> Builder(BI);
5451 Builder.CreateUnreachable();
5452 BI->eraseFromParent();
5453 return true;
5454 }
5455 return false;
5456}
5457
Dehao Chenf6c00832016-05-18 19:44:21 +00005458bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI,
5459 IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005460 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005461
Manman Ren93ab6492012-09-20 22:37:36 +00005462 if (SinkCommon && SinkThenElseCodeToEnd(BI))
5463 return true;
Reid Klecknerbca59d22016-05-02 19:43:22 +00005464
5465 // If the Terminator is the only non-phi instruction, simplify the block.
5466 // if LoopHeader is provided, check if the block is a loop header
Hyojin Sung4673f102016-03-29 04:08:57 +00005467 // (This is for early invocations before loop simplify and vectorization
5468 // to keep canonical loop forms for nested loops.
5469 // These blocks can be eliminated when the pass is invoked later
5470 // in the back-end.)
Reid Klecknerbca59d22016-05-02 19:43:22 +00005471 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00005472 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
Hans Wennborge9134892016-04-11 20:35:01 +00005473 (!LoopHeaders || !LoopHeaders->count(BB)) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00005474 TryToSimplifyUncondBranchFromEmptyBlock(BB))
5475 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005476
Chris Lattner25c3af32010-12-13 06:25:44 +00005477 // If the only instruction in the block is a seteq/setne comparison
5478 // against a constant, try to simplify the block.
5479 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5480 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5481 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5482 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005483 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005484 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
5485 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00005486 return true;
5487 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005488
Philip Reames2b969d72015-03-24 22:28:45 +00005489 // See if we can merge an empty landing pad block with another which is
5490 // equivalent.
5491 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005492 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {
5493 }
5494 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
Philip Reames2b969d72015-03-24 22:28:45 +00005495 return true;
5496 }
5497
Manman Rend33f4ef2012-06-13 05:43:29 +00005498 // If this basic block is ONLY a compare and a branch, and if a predecessor
5499 // branches to us and our successor, fold the comparison into the
5500 // predecessor and use logical operations to update the incoming value
5501 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005502 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5503 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005504 return false;
5505}
5506
James Molloy4de84dd2015-11-04 15:28:04 +00005507static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5508 BasicBlock *PredPred = nullptr;
5509 for (auto *P : predecessors(BB)) {
5510 BasicBlock *PPred = P->getSinglePredecessor();
5511 if (!PPred || (PredPred && PredPred != PPred))
5512 return nullptr;
5513 PredPred = PPred;
5514 }
5515 return PredPred;
5516}
Chris Lattner25c3af32010-12-13 06:25:44 +00005517
Devang Patela7ec47d2011-05-18 20:35:38 +00005518bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005519 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005520
Chris Lattner25c3af32010-12-13 06:25:44 +00005521 // Conditional branch
5522 if (isValueEqualityComparison(BI)) {
5523 // If we only have one predecessor, and if it is a branch on this value,
5524 // see if that predecessor totally determines the outcome of this
5525 // switch.
5526 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00005527 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005528 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005529
Chris Lattner25c3af32010-12-13 06:25:44 +00005530 // This block must be empty, except for the setcond inst, if it exists.
5531 // Ignore dbg intrinsics.
5532 BasicBlock::iterator I = BB->begin();
5533 // Ignore dbg intrinsics.
5534 while (isa<DbgInfoIntrinsic>(I))
5535 ++I;
5536 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00005537 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005538 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Dehao Chenf6c00832016-05-18 19:44:21 +00005539 } else if (&*I == cast<Instruction>(BI->getCondition())) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005540 ++I;
5541 // Ignore dbg intrinsics.
5542 while (isa<DbgInfoIntrinsic>(I))
5543 ++I;
Devang Patel58380552011-05-18 20:53:17 +00005544 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005545 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005546 }
5547 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005548
Chris Lattner25c3af32010-12-13 06:25:44 +00005549 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005550 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00005551 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005552
Chad Rosier4ab37c02016-05-06 14:25:14 +00005553 // If this basic block has a single dominating predecessor block and the
5554 // dominating block's condition implies BI's condition, we know the direction
5555 // of the BI branch.
5556 if (BasicBlock *Dom = BB->getSinglePredecessor()) {
5557 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
5558 if (PBI && PBI->isConditional() &&
5559 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
5560 (PBI->getSuccessor(0) == BB || PBI->getSuccessor(1) == BB)) {
5561 bool CondIsFalse = PBI->getSuccessor(1) == BB;
5562 Optional<bool> Implication = isImpliedCondition(
5563 PBI->getCondition(), BI->getCondition(), DL, CondIsFalse);
5564 if (Implication) {
5565 // Turn this into a branch on constant.
5566 auto *OldCond = BI->getCondition();
5567 ConstantInt *CI = *Implication
5568 ? ConstantInt::getTrue(BB->getContext())
5569 : ConstantInt::getFalse(BB->getContext());
5570 BI->setCondition(CI);
5571 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
5572 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5573 }
5574 }
5575 }
5576
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00005577 // If this basic block is ONLY a compare and a branch, and if a predecessor
5578 // branches to us and one of our successors, fold the comparison into the
5579 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005580 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5581 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005582
Chris Lattner25c3af32010-12-13 06:25:44 +00005583 // We have a conditional branch to two blocks that are only reachable
5584 // from BI. We know that the condbr dominates the two blocks, so see if
5585 // there is any identical code in the "then" and "else" blocks. If so, we
5586 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00005587 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5588 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005589 if (HoistThenElseCodeToIf(BI, TTI))
5590 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005591 } else {
5592 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005593 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00005594 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5595 if (Succ0TI->getNumSuccessors() == 1 &&
5596 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005597 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
5598 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005599 }
Craig Topperf40110f2014-04-25 05:29:35 +00005600 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005601 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005602 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00005603 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5604 if (Succ1TI->getNumSuccessors() == 1 &&
5605 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005606 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
5607 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005608 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005609
Chris Lattner25c3af32010-12-13 06:25:44 +00005610 // If this is a branch on a phi node in the current block, thread control
5611 // through this block if any PHI node entries are constants.
5612 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5613 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005614 if (FoldCondBranchOnPHI(BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005615 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005616
Chris Lattner25c3af32010-12-13 06:25:44 +00005617 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00005618 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5619 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00005620 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00005621 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005622 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005623
James Molloy4de84dd2015-11-04 15:28:04 +00005624 // Look for diamond patterns.
5625 if (MergeCondStores)
5626 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5627 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5628 if (PBI != BI && PBI->isConditional())
5629 if (mergeConditionalStores(PBI, BI))
5630 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Dehao Chenf6c00832016-05-18 19:44:21 +00005631
Chris Lattner25c3af32010-12-13 06:25:44 +00005632 return false;
5633}
5634
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005635/// Check if passing a value to an instruction will cause undefined behavior.
5636static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5637 Constant *C = dyn_cast<Constant>(V);
5638 if (!C)
5639 return false;
5640
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005641 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005642 return false;
5643
David Majnemer1fea77c2016-06-25 07:37:27 +00005644 if (C->isNullValue() || isa<UndefValue>(C)) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005645 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00005646 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005647
5648 // Now make sure that there are no instructions in between that can alter
5649 // control flow (eg. calls)
Duncan P. N. Exon Smith0a12729f2016-08-16 23:57:56 +00005650 for (BasicBlock::iterator
5651 i = ++BasicBlock::iterator(I),
5652 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
5653 i != UI; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00005654 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005655 return false;
5656
5657 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5658 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5659 if (GEP->getPointerOperand() == I)
5660 return passingValueIsAlwaysUndefined(V, GEP);
5661
5662 // Look through bitcasts.
5663 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5664 return passingValueIsAlwaysUndefined(V, BC);
5665
Benjamin Kramer0655b782011-08-26 02:25:55 +00005666 // Load from null is undefined.
5667 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005668 if (!LI->isVolatile())
5669 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005670
Benjamin Kramer0655b782011-08-26 02:25:55 +00005671 // Store to null is undefined.
5672 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005673 if (!SI->isVolatile())
Dehao Chenf6c00832016-05-18 19:44:21 +00005674 return SI->getPointerAddressSpace() == 0 &&
5675 SI->getPointerOperand() == I;
David Majnemer1fea77c2016-06-25 07:37:27 +00005676
5677 // A call to null is undefined.
5678 if (auto CS = CallSite(Use))
5679 return CS.getCalledValue() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005680 }
5681 return false;
5682}
5683
5684/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005685/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005686static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5687 for (BasicBlock::iterator i = BB->begin();
5688 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5689 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5690 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5691 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5692 IRBuilder<> Builder(T);
5693 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5694 BB->removePredecessor(PHI->getIncomingBlock(i));
5695 // Turn uncoditional branches into unreachables and remove the dead
5696 // destination from conditional branches.
5697 if (BI->isUnconditional())
5698 Builder.CreateUnreachable();
5699 else
Dehao Chenf6c00832016-05-18 19:44:21 +00005700 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
5701 : BI->getSuccessor(0));
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005702 BI->eraseFromParent();
5703 return true;
5704 }
5705 // TODO: SwitchInst.
5706 }
5707
5708 return false;
5709}
5710
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005711bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00005712 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00005713
Chris Lattnerd7beca32010-12-14 06:17:25 +00005714 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00005715 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00005716
Dan Gohman4a63fad2010-08-14 00:29:42 +00005717 // Remove basic blocks that have no predecessors (except the entry block)...
5718 // or that just have themself as a predecessor. These are unreachable.
Dehao Chenf6c00832016-05-18 19:44:21 +00005719 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00005720 BB->getSinglePredecessor() == BB) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00005721 DEBUG(dbgs() << "Removing BB: \n" << *BB);
5722 DeleteDeadBlock(BB);
5723 return true;
Chris Lattner466a0492002-05-21 20:50:24 +00005724 }
5725
Chris Lattner031340a2003-08-17 19:41:53 +00005726 // Check to see if we can constant propagate this terminator instruction
5727 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00005728 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00005729
Dan Gohman1a951062009-10-30 22:39:04 +00005730 // Check for and eliminate duplicate PHI nodes in this block.
5731 Changed |= EliminateDuplicatePHINodes(BB);
5732
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005733 // Check for and remove branches that will always cause undefined behavior.
5734 Changed |= removeUndefIntroducingPredecessor(BB);
5735
Chris Lattner2e3832d2010-12-13 05:10:48 +00005736 // Merge basic blocks into their predecessor if there is only one distinct
5737 // pred, and if there is only one distinct successor of the predecessor, and
5738 // if there are no PHI nodes.
5739 //
5740 if (MergeBlockIntoPredecessor(BB))
5741 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005742
Devang Patel15ad6762011-05-18 18:01:27 +00005743 IRBuilder<> Builder(BB);
5744
Dan Gohman20af5a02008-03-11 21:53:06 +00005745 // If there is a trivial two-entry PHI node in this basic block, and we can
5746 // eliminate it, do so now.
5747 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5748 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005749 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00005750
Devang Patela7ec47d2011-05-18 20:35:38 +00005751 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00005752 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00005753 if (BI->isUnconditional()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005754 if (SimplifyUncondBranch(BI, Builder))
5755 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005756 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00005757 if (SimplifyCondBranch(BI, Builder))
5758 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005759 }
5760 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005761 if (SimplifyReturn(RI, Builder))
5762 return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00005763 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005764 if (SimplifyResume(RI, Builder))
5765 return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00005766 } else if (CleanupReturnInst *RI =
Dehao Chenf6c00832016-05-18 19:44:21 +00005767 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5768 if (SimplifyCleanupReturn(RI))
5769 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005770 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005771 if (SimplifySwitch(SI, Builder))
5772 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005773 } else if (UnreachableInst *UI =
Dehao Chenf6c00832016-05-18 19:44:21 +00005774 dyn_cast<UnreachableInst>(BB->getTerminator())) {
5775 if (SimplifyUnreachable(UI))
5776 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005777 } else if (IndirectBrInst *IBI =
Dehao Chenf6c00832016-05-18 19:44:21 +00005778 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
5779 if (SimplifyIndirectBr(IBI))
5780 return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00005781 }
5782
Chris Lattner031340a2003-08-17 19:41:53 +00005783 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00005784}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005785
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005786/// This function is used to do simplification of a CFG.
5787/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005788/// eliminates unreachable basic blocks, and does other "peephole" optimization
5789/// of the CFG. It returns true if a modification was made.
5790///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005791bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Hyojin Sung4673f102016-03-29 04:08:57 +00005792 unsigned BonusInstThreshold, AssumptionCache *AC,
5793 SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005794 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
Dehao Chenf6c00832016-05-18 19:44:21 +00005795 BonusInstThreshold, AC, LoopHeaders)
5796 .run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005797}