blob: e5da77e6319f1628b6507f54518deb8450fbe08b [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 Molloye6566422016-09-01 07:45:25 +0000177static bool
178SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2,
James Molloy21744682016-09-01 09:01:34 +0000179 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000180 if (SI1 == SI2)
181 return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000182
Chris Lattner76dc2042005-08-03 00:19:45 +0000183 // It is not safe to merge these two switch instructions if they have a common
184 // successor, and if that successor has a PHI node, and if *that* PHI node has
185 // conflicting incoming values from the two switch blocks.
186 BasicBlock *SI1BB = SI1->getParent();
187 BasicBlock *SI2BB = SI2->getParent();
James Molloy3c1137c2016-08-31 13:32:28 +0000188
James Molloye6566422016-09-01 07:45:25 +0000189 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
190 bool Fail = false;
Sanjay Patel5781d842016-03-12 16:52:17 +0000191 for (BasicBlock *Succ : successors(SI2BB))
192 if (SI1Succs.count(Succ))
193 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000194 PHINode *PN = cast<PHINode>(BBI);
195 if (PN->getIncomingValueForBlock(SI1BB) !=
James Molloye6566422016-09-01 07:45:25 +0000196 PN->getIncomingValueForBlock(SI2BB)) {
197 if (FailBlocks)
198 FailBlocks->insert(Succ);
199 Fail = true;
200 }
Chris Lattner76dc2042005-08-03 00:19:45 +0000201 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000202
James Molloye6566422016-09-01 07:45:25 +0000203 return !Fail;
Chris Lattner76dc2042005-08-03 00:19:45 +0000204}
205
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000206/// Return true if it is safe and profitable to merge these two terminator
207/// instructions together, where SI1 is an unconditional branch. PhiNodes will
208/// store all PHI nodes in common successors.
Dehao Chenf6c00832016-05-18 19:44:21 +0000209static bool
210isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2,
211 Instruction *Cond,
212 SmallVectorImpl<PHINode *> &PhiNodes) {
213 if (SI1 == SI2)
214 return false; // Can't merge with self!
Manman Rend33f4ef2012-06-13 05:43:29 +0000215 assert(SI1->isUnconditional() && SI2->isConditional());
216
217 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000218 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000219 // 1> We have a constant incoming value for the conditional branch;
220 // 2> We have "Cond" as the incoming value for the unconditional branch;
221 // 3> SI2->getCondition() and Cond have same operands.
222 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
Dehao Chenf6c00832016-05-18 19:44:21 +0000223 if (!Ci2)
224 return false;
Manman Rend33f4ef2012-06-13 05:43:29 +0000225 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
226 Cond->getOperand(1) == Ci2->getOperand(1)) &&
227 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
228 Cond->getOperand(1) == Ci2->getOperand(0)))
229 return false;
230
231 BasicBlock *SI1BB = SI1->getParent();
232 BasicBlock *SI2BB = SI2->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000233 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Sanjay Patel5781d842016-03-12 16:52:17 +0000234 for (BasicBlock *Succ : successors(SI2BB))
235 if (SI1Succs.count(Succ))
236 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
Manman Rend33f4ef2012-06-13 05:43:29 +0000237 PHINode *PN = cast<PHINode>(BBI);
238 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000239 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000240 return false;
241 PhiNodes.push_back(PN);
242 }
243 return true;
244}
245
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000246/// Update PHI nodes in Succ to indicate that there will now be entries in it
247/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
248/// will be the same as those coming in from ExistPred, an existing predecessor
249/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000250static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
251 BasicBlock *ExistPred) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000252 if (!isa<PHINode>(Succ->begin()))
253 return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000254
Chris Lattner80b03a12008-07-13 22:23:11 +0000255 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +0000256 for (BasicBlock::iterator I = Succ->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
Chris Lattner80b03a12008-07-13 22:23:11 +0000257 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000258}
259
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000260/// Compute an abstract "cost" of speculating the given instruction,
261/// which is assumed to be safe to speculate. TCC_Free means cheap,
262/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000263/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000264static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000265 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000266 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000267 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000268 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000269}
Sanjay Patelf9b77632015-09-15 15:24:42 +0000270
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000271/// If we have a merge point of an "if condition" as accepted above,
272/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000273/// don't handle the true generality of domination here, just a special case
274/// which works well enough for us.
275///
276/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000277/// see if V (which must be an instruction) and its recursive operands
278/// that do not dominate BB have a combined cost lower than CostRemaining and
279/// are non-trapping. If both are true, the instruction is inserted into the
280/// set and true is returned.
281///
282/// The cost for most non-trapping instructions is defined as 1 except for
283/// Select whose cost is 2.
284///
285/// After this function returns, CostRemaining is decreased by the cost of
286/// V plus its non-dominating operands. If that cost is greater than
287/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000288static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Dehao Chenf6c00832016-05-18 19:44:21 +0000289 SmallPtrSetImpl<Instruction *> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000290 unsigned &CostRemaining,
David Majnemerfccf5c62016-01-27 02:59:41 +0000291 const TargetTransformInfo &TTI,
292 unsigned Depth = 0) {
Sanjay Patel5264cc72016-01-27 19:22:45 +0000293 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
294 // so limit the recursion depth.
295 // TODO: While this recursion limit does prevent pathological behavior, it
296 // would be better to track visited instructions to avoid cycles.
297 if (Depth == MaxSpeculationDepth)
298 return false;
299
Chris Lattner0aa56562004-04-09 22:50:22 +0000300 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000301 if (!I) {
302 // Non-instructions all dominate instructions, but not all constantexprs
303 // can be executed unconditionally.
304 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
305 if (C->canTrap())
306 return false;
307 return true;
308 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000309 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000310
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000311 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000312 // the bottom of this block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000313 if (PBB == BB)
314 return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000315
Chris Lattner0aa56562004-04-09 22:50:22 +0000316 // If this instruction is defined in a block that contains an unconditional
317 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000318 // statement". If not, it definitely dominates the region.
319 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000320 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000321 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000322
Chris Lattner9ac168d2010-12-14 07:41:39 +0000323 // If we aren't allowing aggressive promotion anymore, then don't consider
324 // instructions in the 'if region'.
Dehao Chenf6c00832016-05-18 19:44:21 +0000325 if (!AggressiveInsts)
326 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000327
Peter Collingbournee3511e12011-04-29 18:47:31 +0000328 // If we have seen this instruction before, don't count it again.
Dehao Chenf6c00832016-05-18 19:44:21 +0000329 if (AggressiveInsts->count(I))
330 return true;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000331
Chris Lattner9ac168d2010-12-14 07:41:39 +0000332 // Okay, it looks like the instruction IS in the "condition". Check to
333 // see if it's a cheap instruction to unconditionally compute, and if it
334 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000335 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000336 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000337
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000338 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000339
David Majnemerfccf5c62016-01-27 02:59:41 +0000340 // Allow exactly one instruction to be speculated regardless of its cost
341 // (as long as it is safe to do so).
342 // This is intended to flatten the CFG even if the instruction is a division
343 // or other expensive operation. The speculation of an expensive instruction
344 // is expected to be undone in CodeGenPrepare if the speculation has not
345 // enabled further IR optimizations.
346 if (Cost > CostRemaining &&
347 (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0))
Peter Collingbournee3511e12011-04-29 18:47:31 +0000348 return false;
349
David Majnemerfccf5c62016-01-27 02:59:41 +0000350 // Avoid unsigned wrap.
351 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000352
353 // Okay, we can only really hoist these out if their operands do
354 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000355 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
David Majnemerfccf5c62016-01-27 02:59:41 +0000356 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
357 Depth + 1))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000358 return false;
359 // Okay, it's safe to do this! Remember this instruction.
360 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000361 return true;
362}
Chris Lattner466a0492002-05-21 20:50:24 +0000363
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000364/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000365/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000366static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000367 // Normal constant int.
368 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000369 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000370 return CI;
371
372 // This is some kind of pointer constant. Turn it into a pointer-sized
373 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000374 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000375
376 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
377 if (isa<ConstantPointerNull>(V))
378 return ConstantInt::get(PtrTy, 0);
379
380 // IntToPtr const int.
381 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
382 if (CE->getOpcode() == Instruction::IntToPtr)
383 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
384 // The constant is very likely to have the right type already.
385 if (CI->getType() == PtrTy)
386 return CI;
387 else
Dehao Chenf6c00832016-05-18 19:44:21 +0000388 return cast<ConstantInt>(
389 ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000390 }
Craig Topperf40110f2014-04-25 05:29:35 +0000391 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000392}
393
Mehdi Aminiffd01002014-11-20 22:40:25 +0000394namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000395
Mehdi Aminiffd01002014-11-20 22:40:25 +0000396/// Given a chain of or (||) or and (&&) comparison of a value against a
397/// constant, this will try to recover the information required for a switch
398/// structure.
399/// It will depth-first traverse the chain of comparison, seeking for patterns
400/// like %a == 12 or %a < 4 and combine them to produce a set of integer
401/// representing the different cases for the switch.
402/// Note that if the chain is composed of '||' it will build the set of elements
403/// that matches the comparisons (i.e. any of this value validate the chain)
404/// while for a chain of '&&' it will build the set elements that make the test
405/// fail.
406struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000407 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000408 Value *CompValue; /// Value found for the switch comparison
409 Value *Extra; /// Extra clause to be checked before the switch
410 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
411 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000412
Mehdi Aminiffd01002014-11-20 22:40:25 +0000413 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000414 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
415 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
416 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000417 }
418
Mehdi Aminiffd01002014-11-20 22:40:25 +0000419 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000420 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000421 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000422 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000423
Mehdi Aminiffd01002014-11-20 22:40:25 +0000424private:
Mehdi Aminiffd01002014-11-20 22:40:25 +0000425 /// Try to set the current value used for the comparison, it succeeds only if
426 /// it wasn't set before or if the new value is the same as the old one
427 bool setValueOnce(Value *NewVal) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000428 if (CompValue && CompValue != NewVal)
429 return false;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000430 CompValue = NewVal;
431 return (CompValue != nullptr);
432 }
433
434 /// Try to match Instruction "I" as a comparison against a constant and
435 /// populates the array Vals with the set of values that match (or do not
436 /// match depending on isEQ).
437 /// Return false on failure. On success, the Value the comparison matched
438 /// against is placed in CompValue.
439 /// If CompValue is already set, the function is expected to fail if a match
440 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000441 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000442 // If this is an icmp against a constant, handle this as one of the cases.
443 ICmpInst *ICI;
444 ConstantInt *C;
445 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
Dehao Chenf6c00832016-05-18 19:44:21 +0000446 (C = GetConstantInt(I->getOperand(1), DL)))) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000447 return false;
448 }
449
450 Value *RHSVal;
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000451 const APInt *RHSC;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000452
453 // Pattern match a special case
David Majnemerc761afd2016-01-27 02:43:28 +0000454 // (x & ~2^z) == y --> x == y || x == y|2^z
Mehdi Aminiffd01002014-11-20 22:40:25 +0000455 // This undoes a transformation done by instcombine to fuse 2 compares.
Dehao Chenf6c00832016-05-18 19:44:21 +0000456 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000457
458 // It's a little bit hard to see why the following transformations are
459 // correct. Here is a CVC3 program to verify them for 64-bit values:
460
461 /*
462 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
463 x : BITVECTOR(64);
464 y : BITVECTOR(64);
465 z : BITVECTOR(64);
466 mask : BITVECTOR(64) = BVSHL(ONE, z);
467 QUERY( (y & ~mask = y) =>
468 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
469 );
Chuang-Yu Cheng68f7f1c2016-06-24 01:59:00 +0000470 QUERY( (y | mask = y) =>
471 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
472 );
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000473 */
474
475 // Please note that each pattern must be a dual implication (<--> or
476 // iff). One directional implication can create spurious matches. If the
477 // implication is only one-way, an unsatisfiable condition on the left
478 // side can imply a satisfiable condition on the right side. Dual
479 // implication ensures that satisfiable conditions are transformed to
480 // other satisfiable conditions and unsatisfiable conditions are
481 // transformed to other unsatisfiable conditions.
482
483 // Here is a concrete example of a unsatisfiable condition on the left
484 // implying a satisfiable condition on the right:
485 //
486 // mask = (1 << z)
487 // (x & ~mask) == y --> (x == y || x == (y | mask))
488 //
489 // Substituting y = 3, z = 0 yields:
490 // (x & -2) == 3 --> (x == 3 || x == 2)
491
492 // Pattern match a special case:
493 /*
494 QUERY( (y & ~mask = y) =>
495 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
496 );
497 */
Mehdi Aminiffd01002014-11-20 22:40:25 +0000498 if (match(ICI->getOperand(0),
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000499 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
500 APInt Mask = ~*RHSC;
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000501 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000502 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000503 if (!setValueOnce(RHSVal))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000504 return false;
505
506 Vals.push_back(C);
Dehao Chenf6c00832016-05-18 19:44:21 +0000507 Vals.push_back(
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000508 ConstantInt::get(C->getContext(),
509 C->getValue() | Mask));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000510 UsedICmps++;
511 return true;
512 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000513 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000514
Chuang-Yu Cheng68f7f1c2016-06-24 01:59:00 +0000515 // Pattern match a special case:
516 /*
517 QUERY( (y | mask = y) =>
518 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
519 );
520 */
521 if (match(ICI->getOperand(0),
522 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
523 APInt Mask = *RHSC;
524 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
525 // If we already have a value for the switch, it has to match!
526 if (!setValueOnce(RHSVal))
527 return false;
528
529 Vals.push_back(C);
530 Vals.push_back(ConstantInt::get(C->getContext(),
531 C->getValue() & ~Mask));
532 UsedICmps++;
533 return true;
534 }
535 }
536
Mehdi Aminiffd01002014-11-20 22:40:25 +0000537 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000538 if (!setValueOnce(ICI->getOperand(0)))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000539 return false;
540
541 UsedICmps++;
542 Vals.push_back(C);
543 return ICI->getOperand(0);
544 }
545
546 // 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 +0000547 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
548 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000549
550 // Shift the range if the compare is fed by an add. This is the range
551 // compare idiom as emitted by instcombine.
552 Value *CandidateVal = I->getOperand(0);
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000553 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
554 Span = Span.subtract(*RHSC);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000555 CandidateVal = RHSVal;
556 }
557
558 // If this is an and/!= check, then we are looking to build the set of
559 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
560 // x != 0 && x != 1.
561 if (!isEQ)
562 Span = Span.inverse();
563
564 // If there are a ton of values, we don't want to make a ginormous switch.
565 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
566 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000567 }
568
569 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000570 if (!setValueOnce(CandidateVal))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000571 return false;
572
573 // Add all values from the range to the set
574 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
575 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000576
577 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000578 return true;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000579 }
580
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000581 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000582 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
583 /// the value being compared, and stick the list constants into the Vals
584 /// vector.
585 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000586 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000587 Instruction *I = dyn_cast<Instruction>(V);
588 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000589
Mehdi Aminiffd01002014-11-20 22:40:25 +0000590 // Keep a stack (SmallVector for efficiency) for depth-first traversal
591 SmallVector<Value *, 8> DFT;
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000592 SmallPtrSet<Value *, 8> Visited;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000593
Mehdi Aminiffd01002014-11-20 22:40:25 +0000594 // Initialize
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000595 Visited.insert(V);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000596 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000597
Dehao Chenf6c00832016-05-18 19:44:21 +0000598 while (!DFT.empty()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000599 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000600
Mehdi Aminiffd01002014-11-20 22:40:25 +0000601 if (Instruction *I = dyn_cast<Instruction>(V)) {
602 // If it is a || (or && depending on isEQ), process the operands.
603 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000604 if (Visited.insert(I->getOperand(1)).second)
605 DFT.push_back(I->getOperand(1));
606 if (Visited.insert(I->getOperand(0)).second)
607 DFT.push_back(I->getOperand(0));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000608 continue;
609 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000610
Mehdi Aminiffd01002014-11-20 22:40:25 +0000611 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000612 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000613 // Match succeed, continue the loop
614 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000615 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000616
Mehdi Aminiffd01002014-11-20 22:40:25 +0000617 // One element of the sequence of || (or &&) could not be match as a
618 // comparison against the same value as the others.
619 // We allow only one "Extra" case to be checked before the switch
620 if (!Extra) {
621 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000622 continue;
623 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000624 // Failed to parse a proper sequence, abort now
625 CompValue = nullptr;
626 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000627 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000628 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000629};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000630}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000631
Eli Friedmancb61afb2008-12-16 20:54:32 +0000632static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000633 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000634 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
635 Cond = dyn_cast<Instruction>(SI->getCondition());
636 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
637 if (BI->isConditional())
638 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000639 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
640 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000641 }
642
643 TI->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000644 if (Cond)
645 RecursivelyDeleteTriviallyDeadInstructions(Cond);
Eli Friedmancb61afb2008-12-16 20:54:32 +0000646}
647
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000648/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000649/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000650Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000651 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000652 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
653 // Do not permit merging of large switch instructions into their
654 // predecessors unless there is only one predecessor.
Dehao Chenf6c00832016-05-18 19:44:21 +0000655 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
656 pred_end(SI->getParent())) <=
657 128)
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000658 CV = SI->getCondition();
659 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000660 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000661 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000662 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000663 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000664 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000665
666 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000667 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000668 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
669 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000670 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000671 CV = Ptr;
672 }
673 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000674 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000675}
676
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000677/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000678/// decode all of the 'cases' that it represents and return the 'default' block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000679BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
680 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000681 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000682 Cases.reserve(SI->getNumCases());
Dehao Chenf6c00832016-05-18 19:44:21 +0000683 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e;
684 ++i)
685 Cases.push_back(
686 ValueEqualityComparisonCase(i.getCaseValue(), i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000687 return SI->getDefaultDest();
688 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000689
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000690 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000691 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000692 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
Dehao Chenf6c00832016-05-18 19:44:21 +0000693 Cases.push_back(ValueEqualityComparisonCase(
694 GetConstantInt(ICI->getOperand(1), DL), Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000695 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000696}
697
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000698/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000699/// in the list that match the specified block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000700static void
701EliminateBlockCases(BasicBlock *BB,
702 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000703 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000704}
705
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000706/// Return true if there are any keys in C1 that exist in C2 as well.
Dehao Chenf6c00832016-05-18 19:44:21 +0000707static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
708 std::vector<ValueEqualityComparisonCase> &C2) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000709 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
710
711 // Make V1 be smaller than V2.
712 if (V1->size() > V2->size())
713 std::swap(V1, V2);
714
Dehao Chenf6c00832016-05-18 19:44:21 +0000715 if (V1->size() == 0)
716 return false;
Eric Christopherb65acc62012-07-02 23:22:21 +0000717 if (V1->size() == 1) {
718 // Just scan V2.
719 ConstantInt *TheVal = (*V1)[0].Value;
720 for (unsigned i = 0, e = V2->size(); i != e; ++i)
721 if (TheVal == (*V2)[i].Value)
722 return true;
723 }
724
725 // Otherwise, just sort both lists and compare element by element.
726 array_pod_sort(V1->begin(), V1->end());
727 array_pod_sort(V2->begin(), V2->end());
728 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
729 while (i1 != e1 && i2 != e2) {
730 if ((*V1)[i1].Value == (*V2)[i2].Value)
731 return true;
732 if ((*V1)[i1].Value < (*V2)[i2].Value)
733 ++i1;
734 else
735 ++i2;
736 }
737 return false;
738}
739
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000740/// If TI is known to be a terminator instruction and its block is known to
741/// only have a single predecessor block, check to see if that predecessor is
742/// also a value comparison with the same value, and if that comparison
743/// determines the outcome of this comparison. If so, simplify TI. This does a
744/// very limited form of jump threading.
Dehao Chenf6c00832016-05-18 19:44:21 +0000745bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
746 TerminatorInst *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000747 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
Dehao Chenf6c00832016-05-18 19:44:21 +0000748 if (!PredVal)
749 return false; // Not a value comparison in predecessor.
Chris Lattner1cca9592005-02-24 06:17:52 +0000750
751 Value *ThisVal = isValueEqualityComparison(TI);
752 assert(ThisVal && "This isn't a value comparison!!");
Dehao Chenf6c00832016-05-18 19:44:21 +0000753 if (ThisVal != PredVal)
754 return false; // Different predicates.
Chris Lattner1cca9592005-02-24 06:17:52 +0000755
Andrew Trick3051aa12012-08-29 21:46:38 +0000756 // TODO: Preserve branch weight metadata, similarly to how
757 // FoldValueComparisonIntoPredecessors preserves it.
758
Chris Lattner1cca9592005-02-24 06:17:52 +0000759 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000760 std::vector<ValueEqualityComparisonCase> PredCases;
Dehao Chenf6c00832016-05-18 19:44:21 +0000761 BasicBlock *PredDef =
762 GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
763 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000764
Chris Lattner1cca9592005-02-24 06:17:52 +0000765 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000766 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000767 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Dehao Chenf6c00832016-05-18 19:44:21 +0000768 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000769
770 // If TI's block is the default block from Pred's comparison, potentially
771 // simplify TI based on this knowledge.
772 if (PredDef == TI->getParent()) {
773 // If we are here, we know that the value is none of those cases listed in
774 // PredCases. If there are any cases in ThisCases that are in PredCases, we
775 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000776 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000777 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000778
Chris Lattner4088e2b2010-12-13 01:47:07 +0000779 if (isa<BranchInst>(TI)) {
780 // Okay, one of the successors of this condbr is dead. Convert it to a
781 // uncond br.
782 assert(ThisCases.size() == 1 && "Branch can only have one case!");
783 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000784 Instruction *NI = Builder.CreateBr(ThisDef);
Dehao Chenf6c00832016-05-18 19:44:21 +0000785 (void)NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000786
Chris Lattner4088e2b2010-12-13 01:47:07 +0000787 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000788 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000789
Chris Lattner4088e2b2010-12-13 01:47:07 +0000790 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Dehao Chenf6c00832016-05-18 19:44:21 +0000791 << "Through successor TI: " << *TI << "Leaving: " << *NI
792 << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000793
Chris Lattner4088e2b2010-12-13 01:47:07 +0000794 EraseTerminatorInstAndDCECond(TI);
795 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000796 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000797
Chris Lattner4088e2b2010-12-13 01:47:07 +0000798 SwitchInst *SI = cast<SwitchInst>(TI);
799 // Okay, TI has cases that are statically dead, prune them away.
Dehao Chenf6c00832016-05-18 19:44:21 +0000800 SmallPtrSet<Constant *, 16> DeadCases;
Eric Christopherb65acc62012-07-02 23:22:21 +0000801 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
802 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000803
David Greene725c7c32010-01-05 01:26:52 +0000804 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000805 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000806
Manman Ren8691e522012-09-14 21:53:06 +0000807 // Collect branch weights into a vector.
808 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000809 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000810 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
811 if (HasWeight)
812 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
813 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000814 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000815 Weights.push_back(CI->getValue().getZExtValue());
816 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000817 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
818 --i;
819 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000820 if (HasWeight) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000821 std::swap(Weights[i.getCaseIndex() + 1], Weights.back());
Manman Ren8691e522012-09-14 21:53:06 +0000822 Weights.pop_back();
823 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000824 i.getCaseSuccessor()->removePredecessor(TI->getParent());
825 SI->removeCase(i);
826 }
827 }
Manman Ren97c18762012-10-11 22:28:34 +0000828 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000829 SI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +0000830 MDBuilder(SI->getParent()->getContext())
831 .createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000832
833 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000834 return true;
835 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000836
Chris Lattner4088e2b2010-12-13 01:47:07 +0000837 // Otherwise, TI's block must correspond to some matched value. Find out
838 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000839 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000840 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000841 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
842 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000843 if (TIV)
Dehao Chenf6c00832016-05-18 19:44:21 +0000844 return false; // Cannot handle multiple values coming to this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000845 TIV = PredCases[i].Value;
846 }
847 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000848
849 // Okay, we found the one constant that our value can be if we get into TI's
850 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000851 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000852 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
853 if (ThisCases[i].Value == TIV) {
854 TheRealDest = ThisCases[i].Dest;
855 break;
856 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000857
858 // If not handled by any explicit cases, it is handled by the default case.
Dehao Chenf6c00832016-05-18 19:44:21 +0000859 if (!TheRealDest)
860 TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000861
862 // Remove PHI node entries for dead edges.
863 BasicBlock *CheckEdge = TheRealDest;
Sanjay Patel5781d842016-03-12 16:52:17 +0000864 for (BasicBlock *Succ : successors(TIBB))
865 if (Succ != CheckEdge)
866 Succ->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000867 else
Craig Topperf40110f2014-04-25 05:29:35 +0000868 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000869
870 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000871 Instruction *NI = Builder.CreateBr(TheRealDest);
Dehao Chenf6c00832016-05-18 19:44:21 +0000872 (void)NI;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000873
874 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Dehao Chenf6c00832016-05-18 19:44:21 +0000875 << "Through successor TI: " << *TI << "Leaving: " << *NI
876 << "\n");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000877
878 EraseTerminatorInstAndDCECond(TI);
879 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000880}
881
Dale Johannesen7f99d222009-03-12 21:01:11 +0000882namespace {
Dehao Chenf6c00832016-05-18 19:44:21 +0000883/// This class implements a stable ordering of constant
884/// integers that does not depend on their address. This is important for
885/// applications that sort ConstantInt's to ensure uniqueness.
886struct ConstantIntOrdering {
887 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
888 return LHS->getValue().ult(RHS->getValue());
889 }
890};
Dale Johannesen7f99d222009-03-12 21:01:11 +0000891}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000892
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000893static int ConstantIntSortPredicate(ConstantInt *const *P1,
894 ConstantInt *const *P2) {
895 const ConstantInt *LHS = *P1;
896 const ConstantInt *RHS = *P2;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000897 if (LHS == RHS)
Chris Lattnere893e262010-12-15 04:52:41 +0000898 return 0;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000899 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000900}
901
Dehao Chenf6c00832016-05-18 19:44:21 +0000902static inline bool HasBranchWeights(const Instruction *I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000903 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000904 if (ProfMD && ProfMD->getOperand(0))
Dehao Chenf6c00832016-05-18 19:44:21 +0000905 if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
Andrew Trick3051aa12012-08-29 21:46:38 +0000906 return MDS->getString().equals("branch_weights");
907
908 return false;
909}
910
Manman Ren571d9e42012-09-11 17:43:35 +0000911/// Get Weights of a given TerminatorInst, the default weight is at the front
912/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
913/// metadata.
914static void GetBranchWeights(TerminatorInst *TI,
915 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000916 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000917 assert(MD);
918 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000919 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000920 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000921 }
922
Manman Ren571d9e42012-09-11 17:43:35 +0000923 // If TI is a conditional eq, the default case is the false case,
924 // and the corresponding branch-weight data is at index 2. We swap the
925 // default weight to be the first entry.
Dehao Chenf6c00832016-05-18 19:44:21 +0000926 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Manman Ren571d9e42012-09-11 17:43:35 +0000927 assert(Weights.size() == 2);
928 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
929 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
930 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000931 }
932}
933
Sanjay Patel84a0bf62016-05-06 17:51:37 +0000934/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000935static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000936 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
937 if (Max > UINT_MAX) {
938 unsigned Offset = 32 - countLeadingZeros(Max);
939 for (uint64_t &I : Weights)
940 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000941 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000942}
943
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000944/// The specified terminator is a value equality comparison instruction
945/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000946/// See if any of the predecessors of the terminator block are value comparisons
947/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000948bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
949 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000950 BasicBlock *BB = TI->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000951 Value *CV = isValueEqualityComparison(TI); // CondVal
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000952 assert(CV && "Not a comparison?");
953 bool Changed = false;
954
Dehao Chenf6c00832016-05-18 19:44:21 +0000955 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000956 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000957 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000958
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000959 // See if the predecessor is a comparison with the same value.
960 TerminatorInst *PTI = Pred->getTerminator();
Dehao Chenf6c00832016-05-18 19:44:21 +0000961 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000962
James Molloye6566422016-09-01 07:45:25 +0000963 if (PCV == CV && TI != PTI) {
James Molloy21744682016-09-01 09:01:34 +0000964 SmallSetVector<BasicBlock*, 4> FailBlocks;
James Molloye6566422016-09-01 07:45:25 +0000965 if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
966 for (auto *Succ : FailBlocks) {
967 std::vector<BasicBlock*> Blocks = { TI->getParent() };
968 if (!SplitBlockPredecessors(Succ, Blocks, ".fold.split"))
969 return false;
970 }
971 }
972
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000973 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000974 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000975 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
976
Eric Christopherb65acc62012-07-02 23:22:21 +0000977 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000978 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
979
980 // Based on whether the default edge from PTI goes to BB or not, fill in
981 // PredCases and PredDefault with the new switch cases we would like to
982 // build.
Dehao Chenf6c00832016-05-18 19:44:21 +0000983 SmallVector<BasicBlock *, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000984
Andrew Trick3051aa12012-08-29 21:46:38 +0000985 // Update the branch weight metadata along the way
986 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000987 bool PredHasWeights = HasBranchWeights(PTI);
988 bool SuccHasWeights = HasBranchWeights(TI);
989
Manman Ren5e5049d2012-09-14 19:05:19 +0000990 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000991 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000992 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000993 if (Weights.size() != 1 + PredCases.size())
994 PredHasWeights = SuccHasWeights = false;
995 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000996 // If there are no predecessor weights but there are successor weights,
997 // populate Weights with 1, which will later be scaled to the sum of
998 // successor's weights
999 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +00001000
Manman Ren571d9e42012-09-11 17:43:35 +00001001 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +00001002 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +00001003 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +00001004 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +00001005 if (SuccWeights.size() != 1 + BBCases.size())
1006 PredHasWeights = SuccHasWeights = false;
1007 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +00001008 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +00001009
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001010 if (PredDefault == BB) {
1011 // If this is the default destination from PTI, only the edges in TI
1012 // that don't occur in PTI, or that branch to BB will be activated.
Dehao Chenf6c00832016-05-18 19:44:21 +00001013 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +00001014 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1015 if (PredCases[i].Dest != BB)
1016 PTIHandled.insert(PredCases[i].Value);
1017 else {
1018 // The default destination is BB, we don't need explicit targets.
1019 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +00001020
Manman Ren571d9e42012-09-11 17:43:35 +00001021 if (PredHasWeights || SuccHasWeights) {
1022 // Increase weight for the default case.
Dehao Chenf6c00832016-05-18 19:44:21 +00001023 Weights[0] += Weights[i + 1];
1024 std::swap(Weights[i + 1], Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +00001025 Weights.pop_back();
1026 }
1027
Eric Christopherb65acc62012-07-02 23:22:21 +00001028 PredCases.pop_back();
Dehao Chenf6c00832016-05-18 19:44:21 +00001029 --i;
1030 --e;
Eric Christopherb65acc62012-07-02 23:22:21 +00001031 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001032
Eric Christopherb65acc62012-07-02 23:22:21 +00001033 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001034 if (PredDefault != BBDefault) {
1035 PredDefault->removePredecessor(Pred);
1036 PredDefault = BBDefault;
1037 NewSuccessors.push_back(BBDefault);
1038 }
Andrew Trick3051aa12012-08-29 21:46:38 +00001039
Manman Ren571d9e42012-09-11 17:43:35 +00001040 unsigned CasesFromPred = Weights.size();
1041 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +00001042 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1043 if (!PTIHandled.count(BBCases[i].Value) &&
1044 BBCases[i].Dest != BBDefault) {
1045 PredCases.push_back(BBCases[i]);
1046 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +00001047 if (SuccHasWeights || PredHasWeights) {
1048 // The default weight is at index 0, so weight for the ith case
1049 // should be at index i+1. Scale the cases from successor by
1050 // PredDefaultWeight (Weights[0]).
Dehao Chenf6c00832016-05-18 19:44:21 +00001051 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1052 ValidTotalSuccWeight += SuccWeights[i + 1];
Andrew Trick3051aa12012-08-29 21:46:38 +00001053 }
Eric Christopherb65acc62012-07-02 23:22:21 +00001054 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001055
Manman Ren571d9e42012-09-11 17:43:35 +00001056 if (SuccHasWeights || PredHasWeights) {
1057 ValidTotalSuccWeight += SuccWeights[0];
1058 // Scale the cases from predecessor by ValidTotalSuccWeight.
1059 for (unsigned i = 1; i < CasesFromPred; ++i)
1060 Weights[i] *= ValidTotalSuccWeight;
1061 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1062 Weights[0] *= SuccWeights[0];
1063 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001064 } else {
1065 // If this is not the default destination from PSI, only the edges
1066 // in SI that occur in PSI with a destination of BB will be
1067 // activated.
Dehao Chenf6c00832016-05-18 19:44:21 +00001068 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1069 std::map<ConstantInt *, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +00001070 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1071 if (PredCases[i].Dest == BB) {
1072 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +00001073
1074 if (PredHasWeights || SuccHasWeights) {
Dehao Chenf6c00832016-05-18 19:44:21 +00001075 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1076 std::swap(Weights[i + 1], Weights.back());
Manman Rend81b8e82012-09-14 17:29:56 +00001077 Weights.pop_back();
1078 }
1079
Eric Christopherb65acc62012-07-02 23:22:21 +00001080 std::swap(PredCases[i], PredCases.back());
1081 PredCases.pop_back();
Dehao Chenf6c00832016-05-18 19:44:21 +00001082 --i;
1083 --e;
Eric Christopherb65acc62012-07-02 23:22:21 +00001084 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001085
1086 // Okay, now we know which constants were sent to BB from the
1087 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +00001088 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1089 if (PTIHandled.count(BBCases[i].Value)) {
1090 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +00001091 if (PredHasWeights || SuccHasWeights)
1092 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +00001093 PredCases.push_back(BBCases[i]);
1094 NewSuccessors.push_back(BBCases[i].Dest);
Dehao Chenf6c00832016-05-18 19:44:21 +00001095 PTIHandled.erase(
1096 BBCases[i].Value); // This constant is taken care of
Eric Christopherb65acc62012-07-02 23:22:21 +00001097 }
1098
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001099 // If there are any constants vectored to BB that TI doesn't handle,
1100 // they must go to the default destination of TI.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001101 for (ConstantInt *I : PTIHandled) {
Andrew Trick90f50292012-11-15 18:40:29 +00001102 if (PredHasWeights || SuccHasWeights)
Benjamin Kramer135f7352016-06-26 12:28:59 +00001103 Weights.push_back(WeightsForHandled[I]);
1104 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001105 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +00001106 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001107 }
1108
1109 // Okay, at this point, we know which new successor Pred will get. Make
1110 // sure we update the number of entries in the PHI nodes for these
1111 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +00001112 for (BasicBlock *NewSuccessor : NewSuccessors)
1113 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001114
Devang Patel58380552011-05-18 20:53:17 +00001115 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001116 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +00001117 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001118 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +00001119 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001120 }
1121
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001122 // Now that the successors are updated, create the new Switch instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00001123 SwitchInst *NewSI =
1124 Builder.CreateSwitch(CV, PredDefault, PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001125 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +00001126 for (ValueEqualityComparisonCase &V : PredCases)
1127 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001128
Andrew Trick3051aa12012-08-29 21:46:38 +00001129 if (PredHasWeights || SuccHasWeights) {
1130 // Halve the weights if any of them cannot fit in an uint32_t
1131 FitWeights(Weights);
1132
1133 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1134
Dehao Chenf6c00832016-05-18 19:44:21 +00001135 NewSI->setMetadata(
1136 LLVMContext::MD_prof,
1137 MDBuilder(BB->getContext()).createBranchWeights(MDWeights));
Andrew Trick3051aa12012-08-29 21:46:38 +00001138 }
1139
Eli Friedmancb61afb2008-12-16 20:54:32 +00001140 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001141
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001142 // Okay, last check. If BB is still a successor of PSI, then we must
1143 // have an infinite loop case. If so, add an infinitely looping block
1144 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001145 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001146 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1147 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001148 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001149 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001150 // or it won't matter if it's hot. :)
Dehao Chenf6c00832016-05-18 19:44:21 +00001151 InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop",
1152 BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001153 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001154 }
1155 NewSI->setSuccessor(i, InfLoopBlock);
1156 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001157
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001158 Changed = true;
1159 }
1160 }
1161 return Changed;
1162}
1163
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001164// If we would need to insert a select that uses the value of this invoke
1165// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1166// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001167static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1168 Instruction *I1, Instruction *I2) {
Sanjay Patel5781d842016-03-12 16:52:17 +00001169 for (BasicBlock *Succ : successors(BB1)) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001170 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001171 for (BasicBlock::iterator BBI = Succ->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001172 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1173 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1174 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001175 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001176 return false;
1177 }
1178 }
1179 }
1180 return true;
1181}
1182
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001183static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1184
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001185/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1186/// in the two blocks up into the branch block. The caller of this function
1187/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001188static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001189 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001190 // This does very trivial matching, with limited scanning, to find identical
1191 // instructions in the two blocks. In particular, we don't want to get into
1192 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1193 // such, we currently just scan for obviously identical instructions in an
1194 // identical order.
Dehao Chenf6c00832016-05-18 19:44:21 +00001195 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1196 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
Chris Lattner389cfac2004-11-30 00:29:14 +00001197
Devang Patelf10e2872009-02-04 00:03:08 +00001198 BasicBlock::iterator BB1_Itr = BB1->begin();
1199 BasicBlock::iterator BB2_Itr = BB2->begin();
1200
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001201 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001202 // Skip debug info if it is not identical.
1203 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1204 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1205 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1206 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001207 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001208 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001209 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001210 }
Devang Patele48ddf82011-04-07 00:30:15 +00001211 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001212 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001213 return false;
1214
Chris Lattner389cfac2004-11-30 00:29:14 +00001215 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001216
David Majnemerc82f27a2013-06-03 20:43:12 +00001217 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001218 do {
1219 // If we are hoisting the terminator instruction, don't move one (making a
1220 // broken BB), instead clone it, and remove BI.
1221 if (isa<TerminatorInst>(I1))
1222 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001223
Chad Rosier54390052015-02-23 19:15:16 +00001224 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1225 return Changed;
1226
Chris Lattner389cfac2004-11-30 00:29:14 +00001227 // For a normal instruction, we just move one to right before the branch,
1228 // then replace all uses of the other with the first. Finally, we remove
1229 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001230 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001231 if (!I2->use_empty())
1232 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001233 I1->intersectOptionalDataWith(I2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001234 unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
1235 LLVMContext::MD_range,
1236 LLVMContext::MD_fpmath,
1237 LLVMContext::MD_invariant_load,
1238 LLVMContext::MD_nonnull,
1239 LLVMContext::MD_invariant_group,
1240 LLVMContext::MD_align,
1241 LLVMContext::MD_dereferenceable,
1242 LLVMContext::MD_dereferenceable_or_null,
1243 LLVMContext::MD_mem_parallel_loop_access};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001244 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001245 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001246 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001247
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001248 I1 = &*BB1_Itr++;
1249 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001250 // Skip debug info if it is not identical.
1251 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1252 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1253 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1254 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001255 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001256 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001257 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001258 }
Devang Patele48ddf82011-04-07 00:30:15 +00001259 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001260
1261 return true;
1262
1263HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001264 // It may not be possible to hoist an invoke.
1265 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001266 return Changed;
1267
Sanjay Patel5781d842016-03-12 16:52:17 +00001268 for (BasicBlock *Succ : successors(BB1)) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001269 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001270 for (BasicBlock::iterator BBI = Succ->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001271 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1272 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1273 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1274 if (BB1V == BB2V)
1275 continue;
1276
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001277 // Check for passingValueIsAlwaysUndefined here because we would rather
1278 // eliminate undefined control flow then converting it to a select.
1279 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1280 passingValueIsAlwaysUndefined(BB2V, PN))
Dehao Chenf6c00832016-05-18 19:44:21 +00001281 return Changed;
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001282
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001283 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001284 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001285 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001286 return Changed;
1287 }
1288 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001289
Chris Lattner389cfac2004-11-30 00:29:14 +00001290 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001291 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001292 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001293 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001294 I1->replaceAllUsesWith(NT);
1295 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001296 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001297 }
1298
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001299 IRBuilder<NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001300 // Hoisting one of the terminators from our successor is a great thing.
1301 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1302 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1303 // nodes, so we insert select instruction to compute the final result.
Dehao Chenf6c00832016-05-18 19:44:21 +00001304 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
Sanjay Patel5781d842016-03-12 16:52:17 +00001305 for (BasicBlock *Succ : successors(BB1)) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001306 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001307 for (BasicBlock::iterator BBI = Succ->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001308 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001309 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1310 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001311 if (BB1V == BB2V)
1312 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001313
Chris Lattner4088e2b2010-12-13 01:47:07 +00001314 // These values do not agree. Insert a select instruction before NT
1315 // that determines the right value.
1316 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001317 if (!SI)
Dehao Chenf6c00832016-05-18 19:44:21 +00001318 SI = cast<SelectInst>(
1319 Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1320 BB1V->getName() + "." + BB2V->getName(), BI));
Devang Patel1407fb42011-05-19 20:52:46 +00001321
Chris Lattner4088e2b2010-12-13 01:47:07 +00001322 // Make the PHI node use the select for all incoming values for BB1/BB2
1323 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1324 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1325 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001326 }
1327 }
1328
1329 // Update any PHI nodes in our new successors.
Sanjay Patel5781d842016-03-12 16:52:17 +00001330 for (BasicBlock *Succ : successors(BB1))
1331 AddPredecessorToBlock(Succ, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001332
Eli Friedmancb61afb2008-12-16 20:54:32 +00001333 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001334 return true;
1335}
1336
James Molloy5bf21142016-08-22 19:07:15 +00001337// Is it legal to place a variable in operand \c OpIdx of \c I?
1338// FIXME: This should be promoted to Instruction.
1339static bool canReplaceOperandWithVariable(const Instruction *I,
1340 unsigned OpIdx) {
1341 // Early exit.
1342 if (!isa<Constant>(I->getOperand(OpIdx)))
1343 return true;
1344
1345 switch (I->getOpcode()) {
1346 default:
1347 return true;
1348 case Instruction::Call:
1349 case Instruction::Invoke:
1350 // FIXME: many arithmetic intrinsics have no issue taking a
1351 // variable, however it's hard to distingish these from
1352 // specials such as @llvm.frameaddress that require a constant.
1353 return !isa<IntrinsicInst>(I);
1354 case Instruction::ShuffleVector:
1355 // Shufflevector masks are constant.
1356 return OpIdx != 2;
1357 case Instruction::ExtractValue:
1358 case Instruction::InsertValue:
1359 // All operands apart from the first are constant.
1360 return OpIdx == 0;
1361 case Instruction::Alloca:
1362 return false;
1363 case Instruction::GetElementPtr:
1364 if (OpIdx == 0)
1365 return true;
1366 gep_type_iterator It = std::next(gep_type_begin(I), OpIdx - 1);
1367 return !It->isStructTy();
1368 }
1369}
1370
James Molloyeec6df32016-09-01 10:44:35 +00001371// All instructions in Insts belong to different blocks that all unconditionally
1372// branch to a common successor. Analyze each instruction and return true if it
1373// would be possible to sink them into their successor, creating one common
1374// instruction instead. For every value that would be required to be provided by
1375// PHI node (because an operand varies in each input block), add to PHIOperands.
1376static bool canSinkInstructions(
1377 ArrayRef<Instruction *> Insts,
1378 DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
James Molloy5bf21142016-08-22 19:07:15 +00001379 // Prune out obviously bad instructions to move. Any non-store instruction
1380 // must have exactly one use, and we check later that use is by a single,
1381 // common PHI instruction in the successor.
1382 for (auto *I : Insts) {
1383 // These instructions may change or break semantics if moved.
1384 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1385 I->getType()->isTokenTy())
1386 return false;
James Molloy5bf21142016-08-22 19:07:15 +00001387 // Everything must have only one use too, apart from stores which
1388 // have no uses.
1389 if (!isa<StoreInst>(I) && !I->hasOneUse())
1390 return false;
1391 }
1392
1393 const Instruction *I0 = Insts.front();
1394 for (auto *I : Insts)
1395 if (!I->isSameOperationAs(I0))
1396 return false;
1397
James Molloyeec6df32016-09-01 10:44:35 +00001398 // All instructions in Insts are known to be the same opcode. If they aren't
1399 // stores, check the only user of each is a PHI or in the same block as the
1400 // instruction, because if a user is in the same block as an instruction
1401 // we're contemplating sinking, it must already be determined to be sinkable.
James Molloy5bf21142016-08-22 19:07:15 +00001402 if (!isa<StoreInst>(I0)) {
1403 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
James Molloy6c009c12016-09-07 09:01:22 +00001404 auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
1405 if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
James Molloyeec6df32016-09-01 10:44:35 +00001406 auto *U = cast<Instruction>(*I->user_begin());
James Molloybf1837d2016-09-07 08:15:54 +00001407 return (PNUse &&
James Molloy6c009c12016-09-07 09:01:22 +00001408 PNUse->getParent() == Succ &&
James Molloybf1837d2016-09-07 08:15:54 +00001409 PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1410 U->getParent() == I->getParent();
James Molloy5bf21142016-08-22 19:07:15 +00001411 }))
1412 return false;
1413 }
1414
James Molloy5bf21142016-08-22 19:07:15 +00001415 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1416 if (I0->getOperand(OI)->getType()->isTokenTy())
1417 // Don't touch any operand of token type.
1418 return false;
1419 auto SameAsI0 = [&I0, OI](const Instruction *I) {
James Molloyeec6df32016-09-01 10:44:35 +00001420 assert(I->getNumOperands() == I0->getNumOperands());
1421 return I->getOperand(OI) == I0->getOperand(OI);
James Molloy5bf21142016-08-22 19:07:15 +00001422 };
1423 if (!all_of(Insts, SameAsI0)) {
1424 if (!canReplaceOperandWithVariable(I0, OI))
1425 // We can't create a PHI from this GEP.
1426 return false;
James Molloy923e98c2016-08-31 10:46:16 +00001427 // Don't create indirect calls! The called value is the final operand.
1428 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OI == OE - 1) {
James Molloy5bf21142016-08-22 19:07:15 +00001429 // FIXME: if the call was *already* indirect, we should do this.
1430 return false;
James Molloy923e98c2016-08-31 10:46:16 +00001431 }
James Molloyf3cf2a42016-09-02 07:29:00 +00001432 // Because SROA can't handle speculating stores of selects, try not
James Molloyec905a62016-09-07 08:40:20 +00001433 // to sink loads or stores of allocas when we'd have to create a PHI for
1434 // the address operand.
James Molloyf3cf2a42016-09-02 07:29:00 +00001435 // FIXME: This is a workaround for a deficiency in SROA - see
1436 // https://llvm.org/bugs/show_bug.cgi?id=30188
1437 if (OI == 1 && isa<StoreInst>(I0) &&
1438 any_of(Insts, [](const Instruction *I) {
1439 return isa<AllocaInst>(I->getOperand(1));
1440 }))
1441 return false;
James Molloyec905a62016-09-07 08:40:20 +00001442 if (OI == 0 && isa<LoadInst>(I0) &&
1443 any_of(Insts, [](const Instruction *I) {
1444 return isa<AllocaInst>(I->getOperand(0));
1445 }))
1446 return false;
James Molloyeec6df32016-09-01 10:44:35 +00001447 for (auto *I : Insts)
1448 PHIOperands[I].push_back(I->getOperand(OI));
James Molloy5bf21142016-08-22 19:07:15 +00001449 }
1450 }
1451 return true;
1452}
1453
1454// Assuming canSinkLastInstruction(Blocks) has returned true, sink the last
1455// instruction of every block in Blocks to their common successor, commoning
1456// into one instruction.
James Molloyeec6df32016-09-01 10:44:35 +00001457static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
James Molloy5bf21142016-08-22 19:07:15 +00001458 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1459
1460 // canSinkLastInstruction returning true guarantees that every block has at
1461 // least one non-terminator instruction.
1462 SmallVector<Instruction*,4> Insts;
1463 for (auto *BB : Blocks)
1464 Insts.push_back(BB->getTerminator()->getPrevNode());
1465
James Molloyeec6df32016-09-01 10:44:35 +00001466 // The only checking we need to do now is that all users of all instructions
1467 // are the same PHI node. canSinkLastInstruction should have checked this but
1468 // it is slightly over-aggressive - it gets confused by commutative instructions
1469 // so double-check it here.
James Molloy5bf21142016-08-22 19:07:15 +00001470 Instruction *I0 = Insts.front();
James Molloyeec6df32016-09-01 10:44:35 +00001471 if (!isa<StoreInst>(I0)) {
1472 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1473 if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
1474 auto *U = cast<Instruction>(*I->user_begin());
1475 return U == PNUse;
1476 }))
1477 return false;
1478 }
1479
1480 // We don't need to do any more checking here; canSinkLastInstruction should
1481 // have done it all for us.
James Molloy5bf21142016-08-22 19:07:15 +00001482 SmallVector<Value*, 4> NewOperands;
1483 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
1484 // This check is different to that in canSinkLastInstruction. There, we
1485 // cared about the global view once simplifycfg (and instcombine) have
1486 // completed - it takes into account PHIs that become trivially
1487 // simplifiable. However here we need a more local view; if an operand
1488 // differs we create a PHI and rely on instcombine to clean up the very
1489 // small mess we may make.
1490 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
1491 return I->getOperand(O) != I0->getOperand(O);
1492 });
1493 if (!NeedPHI) {
1494 NewOperands.push_back(I0->getOperand(O));
1495 continue;
1496 }
1497
1498 // Create a new PHI in the successor block and populate it.
1499 auto *Op = I0->getOperand(O);
1500 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
1501 auto *PN = PHINode::Create(Op->getType(), Insts.size(),
1502 Op->getName() + ".sink", &BBEnd->front());
1503 for (auto *I : Insts)
1504 PN->addIncoming(I->getOperand(O), I->getParent());
1505 NewOperands.push_back(PN);
1506 }
1507
1508 // Arbitrarily use I0 as the new "common" instruction; remap its operands
1509 // and move it to the start of the successor block.
1510 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
1511 I0->getOperandUse(O).set(NewOperands[O]);
1512 I0->moveBefore(&*BBEnd->getFirstInsertionPt());
1513
James Molloyd13b1232016-08-30 10:56:08 +00001514 // Update metadata.
1515 for (auto *I : Insts)
1516 if (I != I0)
1517 combineMetadataForCSE(I0, I);
1518
James Molloy5bf21142016-08-22 19:07:15 +00001519 if (!isa<StoreInst>(I0)) {
1520 // canSinkLastInstruction checked that all instructions were used by
1521 // one and only one PHI node. Find that now, RAUW it to our common
1522 // instruction and nuke it.
1523 assert(I0->hasOneUse());
1524 auto *PN = cast<PHINode>(*I0->user_begin());
1525 PN->replaceAllUsesWith(I0);
1526 PN->eraseFromParent();
1527 }
1528
1529 // Finally nuke all instructions apart from the common instruction.
1530 for (auto *I : Insts)
1531 if (I != I0)
1532 I->eraseFromParent();
James Molloyeec6df32016-09-01 10:44:35 +00001533
1534 return true;
1535}
1536
1537namespace {
1538 // LockstepReverseIterator - Iterates through instructions
1539 // in a set of blocks in reverse order from the first non-terminator.
1540 // For example (assume all blocks have size n):
1541 // LockstepReverseIterator I([B1, B2, B3]);
1542 // *I-- = [B1[n], B2[n], B3[n]];
1543 // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
1544 // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
1545 // ...
1546 class LockstepReverseIterator {
1547 ArrayRef<BasicBlock*> Blocks;
1548 SmallVector<Instruction*,4> Insts;
1549 bool Fail;
1550 public:
1551 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) :
1552 Blocks(Blocks) {
1553 reset();
1554 }
1555
1556 void reset() {
1557 Fail = false;
1558 Insts.clear();
1559 for (auto *BB : Blocks) {
1560 if (BB->size() <= 1) {
1561 // Block wasn't big enough
1562 Fail = true;
1563 return;
1564 }
1565 Insts.push_back(BB->getTerminator()->getPrevNode());
1566 }
1567 }
1568
1569 bool isValid() const {
1570 return !Fail;
1571 }
1572
1573 void operator -- () {
1574 if (Fail)
1575 return;
1576 for (auto *&Inst : Insts) {
1577 if (Inst == &Inst->getParent()->front()) {
1578 Fail = true;
1579 return;
1580 }
1581 Inst = Inst->getPrevNode();
1582 }
1583 }
1584
1585 ArrayRef<Instruction*> operator * () const {
1586 return Insts;
1587 }
1588 };
James Molloy5bf21142016-08-22 19:07:15 +00001589}
1590
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001591/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001592/// check whether BBEnd has only two predecessors and the other predecessor
1593/// ends with an unconditional branch. If it is true, sink any common code
1594/// in the two predecessors to BBEnd.
1595static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1596 assert(BI1->isUnconditional());
Manman Ren93ab6492012-09-20 22:37:36 +00001597 BasicBlock *BBEnd = BI1->getSuccessor(0);
1598
James Molloy88cad7e2016-09-01 12:58:13 +00001599 // We support two situations:
1600 // (1) all incoming arcs are unconditional
1601 // (2) one incoming arc is conditional
1602 //
1603 // (2) is very common in switch defaults and
1604 // else-if patterns;
1605 //
1606 // if (a) f(1);
1607 // else if (b) f(2);
1608 //
1609 // produces:
1610 //
1611 // [if]
1612 // / \
1613 // [f(1)] [if]
1614 // | | \
1615 // | | \
1616 // | [f(2)]|
1617 // \ | /
1618 // [ end ]
1619 //
1620 // [end] has two unconditional predecessor arcs and one conditional. The
1621 // conditional refers to the implicit empty 'else' arc. This conditional
1622 // arc can also be caused by an empty default block in a switch.
1623 //
1624 // In this case, we attempt to sink code from all *unconditional* arcs.
1625 // If we can sink instructions from these arcs (determined during the scan
1626 // phase below) we insert a common successor for all unconditional arcs and
1627 // connect that to [end], to enable sinking:
1628 //
1629 // [if]
1630 // / \
1631 // [x(1)] [if]
1632 // | | \
1633 // | | \
1634 // | [x(2)] |
1635 // \ / |
1636 // [sink.split] |
1637 // \ /
1638 // [ end ]
1639 //
1640 SmallVector<BasicBlock*,4> UnconditionalPreds;
1641 Instruction *Cond = nullptr;
1642 for (auto *B : predecessors(BBEnd)) {
1643 auto *T = B->getTerminator();
1644 if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional())
1645 UnconditionalPreds.push_back(B);
1646 else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond)
1647 Cond = T;
1648 else
1649 return false;
1650 }
1651 if (UnconditionalPreds.size() < 2)
James Molloy475f4a72016-08-22 18:13:12 +00001652 return false;
James Molloy88cad7e2016-09-01 12:58:13 +00001653
Manman Ren93ab6492012-09-20 22:37:36 +00001654 bool Changed = false;
James Molloyeec6df32016-09-01 10:44:35 +00001655 // We take a two-step approach to tail sinking. First we scan from the end of
1656 // each block upwards in lockstep. If the n'th instruction from the end of each
1657 // block can be sunk, those instructions are added to ValuesToSink and we
1658 // carry on. If we can sink an instruction but need to PHI-merge some operands
1659 // (because they're not identical in each instruction) we add these to
1660 // PHIOperands.
1661 unsigned ScanIdx = 0;
1662 SmallPtrSet<Value*,4> InstructionsToSink;
1663 DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
James Molloy88cad7e2016-09-01 12:58:13 +00001664 LockstepReverseIterator LRI(UnconditionalPreds);
James Molloyeec6df32016-09-01 10:44:35 +00001665 while (LRI.isValid() &&
1666 canSinkInstructions(*LRI, PHIOperands)) {
1667 DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0] << "\n");
1668 InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
1669 ++ScanIdx;
1670 --LRI;
1671 }
1672
James Molloy88cad7e2016-09-01 12:58:13 +00001673 auto ProfitableToSinkLastInstruction = [&]() {
1674 LRI.reset();
1675 unsigned NumPHIdValues = 0;
1676 for (auto *I : *LRI)
1677 for (auto *V : PHIOperands[I])
1678 if (InstructionsToSink.count(V) == 0)
1679 ++NumPHIdValues;
1680 DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
1681 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
1682 if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
1683 NumPHIInsts++;
1684
1685 return NumPHIInsts <= 1;
1686 };
1687
1688 if (ScanIdx > 0 && Cond) {
1689 // Check if we would actually sink anything first!
1690 if (!ProfitableToSinkLastInstruction())
1691 return false;
1692
1693 DEBUG(dbgs() << "SINK: Splitting edge\n");
1694 // We have a conditional edge and we're going to sink some instructions.
1695 // Insert a new block postdominating all blocks we're going to sink from.
1696 if (!SplitBlockPredecessors(BI1->getSuccessor(0), UnconditionalPreds,
1697 ".sink.split"))
1698 // Edges couldn't be split.
1699 return false;
1700 Changed = true;
1701 }
1702
James Molloyeec6df32016-09-01 10:44:35 +00001703 // Now that we've analyzed all potential sinking candidates, perform the
1704 // actual sink. We iteratively sink the last non-terminator of the source
1705 // blocks into their common successor unless doing so would require too
1706 // many PHI instructions to be generated (currently only one PHI is allowed
1707 // per sunk instruction).
1708 //
1709 // We can use InstructionsToSink to discount values needing PHI-merging that will
1710 // actually be sunk in a later iteration. This allows us to be more
1711 // aggressive in what we sink. This does allow a false positive where we
1712 // sink presuming a later value will also be sunk, but stop half way through
1713 // and never actually sink it which means we produce more PHIs than intended.
1714 // This is unlikely in practice though.
1715 for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
1716 DEBUG(dbgs() << "SINK: Sink: "
James Molloy88cad7e2016-09-01 12:58:13 +00001717 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
James Molloyeec6df32016-09-01 10:44:35 +00001718 << "\n");
1719
1720 // Because we've sunk every instruction in turn, the current instruction to
1721 // sink is always at index 0.
James Molloy88cad7e2016-09-01 12:58:13 +00001722 if (!ProfitableToSinkLastInstruction()) {
James Molloyeec6df32016-09-01 10:44:35 +00001723 // Too many PHIs would be created.
James Molloy88cad7e2016-09-01 12:58:13 +00001724 DEBUG(dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
James Molloyeec6df32016-09-01 10:44:35 +00001725 break;
James Molloy88cad7e2016-09-01 12:58:13 +00001726 }
James Molloyeec6df32016-09-01 10:44:35 +00001727
James Molloy88cad7e2016-09-01 12:58:13 +00001728 if (!sinkLastInstruction(UnconditionalPreds))
James Molloyeec6df32016-09-01 10:44:35 +00001729 return Changed;
Manman Ren93ab6492012-09-20 22:37:36 +00001730 NumSinkCommons++;
1731 Changed = true;
1732 }
1733 return Changed;
1734}
1735
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001736/// \brief Determine if we can hoist sink a sole store instruction out of a
1737/// conditional block.
1738///
1739/// We are looking for code like the following:
1740/// BrBB:
1741/// store i32 %add, i32* %arrayidx2
1742/// ... // No other stores or function calls (we could be calling a memory
1743/// ... // function).
1744/// %cmp = icmp ult %x, %y
1745/// br i1 %cmp, label %EndBB, label %ThenBB
1746/// ThenBB:
1747/// store i32 %add5, i32* %arrayidx2
1748/// br label EndBB
1749/// EndBB:
1750/// ...
1751/// We are going to transform this into:
1752/// BrBB:
1753/// store i32 %add, i32* %arrayidx2
1754/// ... //
1755/// %cmp = icmp ult %x, %y
1756/// %add.add5 = select i1 %cmp, i32 %add, %add5
1757/// store i32 %add.add5, i32* %arrayidx2
1758/// ...
1759///
1760/// \return The pointer to the value of the previous store if the store can be
1761/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001762static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1763 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001764 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1765 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001766 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001767
1768 // Volatile or atomic.
1769 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001770 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001771
1772 Value *StorePtr = StoreToHoist->getPointerOperand();
1773
1774 // Look for a store to the same pointer in BrBB.
Hans Wennborg0c3518e2016-05-04 15:40:57 +00001775 unsigned MaxNumInstToLookAt = 9;
David Majnemerd7708772016-06-24 04:05:21 +00001776 for (Instruction &CurI : reverse(*BrBB)) {
1777 if (!MaxNumInstToLookAt)
1778 break;
Hans Wennborg0c3518e2016-05-04 15:40:57 +00001779 // Skip debug info.
1780 if (isa<DbgInfoIntrinsic>(CurI))
1781 continue;
1782 --MaxNumInstToLookAt;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001783
David L Kreitzer96674172016-08-12 21:06:53 +00001784 // Could be calling an instruction that affects memory like free().
David Majnemerd7708772016-06-24 04:05:21 +00001785 if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001786 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001787
David Majnemerd7708772016-06-24 04:05:21 +00001788 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
1789 // Found the previous store make sure it stores to the same location.
1790 if (SI->getPointerOperand() == StorePtr)
1791 // Found the previous store, return its value operand.
1792 return SI->getValueOperand();
Craig Topperf40110f2014-04-25 05:29:35 +00001793 return nullptr; // Unknown store.
David Majnemerd7708772016-06-24 04:05:21 +00001794 }
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001795 }
1796
Craig Topperf40110f2014-04-25 05:29:35 +00001797 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001798}
1799
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001800/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001801///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001802/// Note that this is a very risky transform currently. Speculating
1803/// instructions like this is most often not desirable. Instead, there is an MI
1804/// pass which can do it with full awareness of the resource constraints.
1805/// However, some cases are "obvious" and we should do directly. An example of
1806/// this is speculating a single, reasonably cheap instruction.
1807///
1808/// There is only one distinct advantage to flattening the CFG at the IR level:
1809/// it makes very common but simplistic optimizations such as are common in
1810/// instcombine and the DAG combiner more powerful by removing CFG edges and
1811/// modeling their effects with easier to reason about SSA value graphs.
1812///
1813///
1814/// An illustration of this transform is turning this IR:
1815/// \code
1816/// BB:
1817/// %cmp = icmp ult %x, %y
1818/// br i1 %cmp, label %EndBB, label %ThenBB
1819/// ThenBB:
1820/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001821/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001822/// EndBB:
1823/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1824/// ...
1825/// \endcode
1826///
1827/// Into this IR:
1828/// \code
1829/// BB:
1830/// %cmp = icmp ult %x, %y
1831/// %sub = sub %x, %y
1832/// %cond = select i1 %cmp, 0, %sub
1833/// ...
1834/// \endcode
1835///
1836/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001837static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001838 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001839 // Be conservative for now. FP select instruction can often be expensive.
1840 Value *BrCond = BI->getCondition();
1841 if (isa<FCmpInst>(BrCond))
1842 return false;
1843
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001844 BasicBlock *BB = BI->getParent();
1845 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1846
1847 // If ThenBB is actually on the false edge of the conditional branch, remember
1848 // to swap the select operands later.
1849 bool Invert = false;
1850 if (ThenBB != BI->getSuccessor(0)) {
1851 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1852 Invert = true;
1853 }
1854 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1855
Chandler Carruthceff2222013-01-25 05:40:09 +00001856 // Keep a count of how many times instructions are used within CondBB when
1857 // they are candidates for sinking into CondBB. Specifically:
1858 // - They are defined in BB, and
1859 // - They have no side effects, and
1860 // - All of their uses are in CondBB.
1861 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1862
Chandler Carruth7481ca82013-01-24 11:52:58 +00001863 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001864 Value *SpeculatedStoreValue = nullptr;
1865 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001866 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001867 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001868 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001869 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001870 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001871 if (isa<DbgInfoIntrinsic>(I))
1872 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001873
Mark Lacey274f48b2015-04-12 18:18:51 +00001874 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001875 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001876 ++SpeculationCost;
1877 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001878 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001879
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001880 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001881 if (!isSafeToSpeculativelyExecute(I) &&
1882 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1883 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001884 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001885 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001886 ComputeSpeculationCost(I, TTI) >
1887 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001888 return false;
1889
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001890 // Store the store speculation candidate.
1891 if (SpeculatedStoreValue)
1892 SpeculatedStore = cast<StoreInst>(I);
1893
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001894 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001895 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001896 // being sunk into the use block.
Dehao Chenf6c00832016-05-18 19:44:21 +00001897 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001898 Instruction *OpI = dyn_cast<Instruction>(*i);
Dehao Chenf6c00832016-05-18 19:44:21 +00001899 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
Chandler Carruthceff2222013-01-25 05:40:09 +00001900 continue; // Not a candidate for sinking.
1901
1902 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001903 }
1904 }
Evan Cheng89200c92008-06-07 08:52:29 +00001905
Chandler Carruthceff2222013-01-25 05:40:09 +00001906 // Consider any sink candidates which are only used in CondBB as costs for
1907 // speculation. Note, while we iterate over a DenseMap here, we are summing
1908 // and so iteration order isn't significant.
Dehao Chenf6c00832016-05-18 19:44:21 +00001909 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
1910 I = SinkCandidateUseCounts.begin(),
1911 E = SinkCandidateUseCounts.end();
Chandler Carruthceff2222013-01-25 05:40:09 +00001912 I != E; ++I)
1913 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001914 ++SpeculationCost;
1915 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001916 return false;
1917 }
1918
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001919 // Check that the PHI nodes can be converted to selects.
1920 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001921 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001922 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001923 Value *OrigV = PN->getIncomingValueForBlock(BB);
1924 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001925
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001926 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001927 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001928 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001929 continue;
1930
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001931 // Don't convert to selects if we could remove undefined behavior instead.
1932 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1933 passingValueIsAlwaysUndefined(ThenV, PN))
1934 return false;
1935
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001936 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001937 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1938 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1939 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001940 continue; // Known safe and cheap.
1941
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001942 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1943 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001944 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001945 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1946 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
Dehao Chenf6c00832016-05-18 19:44:21 +00001947 unsigned MaxCost =
1948 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
James Molloy7c336572015-02-11 12:15:41 +00001949 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00001950 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001951
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001952 // Account for the cost of an unfolded ConstantExpr which could end up
1953 // getting expanded into Instructions.
1954 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001955 // constant expression.
1956 ++SpeculationCost;
1957 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001958 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001959 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001960
1961 // If there are no PHIs to process, bail early. This helps ensure idempotence
1962 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001963 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001964 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001965
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001966 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001967 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001968
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001969 // Insert a select of the value of the speculated store.
1970 if (SpeculatedStoreValue) {
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001971 IRBuilder<NoFolder> Builder(BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001972 Value *TrueV = SpeculatedStore->getValueOperand();
1973 Value *FalseV = SpeculatedStoreValue;
1974 if (Invert)
1975 std::swap(TrueV, FalseV);
Sanjay Patel796db352016-03-26 23:30:50 +00001976 Value *S = Builder.CreateSelect(
1977 BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001978 SpeculatedStore->setOperand(0, S);
1979 }
1980
Igor Laevsky7310c682015-11-18 14:50:18 +00001981 // Metadata can be dependent on the condition we are hoisting above.
1982 // Conservatively strip all metadata on the instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00001983 for (auto &I : *ThenBB)
Igor Laevsky7310c682015-11-18 14:50:18 +00001984 I.dropUnknownNonDebugMetadata();
1985
Chandler Carruth7481ca82013-01-24 11:52:58 +00001986 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001987 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
1988 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001989
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001990 // Insert selects and rewrite the PHI operands.
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001991 IRBuilder<NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001992 for (BasicBlock::iterator I = EndBB->begin();
1993 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1994 unsigned OrigI = PN->getBasicBlockIndex(BB);
1995 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1996 Value *OrigV = PN->getIncomingValue(OrigI);
1997 Value *ThenV = PN->getIncomingValue(ThenI);
1998
1999 // Skip PHIs which are trivial.
2000 if (OrigV == ThenV)
2001 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00002002
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002003 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002004 // false value is the preexisting value. Swap them if the branch
2005 // destinations were inverted.
2006 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002007 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002008 std::swap(TrueV, FalseV);
Sanjay Patelf11ab052016-04-15 15:32:12 +00002009 Value *V = Builder.CreateSelect(
2010 BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002011 PN->setIncomingValue(OrigI, V);
2012 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00002013 }
2014
Evan Cheng89553cc2008-06-12 21:15:59 +00002015 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00002016 return true;
2017}
2018
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002019/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002020static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
2021 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00002022 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002023
Devang Patel84fceff2009-03-10 18:00:05 +00002024 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00002025 if (isa<DbgInfoIntrinsic>(BBI))
2026 continue;
Dehao Chenf6c00832016-05-18 19:44:21 +00002027 if (Size > 10)
2028 return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00002029 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002030
Dale Johannesened6f5a82009-03-12 23:18:09 +00002031 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00002032 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002033 for (User *U : BBI->users()) {
2034 Instruction *UI = cast<Instruction>(U);
Dehao Chenf6c00832016-05-18 19:44:21 +00002035 if (UI->getParent() != BB || isa<PHINode>(UI))
2036 return false;
Chris Lattner6c701062005-09-20 01:48:40 +00002037 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002038
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002039 // Looks ok, continue checking.
2040 }
Chris Lattner6c701062005-09-20 01:48:40 +00002041
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002042 return true;
2043}
2044
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002045/// If we have a conditional branch on a PHI node value that is defined in the
2046/// same block as the branch and if any PHI entries are constants, thread edges
2047/// corresponding to that entry to be branches to their ultimate destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002048static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00002049 BasicBlock *BB = BI->getParent();
2050 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00002051 // NOTE: we currently cannot transform this case if the PHI node is used
2052 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002053 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
2054 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002055
Chris Lattner748f9032005-09-19 23:49:37 +00002056 // Degenerate case of a single entry PHI.
2057 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00002058 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002059 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00002060 }
2061
2062 // Now we know that this block has multiple preds and two succs.
Dehao Chenf6c00832016-05-18 19:44:21 +00002063 if (!BlockIsSimpleEnoughToThreadThrough(BB))
2064 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002065
Justin Lebardb639492016-02-12 21:01:36 +00002066 // Can't fold blocks that contain noduplicate or convergent calls.
David Majnemer0a16c222016-08-11 21:15:00 +00002067 if (any_of(*BB, [](const Instruction &I) {
Justin Lebardb639492016-02-12 21:01:36 +00002068 const CallInst *CI = dyn_cast<CallInst>(&I);
2069 return CI && (CI->cannotDuplicate() || CI->isConvergent());
2070 }))
2071 return false;
Tom Stellarde1631dd2013-10-21 20:07:30 +00002072
Chris Lattner748f9032005-09-19 23:49:37 +00002073 // Okay, this is a simple enough basic block. See if any phi values are
2074 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002075 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00002076 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Dehao Chenf6c00832016-05-18 19:44:21 +00002077 if (!CB || !CB->getType()->isIntegerTy(1))
2078 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002079
Chris Lattner4088e2b2010-12-13 01:47:07 +00002080 // Okay, we now know that all edges from PredBB should be revectored to
2081 // branch to RealDest.
2082 BasicBlock *PredBB = PN->getIncomingBlock(i);
2083 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002084
Dehao Chenf6c00832016-05-18 19:44:21 +00002085 if (RealDest == BB)
2086 continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00002087 // Skip if the predecessor's terminator is an indirect branch.
Dehao Chenf6c00832016-05-18 19:44:21 +00002088 if (isa<IndirectBrInst>(PredBB->getTerminator()))
2089 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002090
Chris Lattner4088e2b2010-12-13 01:47:07 +00002091 // The dest block might have PHI nodes, other predecessors and other
2092 // difficult cases. Instead of being smart about this, just insert a new
2093 // block that jumps to the destination block, effectively splitting
2094 // the edge we are about to create.
Dehao Chenf6c00832016-05-18 19:44:21 +00002095 BasicBlock *EdgeBB =
2096 BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
2097 RealDest->getParent(), RealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002098 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002099
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002100 // Update PHI nodes.
2101 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002102
2103 // BB may have instructions that are being threaded over. Clone these
2104 // instructions into EdgeBB. We know that there will be no uses of the
2105 // cloned instructions outside of EdgeBB.
2106 BasicBlock::iterator InsertPt = EdgeBB->begin();
Dehao Chenf6c00832016-05-18 19:44:21 +00002107 DenseMap<Value *, Value *> TranslateMap; // Track translated values.
Chris Lattner4088e2b2010-12-13 01:47:07 +00002108 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
2109 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
2110 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
2111 continue;
2112 }
2113 // Clone the instruction.
2114 Instruction *N = BBI->clone();
Dehao Chenf6c00832016-05-18 19:44:21 +00002115 if (BBI->hasName())
2116 N->setName(BBI->getName() + ".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002117
Chris Lattner4088e2b2010-12-13 01:47:07 +00002118 // Update operands due to translation.
Dehao Chenf6c00832016-05-18 19:44:21 +00002119 for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) {
2120 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002121 if (PI != TranslateMap.end())
2122 *i = PI->second;
2123 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002124
Chris Lattner4088e2b2010-12-13 01:47:07 +00002125 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002126 if (Value *V = SimplifyInstruction(N, DL)) {
David Majnemerb8da3a22016-06-25 00:04:10 +00002127 if (!BBI->use_empty())
2128 TranslateMap[&*BBI] = V;
2129 if (!N->mayHaveSideEffects()) {
2130 delete N; // Instruction folded away, don't need actual inst
2131 N = nullptr;
2132 }
Chris Lattner4088e2b2010-12-13 01:47:07 +00002133 } else {
Chris Lattner4088e2b2010-12-13 01:47:07 +00002134 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002135 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00002136 }
David Majnemerb8da3a22016-06-25 00:04:10 +00002137 // Insert the new instruction into its new home.
2138 if (N)
2139 EdgeBB->getInstList().insert(InsertPt, N);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002140 }
2141
2142 // Loop over all of the edges from PredBB to BB, changing them to branch
2143 // to EdgeBB instead.
2144 TerminatorInst *PredBBTI = PredBB->getTerminator();
2145 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
2146 if (PredBBTI->getSuccessor(i) == BB) {
2147 BB->removePredecessor(PredBB);
2148 PredBBTI->setSuccessor(i, EdgeBB);
2149 }
Bill Wendling4f163df2011-06-04 09:42:04 +00002150
Chris Lattner4088e2b2010-12-13 01:47:07 +00002151 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002152 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00002153 }
Chris Lattner748f9032005-09-19 23:49:37 +00002154
2155 return false;
2156}
2157
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002158/// Given a BB that starts with the specified two-entry PHI node,
2159/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002160static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
2161 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002162 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
2163 // statement", which has a very simple dominance structure. Basically, we
2164 // are trying to find the condition that is being branched on, which
2165 // subsequently causes this merge to happen. We really want control
2166 // dependence information for this check, but simplifycfg can't keep it up
2167 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002168 BasicBlock *BB = PN->getParent();
2169 BasicBlock *IfTrue, *IfFalse;
2170 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00002171 if (!IfCond ||
2172 // Don't bother if the branch will be constant folded trivially.
2173 isa<ConstantInt>(IfCond))
2174 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002175
Chris Lattner95adf8f12006-11-18 19:19:36 +00002176 // Okay, we found that we can merge this two-entry phi node into a select.
2177 // Doing so would require us to fold *all* two entry phi nodes in this block.
2178 // At some point this becomes non-profitable (particularly if the target
2179 // doesn't support cmov's). Only do this transformation if there are two or
2180 // fewer PHI nodes in this block.
2181 unsigned NumPhis = 0;
2182 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
2183 if (NumPhis > 2)
2184 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002185
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002186 // Loop over the PHI's seeing if we can promote them all to select
2187 // instructions. While we are at it, keep track of the instructions
2188 // that need to be moved to the dominating block.
Dehao Chenf6c00832016-05-18 19:44:21 +00002189 SmallPtrSet<Instruction *, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00002190 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
2191 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00002192 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
2193 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002194
Chris Lattner7499b452010-12-14 08:46:09 +00002195 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
2196 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002197 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00002198 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00002199 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00002200 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002201 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002202
Peter Collingbournee3511e12011-04-29 18:47:31 +00002203 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002204 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00002205 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002206 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00002207 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002208 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002209
Sylvestre Ledru35521e22012-07-23 08:51:15 +00002210 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00002211 // we ran out of PHIs then we simplified them all.
2212 PN = dyn_cast<PHINode>(BB->begin());
Dehao Chenf6c00832016-05-18 19:44:21 +00002213 if (!PN)
2214 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002215
Chris Lattner7499b452010-12-14 08:46:09 +00002216 // Don't fold i1 branches on PHIs which contain binary operators. These can
2217 // often be turned into switches and other things.
2218 if (PN->getType()->isIntegerTy(1) &&
2219 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
2220 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
2221 isa<BinaryOperator>(IfCond)))
2222 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002223
Sanjay Patel2e002772016-03-12 18:05:53 +00002224 // If all PHI nodes are promotable, check to make sure that all instructions
2225 // in the predecessor blocks can be promoted as well. If not, we won't be able
2226 // to get rid of the control flow, so it's not worth promoting to select
2227 // instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00002228 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002229 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
2230 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
2231 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002232 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002233 } else {
2234 DomBlock = *pred_begin(IfBlock1);
Dehao Chenf6c00832016-05-18 19:44:21 +00002235 for (BasicBlock::iterator I = IfBlock1->begin(); !isa<TerminatorInst>(I);
2236 ++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002237 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002238 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00002239 // Because of this, we won't be able to get rid of the control flow, so
2240 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002241 return false;
2242 }
2243 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002244
Chris Lattner9ac168d2010-12-14 07:41:39 +00002245 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002246 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002247 } else {
2248 DomBlock = *pred_begin(IfBlock2);
Dehao Chenf6c00832016-05-18 19:44:21 +00002249 for (BasicBlock::iterator I = IfBlock2->begin(); !isa<TerminatorInst>(I);
2250 ++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002251 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002252 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00002253 // Because of this, we won't be able to get rid of the control flow, so
2254 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002255 return false;
2256 }
2257 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002258
Chris Lattner9fd838d2010-12-14 07:23:10 +00002259 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00002260 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002261
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002262 // If we can still promote the PHI nodes after this gauntlet of tests,
2263 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00002264 Instruction *InsertPt = DomBlock->getTerminator();
Mehdi Aminiba9fba82016-03-13 21:05:13 +00002265 IRBuilder<NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002266
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002267 // Move all 'aggressive' instructions, which are defined in the
2268 // conditional parts of the if's up to the dominating block.
David Majnemere8fd5f92016-08-29 17:14:08 +00002269 if (IfBlock1) {
2270 for (auto &I : *IfBlock1)
2271 I.dropUnknownNonDebugMetadata();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002272 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00002273 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002274 IfBlock1->getTerminator()->getIterator());
David Majnemere8fd5f92016-08-29 17:14:08 +00002275 }
2276 if (IfBlock2) {
2277 for (auto &I : *IfBlock2)
2278 I.dropUnknownNonDebugMetadata();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002279 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00002280 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002281 IfBlock2->getTerminator()->getIterator());
David Majnemere8fd5f92016-08-29 17:14:08 +00002282 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002283
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002284 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
2285 // Change the PHI node into a select instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00002286 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002287 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002288
Sanjay Patel9e23fed2016-03-17 15:30:52 +00002289 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
2290 PN->replaceAllUsesWith(Sel);
2291 Sel->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00002292 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002293 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002294
Chris Lattner335f0e42010-12-14 08:01:53 +00002295 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
2296 // has been flattened. Change DomBlock to jump directly to our new block to
2297 // avoid other simplifycfg's kicking in on the diamond.
2298 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00002299 Builder.SetInsertPoint(OldTI);
2300 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00002301 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002302 return true;
2303}
Chris Lattner748f9032005-09-19 23:49:37 +00002304
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002305/// If we found a conditional branch that goes to two returning blocks,
2306/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00002307/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002308static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00002309 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002310 assert(BI->isConditional() && "Must be a conditional branch");
2311 BasicBlock *TrueSucc = BI->getSuccessor(0);
2312 BasicBlock *FalseSucc = BI->getSuccessor(1);
2313 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2314 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002315
Chris Lattner86bbf332008-04-24 00:01:19 +00002316 // Check to ensure both blocks are empty (just a return) or optionally empty
2317 // with PHI nodes. If there are other instructions, merging would cause extra
2318 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00002319 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00002320 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00002321 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00002322 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00002323
Devang Pateldd14e0f2011-05-18 21:33:11 +00002324 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002325 // Okay, we found a branch that is going to two return nodes. If
2326 // there is no return value for this function, just change the
2327 // branch into a return.
2328 if (FalseRet->getNumOperands() == 0) {
2329 TrueSucc->removePredecessor(BI->getParent());
2330 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00002331 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00002332 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002333 return true;
2334 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002335
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002336 // Otherwise, figure out what the true and false return values are
2337 // so we can insert a new select instruction.
2338 Value *TrueValue = TrueRet->getReturnValue();
2339 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002340
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002341 // Unwrap any PHI nodes in the return blocks.
2342 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2343 if (TVPN->getParent() == TrueSucc)
2344 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
2345 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2346 if (FVPN->getParent() == FalseSucc)
2347 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002348
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002349 // In order for this transformation to be safe, we must be able to
2350 // unconditionally execute both operands to the return. This is
2351 // normally the case, but we could have a potentially-trapping
2352 // constant expression that prevents this transformation from being
2353 // safe.
2354 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2355 if (TCV->canTrap())
2356 return false;
2357 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2358 if (FCV->canTrap())
2359 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002360
Chris Lattner86bbf332008-04-24 00:01:19 +00002361 // Okay, we collected all the mapped values and checked them for sanity, and
2362 // defined to really do this transformation. First, update the CFG.
2363 TrueSucc->removePredecessor(BI->getParent());
2364 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002365
Chris Lattner86bbf332008-04-24 00:01:19 +00002366 // Insert select instructions where needed.
2367 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002368 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002369 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002370 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2371 } else if (isa<UndefValue>(TrueValue)) {
2372 TrueValue = FalseValue;
2373 } else {
Sanjay Patelfacf45a2016-04-27 23:14:12 +00002374 TrueValue =
2375 Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002376 }
Chris Lattner86bbf332008-04-24 00:01:19 +00002377 }
2378
Dehao Chenf6c00832016-05-18 19:44:21 +00002379 Value *RI =
2380 !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
Devang Pateldd14e0f2011-05-18 21:33:11 +00002381
Dehao Chenf6c00832016-05-18 19:44:21 +00002382 (void)RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002383
David Greene725c7c32010-01-05 01:26:52 +00002384 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002385 << "\n " << *BI << "NewRet = " << *RI
Dehao Chenf6c00832016-05-18 19:44:21 +00002386 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: " << *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002387
Eli Friedmancb61afb2008-12-16 20:54:32 +00002388 EraseTerminatorInstAndDCECond(BI);
2389
Chris Lattner86bbf332008-04-24 00:01:19 +00002390 return true;
2391}
2392
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002393/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002394/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002395static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002396 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2397 return false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00002398 for (Instruction &I : *PB) {
2399 Instruction *PBI = &I;
Manman Rend33f4ef2012-06-13 05:43:29 +00002400 // Check whether Inst and PBI generate the same value.
2401 if (Inst->isIdenticalTo(PBI)) {
2402 Inst->replaceAllUsesWith(PBI);
2403 Inst->eraseFromParent();
2404 return true;
2405 }
2406 }
2407 return false;
2408}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002409
Dehao Chenf16376b2016-05-18 22:41:03 +00002410/// Return true if either PBI or BI has branch weight available, and store
2411/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
2412/// not have branch weight, use 1:1 as its weight.
2413static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
2414 uint64_t &PredTrueWeight,
2415 uint64_t &PredFalseWeight,
2416 uint64_t &SuccTrueWeight,
2417 uint64_t &SuccFalseWeight) {
2418 bool PredHasWeights =
2419 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
2420 bool SuccHasWeights =
2421 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
2422 if (PredHasWeights || SuccHasWeights) {
2423 if (!PredHasWeights)
2424 PredTrueWeight = PredFalseWeight = 1;
2425 if (!SuccHasWeights)
2426 SuccTrueWeight = SuccFalseWeight = 1;
2427 return true;
2428 } else {
2429 return false;
2430 }
2431}
2432
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002433/// If this basic block is simple enough, and if a predecessor branches to us
2434/// and one of our successors, fold the block into the predecessor and use
2435/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002436bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002437 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002438
Craig Topperf40110f2014-04-25 05:29:35 +00002439 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002440 if (BI->isConditional())
2441 Cond = dyn_cast<Instruction>(BI->getCondition());
2442 else {
2443 // For unconditional branch, check for a simple CFG pattern, where
2444 // BB has a single predecessor and BB's successor is also its predecessor's
2445 // successor. If such pattern exisits, check for CSE between BB and its
2446 // predecessor.
2447 if (BasicBlock *PB = BB->getSinglePredecessor())
2448 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2449 if (PBI->isConditional() &&
2450 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2451 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002452 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002453 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002454 if (isa<CmpInst>(Curr)) {
2455 Cond = Curr;
2456 break;
2457 }
2458 // Quit if we can't remove this instruction.
2459 if (!checkCSEInPredecessor(Curr, PB))
2460 return false;
2461 }
2462 }
2463
Craig Topperf40110f2014-04-25 05:29:35 +00002464 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002465 return false;
2466 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002467
Craig Topperf40110f2014-04-25 05:29:35 +00002468 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2469 Cond->getParent() != BB || !Cond->hasOneUse())
Sanjay Patel2e002772016-03-12 18:05:53 +00002470 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002471
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002472 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002473 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002474
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002475 // Ignore dbg intrinsics.
Dehao Chenf6c00832016-05-18 19:44:21 +00002476 while (isa<DbgInfoIntrinsic>(CondIt))
2477 ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002478
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002479 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002480 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002481
Jingyue Wufc029672014-09-30 22:23:38 +00002482 // Only allow this transformation if computing the condition doesn't involve
2483 // too many instructions and these involved instructions can be executed
2484 // unconditionally. We denote all involved instructions except the condition
2485 // as "bonus instructions", and only allow this transformation when the
2486 // number of the bonus instructions does not exceed a certain threshold.
2487 unsigned NumBonusInsts = 0;
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002488 for (auto I = BB->begin(); Cond != &*I; ++I) {
Jingyue Wufc029672014-09-30 22:23:38 +00002489 // Ignore dbg intrinsics.
2490 if (isa<DbgInfoIntrinsic>(I))
2491 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002492 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002493 return false;
2494 // I has only one use and can be executed unconditionally.
2495 Instruction *User = dyn_cast<Instruction>(I->user_back());
2496 if (User == nullptr || User->getParent() != BB)
2497 return false;
2498 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2499 // to use any other instruction, User must be an instruction between next(I)
2500 // and Cond.
2501 ++NumBonusInsts;
2502 // Early exits once we reach the limit.
2503 if (NumBonusInsts > BonusInstThreshold)
2504 return false;
2505 }
2506
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002507 // Cond is known to be a compare or binary operator. Check to make sure that
2508 // neither operand is a potentially-trapping constant expression.
2509 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2510 if (CE->canTrap())
2511 return false;
2512 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2513 if (CE->canTrap())
2514 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002515
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002516 // Finally, don't infinitely unroll conditional loops.
Dehao Chenf6c00832016-05-18 19:44:21 +00002517 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002518 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002519 if (TrueDest == BB || FalseDest == BB)
2520 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002521
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002522 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2523 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002524 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002525
Chris Lattner80b03a12008-07-13 22:23:11 +00002526 // Check that we have two conditional branches. If there is a PHI node in
2527 // the common successor, verify that the same value flows in from both
2528 // blocks.
Dehao Chenf6c00832016-05-18 19:44:21 +00002529 SmallVector<PHINode *, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002530 if (!PBI || PBI->isUnconditional() ||
Dehao Chenf6c00832016-05-18 19:44:21 +00002531 (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
Manman Rend33f4ef2012-06-13 05:43:29 +00002532 (!BI->isConditional() &&
2533 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002534 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002535
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002536 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002537 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002538 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002539
Manman Rend33f4ef2012-06-13 05:43:29 +00002540 if (BI->isConditional()) {
Richard Trieu7a083812016-02-18 22:09:30 +00002541 if (PBI->getSuccessor(0) == TrueDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002542 Opc = Instruction::Or;
Richard Trieu7a083812016-02-18 22:09:30 +00002543 } else if (PBI->getSuccessor(1) == FalseDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002544 Opc = Instruction::And;
Richard Trieu7a083812016-02-18 22:09:30 +00002545 } else if (PBI->getSuccessor(0) == FalseDest) {
2546 Opc = Instruction::And;
2547 InvertPredCond = true;
2548 } else if (PBI->getSuccessor(1) == TrueDest) {
2549 Opc = Instruction::Or;
2550 InvertPredCond = true;
2551 } else {
Manman Rend33f4ef2012-06-13 05:43:29 +00002552 continue;
Richard Trieu7a083812016-02-18 22:09:30 +00002553 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002554 } else {
2555 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2556 continue;
2557 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002558
David Greene725c7c32010-01-05 01:26:52 +00002559 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002560 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002561
Chris Lattner55eaae12008-07-13 21:20:19 +00002562 // If we need to invert the condition in the pred block to match, do so now.
2563 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002564 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002565
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002566 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2567 CmpInst *CI = cast<CmpInst>(NewCond);
2568 CI->setPredicate(CI->getInversePredicate());
2569 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00002570 NewCond =
2571 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002572 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002573
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002574 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002575 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002576 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002577
Jingyue Wufc029672014-09-30 22:23:38 +00002578 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002579 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002580 // bonus instructions to a predecessor block.
2581 ValueToValueMapTy VMap; // maps original values to cloned values
2582 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002583 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002584 // instructions.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002585 for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
Jingyue Wufc029672014-09-30 22:23:38 +00002586 if (isa<DbgInfoIntrinsic>(BonusInst))
2587 continue;
2588 Instruction *NewBonusInst = BonusInst->clone();
2589 RemapInstruction(NewBonusInst, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00002590 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002591 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002592
2593 // If we moved a load, we cannot any longer claim any knowledge about
2594 // its potential value. The previous information might have been valid
2595 // only given the branch precondition.
2596 // For an analogous reason, we must also drop all the metadata whose
2597 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002598 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002599
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002600 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2601 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002602 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002603 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002604
Chris Lattner55eaae12008-07-13 21:20:19 +00002605 // Clone Cond into the predecessor basic block, and or/and the
2606 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002607 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002608 RemapInstruction(New, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00002609 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002610 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002611 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002612 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002613
Manman Rend33f4ef2012-06-13 05:43:29 +00002614 if (BI->isConditional()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002615 Instruction *NewCond = cast<Instruction>(
2616 Builder.CreateBinOp(Opc, PBI->getCondition(), New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002617 PBI->setCondition(NewCond);
2618
Manman Renbfb9d432012-09-15 00:39:57 +00002619 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Dehao Chenf16376b2016-05-18 22:41:03 +00002620 bool HasWeights =
2621 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
2622 SuccTrueWeight, SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002623 SmallVector<uint64_t, 8> NewWeights;
2624
Manman Rend33f4ef2012-06-13 05:43:29 +00002625 if (PBI->getSuccessor(0) == BB) {
Dehao Chenf16376b2016-05-18 22:41:03 +00002626 if (HasWeights) {
Manman Renbfb9d432012-09-15 00:39:57 +00002627 // PBI: br i1 %x, BB, FalseDest
2628 // BI: br i1 %y, TrueDest, FalseDest
Dehao Chenf6c00832016-05-18 19:44:21 +00002629 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
Manman Renbfb9d432012-09-15 00:39:57 +00002630 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
Dehao Chenf6c00832016-05-18 19:44:21 +00002631 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
Manman Renbfb9d432012-09-15 00:39:57 +00002632 // TrueWeight for PBI * FalseWeight for BI.
2633 // We assume that total weights of a BranchInst can fit into 32 bits.
2634 // Therefore, we will not have overflow using 64-bit arithmetic.
Dehao Chenf6c00832016-05-18 19:44:21 +00002635 NewWeights.push_back(PredFalseWeight *
2636 (SuccFalseWeight + SuccTrueWeight) +
2637 PredTrueWeight * SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002638 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002639 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2640 PBI->setSuccessor(0, TrueDest);
2641 }
2642 if (PBI->getSuccessor(1) == BB) {
Dehao Chenf16376b2016-05-18 22:41:03 +00002643 if (HasWeights) {
Manman Renbfb9d432012-09-15 00:39:57 +00002644 // PBI: br i1 %x, TrueDest, BB
2645 // BI: br i1 %y, TrueDest, FalseDest
Dehao Chenf6c00832016-05-18 19:44:21 +00002646 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
Manman Renbfb9d432012-09-15 00:39:57 +00002647 // FalseWeight for PBI * TrueWeight for BI.
Dehao Chenf6c00832016-05-18 19:44:21 +00002648 NewWeights.push_back(PredTrueWeight *
2649 (SuccFalseWeight + SuccTrueWeight) +
2650 PredFalseWeight * SuccTrueWeight);
2651 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
Manman Renbfb9d432012-09-15 00:39:57 +00002652 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2653 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002654 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2655 PBI->setSuccessor(1, FalseDest);
2656 }
Manman Renbfb9d432012-09-15 00:39:57 +00002657 if (NewWeights.size() == 2) {
2658 // Halve the weights if any of them cannot fit in an uint32_t
2659 FitWeights(NewWeights);
2660
Dehao Chenf6c00832016-05-18 19:44:21 +00002661 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
2662 NewWeights.end());
2663 PBI->setMetadata(
2664 LLVMContext::MD_prof,
2665 MDBuilder(BI->getContext()).createBranchWeights(MDWeights));
Manman Renbfb9d432012-09-15 00:39:57 +00002666 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002667 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002668 } else {
2669 // Update PHI nodes in the common successors.
2670 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002671 ConstantInt *PBI_C = cast<ConstantInt>(
Dehao Chenf6c00832016-05-18 19:44:21 +00002672 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
Manman Rend33f4ef2012-06-13 05:43:29 +00002673 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002674 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002675 if (PBI->getSuccessor(0) == TrueDest) {
2676 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2677 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2678 // is false: !PBI_Cond and BI_Value
Dehao Chenf6c00832016-05-18 19:44:21 +00002679 Instruction *NotCond = cast<Instruction>(
2680 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2681 MergedCond = cast<Instruction>(
2682 Builder.CreateBinOp(Instruction::And, NotCond, New, "and.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002683 if (PBI_C->isOne())
Dehao Chenf6c00832016-05-18 19:44:21 +00002684 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2685 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002686 } else {
2687 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2688 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2689 // is false: PBI_Cond and BI_Value
Dehao Chenf6c00832016-05-18 19:44:21 +00002690 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2691 Instruction::And, PBI->getCondition(), New, "and.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002692 if (PBI_C->isOne()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002693 Instruction *NotCond = cast<Instruction>(
2694 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2695 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2696 Instruction::Or, NotCond, MergedCond, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002697 }
2698 }
2699 // Update PHI Node.
2700 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2701 MergedCond);
2702 }
2703 // Change PBI from Conditional to Unconditional.
2704 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2705 EraseTerminatorInstAndDCECond(PBI);
2706 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002707 }
Devang Pateld715ec82011-04-06 22:37:20 +00002708
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002709 // TODO: If BB is reachable from all paths through PredBlock, then we
2710 // could replace PBI's branch probabilities with BI's.
2711
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002712 // Copy any debug value intrinsics into the end of PredBlock.
Benjamin Kramer135f7352016-06-26 12:28:59 +00002713 for (Instruction &I : *BB)
2714 if (isa<DbgInfoIntrinsic>(I))
2715 I.clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002716
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002717 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002718 }
2719 return false;
2720}
2721
James Molloy4de84dd2015-11-04 15:28:04 +00002722// If there is only one store in BB1 and BB2, return it, otherwise return
2723// nullptr.
2724static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2725 StoreInst *S = nullptr;
2726 for (auto *BB : {BB1, BB2}) {
2727 if (!BB)
2728 continue;
2729 for (auto &I : *BB)
2730 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2731 if (S)
2732 // Multiple stores seen.
2733 return nullptr;
2734 else
2735 S = SI;
2736 }
2737 }
2738 return S;
2739}
2740
2741static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2742 Value *AlternativeV = nullptr) {
2743 // PHI is going to be a PHI node that allows the value V that is defined in
2744 // BB to be referenced in BB's only successor.
2745 //
2746 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2747 // doesn't matter to us what the other operand is (it'll never get used). We
2748 // could just create a new PHI with an undef incoming value, but that could
2749 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2750 // other PHI. So here we directly look for some PHI in BB's successor with V
2751 // as an incoming operand. If we find one, we use it, else we create a new
2752 // one.
2753 //
2754 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2755 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2756 // where OtherBB is the single other predecessor of BB's only successor.
2757 PHINode *PHI = nullptr;
2758 BasicBlock *Succ = BB->getSingleSuccessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00002759
James Molloy4de84dd2015-11-04 15:28:04 +00002760 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2761 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2762 PHI = cast<PHINode>(I);
2763 if (!AlternativeV)
2764 break;
2765
2766 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2767 auto PredI = pred_begin(Succ);
2768 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2769 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2770 break;
2771 PHI = nullptr;
2772 }
2773 if (PHI)
2774 return PHI;
2775
James Molloy3d21dcf2015-12-16 14:12:44 +00002776 // If V is not an instruction defined in BB, just return it.
2777 if (!AlternativeV &&
2778 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2779 return V;
2780
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002781 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
James Molloy4de84dd2015-11-04 15:28:04 +00002782 PHI->addIncoming(V, BB);
2783 for (BasicBlock *PredBB : predecessors(Succ))
2784 if (PredBB != BB)
Dehao Chenf6c00832016-05-18 19:44:21 +00002785 PHI->addIncoming(
2786 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
James Molloy4de84dd2015-11-04 15:28:04 +00002787 return PHI;
2788}
2789
2790static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2791 BasicBlock *QTB, BasicBlock *QFB,
2792 BasicBlock *PostBB, Value *Address,
2793 bool InvertPCond, bool InvertQCond) {
2794 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2795 return Operator::getOpcode(&I) == Instruction::BitCast &&
2796 I.getType()->isPointerTy();
2797 };
2798
2799 // If we're not in aggressive mode, we only optimize if we have some
2800 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2801 auto IsWorthwhile = [&](BasicBlock *BB) {
2802 if (!BB)
2803 return true;
2804 // Heuristic: if the block can be if-converted/phi-folded and the
2805 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2806 // thread this store.
James Molloy9e959ac2015-11-05 08:40:19 +00002807 unsigned N = 0;
2808 for (auto &I : *BB) {
2809 // Cheap instructions viable for folding.
2810 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2811 isa<StoreInst>(I))
2812 ++N;
2813 // Free instructions.
2814 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2815 IsaBitcastOfPointerType(I))
2816 continue;
2817 else
James Molloy4de84dd2015-11-04 15:28:04 +00002818 return false;
James Molloy9e959ac2015-11-05 08:40:19 +00002819 }
2820 return N <= PHINodeFoldingThreshold;
James Molloy4de84dd2015-11-04 15:28:04 +00002821 };
2822
Dehao Chenf6c00832016-05-18 19:44:21 +00002823 if (!MergeCondStoresAggressively &&
2824 (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
2825 !IsWorthwhile(QFB)))
James Molloy4de84dd2015-11-04 15:28:04 +00002826 return false;
2827
2828 // For every pointer, there must be exactly two stores, one coming from
2829 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2830 // store (to any address) in PTB,PFB or QTB,QFB.
2831 // FIXME: We could relax this restriction with a bit more work and performance
2832 // testing.
2833 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2834 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2835 if (!PStore || !QStore)
2836 return false;
2837
2838 // Now check the stores are compatible.
2839 if (!QStore->isUnordered() || !PStore->isUnordered())
2840 return false;
2841
2842 // Check that sinking the store won't cause program behavior changes. Sinking
2843 // the store out of the Q blocks won't change any behavior as we're sinking
2844 // from a block to its unconditional successor. But we're moving a store from
2845 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2846 // So we need to check that there are no aliasing loads or stores in
2847 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2848 // operations between PStore and the end of its parent block.
2849 //
2850 // The ideal way to do this is to query AliasAnalysis, but we don't
2851 // preserve AA currently so that is dangerous. Be super safe and just
2852 // check there are no other memory operations at all.
2853 for (auto &I : *QFB->getSinglePredecessor())
2854 if (I.mayReadOrWriteMemory())
2855 return false;
2856 for (auto &I : *QFB)
2857 if (&I != QStore && I.mayReadOrWriteMemory())
2858 return false;
2859 if (QTB)
2860 for (auto &I : *QTB)
2861 if (&I != QStore && I.mayReadOrWriteMemory())
2862 return false;
2863 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2864 I != E; ++I)
2865 if (&*I != PStore && I->mayReadOrWriteMemory())
2866 return false;
2867
2868 // OK, we're going to sink the stores to PostBB. The store has to be
2869 // conditional though, so first create the predicate.
2870 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2871 ->getCondition();
2872 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2873 ->getCondition();
2874
2875 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2876 PStore->getParent());
2877 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2878 QStore->getParent(), PPHI);
2879
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002880 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2881
James Molloy4de84dd2015-11-04 15:28:04 +00002882 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2883 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2884
2885 if (InvertPCond)
2886 PPred = QB.CreateNot(PPred);
2887 if (InvertQCond)
2888 QPred = QB.CreateNot(QPred);
2889 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2890
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002891 auto *T =
2892 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
James Molloy4de84dd2015-11-04 15:28:04 +00002893 QB.SetInsertPoint(T);
2894 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2895 AAMDNodes AAMD;
2896 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2897 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2898 SI->setAAMetadata(AAMD);
2899
2900 QStore->eraseFromParent();
2901 PStore->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00002902
James Molloy4de84dd2015-11-04 15:28:04 +00002903 return true;
2904}
2905
2906static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) {
2907 // The intention here is to find diamonds or triangles (see below) where each
2908 // conditional block contains a store to the same address. Both of these
2909 // stores are conditional, so they can't be unconditionally sunk. But it may
2910 // be profitable to speculatively sink the stores into one merged store at the
2911 // end, and predicate the merged store on the union of the two conditions of
2912 // PBI and QBI.
2913 //
2914 // This can reduce the number of stores executed if both of the conditions are
2915 // true, and can allow the blocks to become small enough to be if-converted.
2916 // This optimization will also chain, so that ladders of test-and-set
2917 // sequences can be if-converted away.
2918 //
2919 // We only deal with simple diamonds or triangles:
2920 //
2921 // PBI or PBI or a combination of the two
2922 // / \ | \
2923 // PTB PFB | PFB
2924 // \ / | /
2925 // QBI QBI
2926 // / \ | \
2927 // QTB QFB | QFB
2928 // \ / | /
2929 // PostBB PostBB
2930 //
2931 // We model triangles as a type of diamond with a nullptr "true" block.
2932 // Triangles are canonicalized so that the fallthrough edge is represented by
2933 // a true condition, as in the diagram above.
Dehao Chenf6c00832016-05-18 19:44:21 +00002934 //
James Molloy4de84dd2015-11-04 15:28:04 +00002935 BasicBlock *PTB = PBI->getSuccessor(0);
2936 BasicBlock *PFB = PBI->getSuccessor(1);
2937 BasicBlock *QTB = QBI->getSuccessor(0);
2938 BasicBlock *QFB = QBI->getSuccessor(1);
2939 BasicBlock *PostBB = QFB->getSingleSuccessor();
2940
2941 bool InvertPCond = false, InvertQCond = false;
2942 // Canonicalize fallthroughs to the true branches.
2943 if (PFB == QBI->getParent()) {
2944 std::swap(PFB, PTB);
2945 InvertPCond = true;
2946 }
2947 if (QFB == PostBB) {
2948 std::swap(QFB, QTB);
2949 InvertQCond = true;
2950 }
2951
2952 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
2953 // and QFB may not. Model fallthroughs as a nullptr block.
2954 if (PTB == QBI->getParent())
2955 PTB = nullptr;
2956 if (QTB == PostBB)
2957 QTB = nullptr;
2958
2959 // Legality bailouts. We must have at least the non-fallthrough blocks and
2960 // the post-dominating block, and the non-fallthroughs must only have one
2961 // predecessor.
2962 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002963 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
James Molloy4de84dd2015-11-04 15:28:04 +00002964 };
2965 if (!PostBB ||
2966 !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
2967 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
2968 return false;
2969 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
2970 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
2971 return false;
2972 if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2)
2973 return false;
2974
2975 // OK, this is a sequence of two diamonds or triangles.
2976 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
Dehao Chenf6c00832016-05-18 19:44:21 +00002977 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
James Molloy4de84dd2015-11-04 15:28:04 +00002978 for (auto *BB : {PTB, PFB}) {
2979 if (!BB)
2980 continue;
2981 for (auto &I : *BB)
2982 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2983 PStoreAddresses.insert(SI->getPointerOperand());
2984 }
2985 for (auto *BB : {QTB, QFB}) {
2986 if (!BB)
2987 continue;
2988 for (auto &I : *BB)
2989 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2990 QStoreAddresses.insert(SI->getPointerOperand());
2991 }
Dehao Chenf6c00832016-05-18 19:44:21 +00002992
James Molloy4de84dd2015-11-04 15:28:04 +00002993 set_intersect(PStoreAddresses, QStoreAddresses);
2994 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
2995 // clear what it contains.
2996 auto &CommonAddresses = PStoreAddresses;
2997
2998 bool Changed = false;
2999 for (auto *Address : CommonAddresses)
3000 Changed |= mergeConditionalStoreToAddress(
3001 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond);
3002 return Changed;
3003}
3004
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003005/// If we have a conditional branch as a predecessor of another block,
3006/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00003007/// that PBI and BI are both conditional branches, and BI is in one of the
3008/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00003009static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3010 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00003011 assert(PBI->isConditional() && BI->isConditional());
3012 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00003013
Chris Lattner9aada1d2008-07-13 21:53:26 +00003014 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00003015 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00003016 // this conditional branch redundant.
3017 if (PBI->getCondition() == BI->getCondition() &&
3018 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3019 // Okay, the outcome of this conditional branch is statically
3020 // knowable. If this block had a single pred, handle specially.
3021 if (BB->getSinglePredecessor()) {
3022 // Turn this into a branch on constant.
3023 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Dehao Chenf6c00832016-05-18 19:44:21 +00003024 BI->setCondition(
3025 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
3026 return true; // Nuke the branch on constant.
Chris Lattner9aada1d2008-07-13 21:53:26 +00003027 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003028
Chris Lattner9aada1d2008-07-13 21:53:26 +00003029 // Otherwise, if there are multiple predecessors, insert a PHI that merges
3030 // in the constant and simplify the block result. Subsequent passes of
3031 // simplifycfg will thread the block.
3032 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00003033 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003034 PHINode *NewPN = PHINode::Create(
3035 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
3036 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00003037 // Okay, we're going to insert the PHI node. Since PBI is not the only
3038 // predecessor, compute the PHI'd conditional value for all of the preds.
3039 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00003040 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00003041 BasicBlock *P = *PI;
Dehao Chenf6c00832016-05-18 19:44:21 +00003042 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
3043 PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00003044 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3045 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Dehao Chenf6c00832016-05-18 19:44:21 +00003046 NewPN->addIncoming(
3047 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
3048 P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00003049 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00003050 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00003051 }
Gabor Greif8629f122010-07-12 10:59:23 +00003052 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003053
Chris Lattner9aada1d2008-07-13 21:53:26 +00003054 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00003055 return true;
3056 }
3057 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003058
Philip Reamesb42db212015-10-14 22:46:19 +00003059 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
3060 if (CE->canTrap())
3061 return false;
3062
James Molloy4de84dd2015-11-04 15:28:04 +00003063 // If both branches are conditional and both contain stores to the same
3064 // address, remove the stores from the conditionals and create a conditional
3065 // merged store at the end.
3066 if (MergeCondStores && mergeConditionalStores(PBI, BI))
3067 return true;
3068
Chris Lattner9aada1d2008-07-13 21:53:26 +00003069 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00003070 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00003071 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00003072 BasicBlock::iterator BBI = BB->begin();
3073 // Ignore dbg intrinsics.
3074 while (isa<DbgInfoIntrinsic>(BBI))
3075 ++BBI;
3076 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00003077 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00003078
Chris Lattner834ab4e2008-07-13 22:04:41 +00003079 int PBIOp, BIOp;
Richard Trieu7a083812016-02-18 22:09:30 +00003080 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3081 PBIOp = 0;
3082 BIOp = 0;
3083 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3084 PBIOp = 0;
3085 BIOp = 1;
3086 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3087 PBIOp = 1;
3088 BIOp = 0;
3089 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3090 PBIOp = 1;
3091 BIOp = 1;
3092 } else {
Chris Lattner834ab4e2008-07-13 22:04:41 +00003093 return false;
Richard Trieu7a083812016-02-18 22:09:30 +00003094 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003095
Chris Lattner834ab4e2008-07-13 22:04:41 +00003096 // Check to make sure that the other destination of this branch
3097 // isn't BB itself. If so, this is an infinite loop that will
3098 // keep getting unwound.
3099 if (PBI->getSuccessor(PBIOp) == BB)
3100 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003101
3102 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00003103 // insertion of a large number of select instructions. For targets
3104 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003105
Sanjay Patela932da82014-07-07 21:19:00 +00003106 // Also do not perform this transformation if any phi node in the common
3107 // destination block can trap when reached by BB or PBB (PR17073). In that
3108 // case, it would be unsafe to hoist the operation into a select instruction.
3109
3110 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00003111 unsigned NumPhis = 0;
Dehao Chenf6c00832016-05-18 19:44:21 +00003112 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
3113 ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00003114 if (NumPhis > 2) // Disable this xform.
3115 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003116
Sanjay Patela932da82014-07-07 21:19:00 +00003117 PHINode *PN = cast<PHINode>(II);
3118 Value *BIV = PN->getIncomingValueForBlock(BB);
3119 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
3120 if (CE->canTrap())
3121 return false;
3122
3123 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3124 Value *PBIV = PN->getIncomingValue(PBBIdx);
3125 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
3126 if (CE->canTrap())
3127 return false;
3128 }
3129
Chris Lattner834ab4e2008-07-13 22:04:41 +00003130 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00003131 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003132
David Greene725c7c32010-01-05 01:26:52 +00003133 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00003134 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003135
Chris Lattner80b03a12008-07-13 22:23:11 +00003136 // If OtherDest *is* BB, then BB is a basic block with a single conditional
3137 // branch in it, where one edge (OtherDest) goes back to itself but the other
3138 // exits. We don't *know* that the program avoids the infinite loop
3139 // (even though that seems likely). If we do this xform naively, we'll end up
3140 // recursively unpeeling the loop. Since we know that (after the xform is
3141 // done) that the block *is* infinite if reached, we just make it an obviously
3142 // infinite loop with no cond branch.
3143 if (OtherDest == BB) {
3144 // Insert it at the end of the function, because it's either code,
3145 // or it won't matter if it's hot. :)
Dehao Chenf6c00832016-05-18 19:44:21 +00003146 BasicBlock *InfLoopBlock =
3147 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00003148 BranchInst::Create(InfLoopBlock, InfLoopBlock);
3149 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003150 }
3151
David Greene725c7c32010-01-05 01:26:52 +00003152 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00003153
Chris Lattner834ab4e2008-07-13 22:04:41 +00003154 // BI may have other predecessors. Because of this, we leave
3155 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003156
Chris Lattner834ab4e2008-07-13 22:04:41 +00003157 // Make sure we get to CommonDest on True&True directions.
3158 Value *PBICond = PBI->getCondition();
Mehdi Aminiba9fba82016-03-13 21:05:13 +00003159 IRBuilder<NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00003160 if (PBIOp)
Dehao Chenf6c00832016-05-18 19:44:21 +00003161 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
Devang Patel1407fb42011-05-19 20:52:46 +00003162
Chris Lattner834ab4e2008-07-13 22:04:41 +00003163 Value *BICond = BI->getCondition();
3164 if (BIOp)
Dehao Chenf6c00832016-05-18 19:44:21 +00003165 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
Devang Patel1407fb42011-05-19 20:52:46 +00003166
Chris Lattner834ab4e2008-07-13 22:04:41 +00003167 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00003168 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00003169
Chris Lattner834ab4e2008-07-13 22:04:41 +00003170 // Modify PBI to branch on the new condition to the new dests.
3171 PBI->setCondition(Cond);
3172 PBI->setSuccessor(0, CommonDest);
3173 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003174
Manman Ren2d4c10f2012-09-17 21:30:40 +00003175 // Update branch weight for PBI.
3176 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Dehao Chenb76e5d92016-05-10 23:07:19 +00003177 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
Dehao Chenf16376b2016-05-18 22:41:03 +00003178 bool HasWeights =
3179 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3180 SuccTrueWeight, SuccFalseWeight);
Dehao Chenb76e5d92016-05-10 23:07:19 +00003181 if (HasWeights) {
Dehao Chenb76e5d92016-05-10 23:07:19 +00003182 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3183 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3184 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3185 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
Manman Ren2d4c10f2012-09-17 21:30:40 +00003186 // The weight to CommonDest should be PredCommon * SuccTotal +
3187 // PredOther * SuccCommon.
3188 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00003189 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3190 PredOther * SuccCommon,
3191 PredOther * SuccOther};
Sanjay Patel84a0bf62016-05-06 17:51:37 +00003192 // Halve the weights if any of them cannot fit in an uint32_t
Manman Ren2d4c10f2012-09-17 21:30:40 +00003193 FitWeights(NewWeights);
3194
Manman Ren2d4c10f2012-09-17 21:30:40 +00003195 PBI->setMetadata(LLVMContext::MD_prof,
Sanjay Patel84a0bf62016-05-06 17:51:37 +00003196 MDBuilder(BI->getContext())
3197 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00003198 }
3199
Chris Lattner834ab4e2008-07-13 22:04:41 +00003200 // OtherDest may have phi nodes. If so, add an entry from PBI's
3201 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003202 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003203
Chris Lattner834ab4e2008-07-13 22:04:41 +00003204 // We know that the CommonDest already had an edge from PBI to
3205 // it. If it has PHIs though, the PHIs may have different
3206 // entries for BB and PBI's BB. If so, insert a select to make
3207 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003208 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00003209 for (BasicBlock::iterator II = CommonDest->begin();
3210 (PN = dyn_cast<PHINode>(II)); ++II) {
3211 Value *BIV = PN->getIncomingValueForBlock(BB);
3212 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3213 Value *PBIV = PN->getIncomingValue(PBBIdx);
3214 if (BIV != PBIV) {
3215 // Insert a select in PBI to pick the right value.
Dehao Chenf6c00832016-05-18 19:44:21 +00003216 SelectInst *NV = cast<SelectInst>(
3217 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00003218 PN->setIncomingValue(PBBIdx, NV);
Sanjay Patel1cb62412016-05-06 18:07:46 +00003219 // Although the select has the same condition as PBI, the original branch
3220 // weights for PBI do not apply to the new select because the select's
3221 // 'logical' edges are incoming edges of the phi that is eliminated, not
3222 // the outgoing edges of PBI.
Dehao Chenf16376b2016-05-18 22:41:03 +00003223 if (HasWeights) {
Sanjay Patel1cb62412016-05-06 18:07:46 +00003224 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3225 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3226 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3227 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3228 // The weight to PredCommonDest should be PredCommon * SuccTotal.
3229 // The weight to PredOtherDest should be PredOther * SuccCommon.
3230 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3231 PredOther * SuccCommon};
3232
3233 FitWeights(NewWeights);
3234
3235 NV->setMetadata(LLVMContext::MD_prof,
3236 MDBuilder(BI->getContext())
3237 .createBranchWeights(NewWeights[0], NewWeights[1]));
3238 }
Chris Lattner9aada1d2008-07-13 21:53:26 +00003239 }
3240 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003241
David Greene725c7c32010-01-05 01:26:52 +00003242 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
3243 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003244
Chris Lattner834ab4e2008-07-13 22:04:41 +00003245 // This basic block is probably dead. We know it has at least
3246 // one fewer predecessor.
3247 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00003248}
3249
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003250// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
3251// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00003252// Takes care of updating the successors and removing the old terminator.
3253// Also makes sure not to introduce new successors by assuming that edges to
3254// non-successor TrueBBs and FalseBBs aren't reachable.
3255static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00003256 BasicBlock *TrueBB, BasicBlock *FalseBB,
3257 uint32_t TrueWeight,
Dehao Chenf6c00832016-05-18 19:44:21 +00003258 uint32_t FalseWeight) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003259 // Remove any superfluous successor edges from the CFG.
3260 // First, figure out which successors to preserve.
3261 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
3262 // successor.
3263 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00003264 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003265
3266 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00003267 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003268 // Make sure only to keep exactly one copy of each edge.
3269 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00003270 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003271 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00003272 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003273 else
David Majnemerdc3b67b2015-10-21 18:22:24 +00003274 Succ->removePredecessor(OldTerm->getParent(),
3275 /*DontDeleteUselessPHIs=*/true);
Frits van Bommel8e158492011-01-11 12:52:11 +00003276 }
3277
Devang Patel2c2ea222011-05-18 18:43:31 +00003278 IRBuilder<> Builder(OldTerm);
3279 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
3280
Frits van Bommel8e158492011-01-11 12:52:11 +00003281 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00003282 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003283 if (TrueBB == FalseBB)
3284 // We were only looking for one successor, and it was present.
3285 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00003286 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00003287 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00003288 // We found both of the successors we were looking for.
3289 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00003290 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
3291 if (TrueWeight != FalseWeight)
3292 NewBI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00003293 MDBuilder(OldTerm->getContext())
3294 .createBranchWeights(TrueWeight, FalseWeight));
Manman Ren774246a2012-09-17 22:28:55 +00003295 }
Frits van Bommel8e158492011-01-11 12:52:11 +00003296 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3297 // Neither of the selected blocks were successors, so this
3298 // terminator must be unreachable.
3299 new UnreachableInst(OldTerm->getContext(), OldTerm);
3300 } else {
3301 // One of the selected values was a successor, but the other wasn't.
3302 // Insert an unconditional branch to the one that was found;
3303 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00003304 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00003305 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00003306 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00003307 else
3308 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00003309 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00003310 }
3311
3312 EraseTerminatorInstAndDCECond(OldTerm);
3313 return true;
3314}
3315
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003316// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00003317// (switch (select cond, X, Y)) on constant X, Y
3318// with a branch - conditional if X and Y lead to distinct BBs,
3319// unconditional otherwise.
3320static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
3321 // Check for constant integer values in the select.
3322 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
3323 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
3324 if (!TrueVal || !FalseVal)
3325 return false;
3326
3327 // Find the relevant condition and destinations.
3328 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003329 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
3330 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00003331
Manman Ren774246a2012-09-17 22:28:55 +00003332 // Get weight for TrueBB and FalseBB.
3333 uint32_t TrueWeight = 0, FalseWeight = 0;
3334 SmallVector<uint64_t, 8> Weights;
3335 bool HasWeights = HasBranchWeights(SI);
3336 if (HasWeights) {
3337 GetBranchWeights(SI, Weights);
3338 if (Weights.size() == 1 + SI->getNumCases()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00003339 TrueWeight =
3340 (uint32_t)Weights[SI->findCaseValue(TrueVal).getSuccessorIndex()];
3341 FalseWeight =
3342 (uint32_t)Weights[SI->findCaseValue(FalseVal).getSuccessorIndex()];
Manman Ren774246a2012-09-17 22:28:55 +00003343 }
3344 }
3345
Frits van Bommel8ae07992011-02-28 09:44:07 +00003346 // Perform the actual simplification.
Dehao Chenf6c00832016-05-18 19:44:21 +00003347 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
3348 FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00003349}
3350
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003351// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003352// (indirectbr (select cond, blockaddress(@fn, BlockA),
3353// blockaddress(@fn, BlockB)))
3354// with
3355// (br cond, BlockA, BlockB).
3356static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
3357 // Check that both operands of the select are block addresses.
3358 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3359 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3360 if (!TBA || !FBA)
3361 return false;
3362
3363 // Extract the actual blocks.
3364 BasicBlock *TrueBB = TBA->getBasicBlock();
3365 BasicBlock *FalseBB = FBA->getBasicBlock();
3366
Frits van Bommel8e158492011-01-11 12:52:11 +00003367 // Perform the actual simplification.
Dehao Chenf6c00832016-05-18 19:44:21 +00003368 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
3369 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003370}
3371
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003372/// This is called when we find an icmp instruction
3373/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003374/// block that ends with an uncond branch. We are looking for a very specific
3375/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3376/// this case, we merge the first two "or's of icmp" into a switch, but then the
3377/// default value goes to an uncond block with a seteq in it, we get something
3378/// like:
3379///
3380/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3381/// DEFAULT:
3382/// %tmp = icmp eq i8 %A, 92
3383/// br label %end
3384/// end:
3385/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00003386///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003387/// We prefer to split the edge to 'end' so that there is a true/false entry to
3388/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003389static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003390 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
3391 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
3392 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003393 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00003394
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003395 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3396 // complex.
Dehao Chenf6c00832016-05-18 19:44:21 +00003397 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
3398 return false;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003399
3400 Value *V = ICI->getOperand(0);
3401 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00003402
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003403 // The pattern we're looking for is where our only predecessor is a switch on
3404 // 'V' and this block is the default case for the switch. In this case we can
3405 // fold the compared value into the switch to simplify things.
3406 BasicBlock *Pred = BB->getSinglePredecessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00003407 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3408 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003409
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003410 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3411 if (SI->getCondition() != V)
3412 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003413
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003414 // If BB is reachable on a non-default case, then we simply know the value of
3415 // V in this block. Substitute it and constant fold the icmp instruction
3416 // away.
3417 if (SI->getDefaultDest() != BB) {
3418 ConstantInt *VVal = SI->findCaseDest(BB);
3419 assert(VVal && "Should have a unique destination value");
3420 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003421
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003422 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00003423 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003424 ICI->eraseFromParent();
3425 }
3426 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003427 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003428 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003429
Chris Lattner62cc76e2010-12-13 03:43:57 +00003430 // Ok, the block is reachable from the default dest. If the constant we're
3431 // comparing exists in one of the other edges, then we can constant fold ICI
3432 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003433 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00003434 Value *V;
3435 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3436 V = ConstantInt::getFalse(BB->getContext());
3437 else
3438 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003439
Chris Lattner62cc76e2010-12-13 03:43:57 +00003440 ICI->replaceAllUsesWith(V);
3441 ICI->eraseFromParent();
3442 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003443 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00003444 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003445
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003446 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3447 // the block.
3448 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003449 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00003450 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003451 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3452 return false;
3453
3454 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3455 // true in the PHI.
3456 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
Dehao Chenf6c00832016-05-18 19:44:21 +00003457 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003458
3459 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3460 std::swap(DefaultCst, NewCst);
3461
3462 // Replace ICI (which is used by the PHI for the default value) with true or
3463 // false depending on if it is EQ or NE.
3464 ICI->replaceAllUsesWith(DefaultCst);
3465 ICI->eraseFromParent();
3466
3467 // Okay, the switch goes to this block on a default value. Add an edge from
3468 // the switch to the merge point on the compared value.
Dehao Chenf6c00832016-05-18 19:44:21 +00003469 BasicBlock *NewBB =
3470 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00003471 SmallVector<uint64_t, 8> Weights;
3472 bool HasWeights = HasBranchWeights(SI);
3473 if (HasWeights) {
3474 GetBranchWeights(SI, Weights);
3475 if (Weights.size() == 1 + SI->getNumCases()) {
3476 // Split weight for default case to case for "Cst".
Dehao Chenf6c00832016-05-18 19:44:21 +00003477 Weights[0] = (Weights[0] + 1) >> 1;
Manman Rence48ea72012-09-17 23:07:43 +00003478 Weights.push_back(Weights[0]);
3479
3480 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
Dehao Chenf6c00832016-05-18 19:44:21 +00003481 SI->setMetadata(
3482 LLVMContext::MD_prof,
3483 MDBuilder(SI->getContext()).createBranchWeights(MDWeights));
Manman Rence48ea72012-09-17 23:07:43 +00003484 }
3485 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003486 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003487
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003488 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00003489 Builder.SetInsertPoint(NewBB);
3490 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3491 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003492 PHIUse->addIncoming(NewCst, NewBB);
3493 return true;
3494}
3495
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003496/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003497/// Check to see if it is branching on an or/and chain of icmp instructions, and
3498/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003499static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3500 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003501 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Dehao Chenf6c00832016-05-18 19:44:21 +00003502 if (!Cond)
3503 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003504
Chris Lattnera69c4432010-12-13 05:03:41 +00003505 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3506 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3507 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003508
Mehdi Amini9a25cb82014-11-19 20:09:11 +00003509 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00003510 ConstantComparesGatherer ConstantCompare(Cond, DL);
3511 // Unpack the result
Dehao Chenf6c00832016-05-18 19:44:21 +00003512 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
Mehdi Aminiffd01002014-11-20 22:40:25 +00003513 Value *CompVal = ConstantCompare.CompValue;
3514 unsigned UsedICmps = ConstantCompare.UsedICmps;
3515 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003516
Chris Lattnera69c4432010-12-13 05:03:41 +00003517 // If we didn't have a multiply compared value, fail.
Dehao Chenf6c00832016-05-18 19:44:21 +00003518 if (!CompVal)
3519 return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00003520
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003521 // Avoid turning single icmps into a switch.
3522 if (UsedICmps <= 1)
3523 return false;
3524
Mehdi Aminiffd01002014-11-20 22:40:25 +00003525 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3526
Chris Lattnera69c4432010-12-13 05:03:41 +00003527 // There might be duplicate constants in the list, which the switch
3528 // instruction can't handle, remove them now.
3529 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3530 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003531
Chris Lattnera69c4432010-12-13 05:03:41 +00003532 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00003533 // transformation. A switch with one value is just a conditional branch.
Dehao Chenf6c00832016-05-18 19:44:21 +00003534 if (ExtraCase && Values.size() < 2)
3535 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003536
Andrew Trick3051aa12012-08-29 21:46:38 +00003537 // TODO: Preserve branch weight metadata, similarly to how
3538 // FoldValueComparisonIntoPredecessors preserves it.
3539
Chris Lattnera69c4432010-12-13 05:03:41 +00003540 // Figure out which block is which destination.
3541 BasicBlock *DefaultBB = BI->getSuccessor(1);
Dehao Chenf6c00832016-05-18 19:44:21 +00003542 BasicBlock *EdgeBB = BI->getSuccessor(0);
3543 if (!TrueWhenEqual)
3544 std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003545
Chris Lattnera69c4432010-12-13 05:03:41 +00003546 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003547
Chris Lattnerd7beca32010-12-14 06:17:25 +00003548 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Dehao Chenf6c00832016-05-18 19:44:21 +00003549 << " cases into SWITCH. BB is:\n"
3550 << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003551
Chris Lattnera69c4432010-12-13 05:03:41 +00003552 // If there are any extra values that couldn't be folded into the switch
3553 // then we evaluate them with an explicit branch first. Split the block
3554 // right before the condbr to handle it.
3555 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003556 BasicBlock *NewBB =
3557 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00003558 // Remove the uncond branch added to the old block.
3559 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00003560 Builder.SetInsertPoint(OldTI);
3561
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003562 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00003563 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003564 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00003565 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003566
Chris Lattnera69c4432010-12-13 05:03:41 +00003567 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003568
Chris Lattnercb570f82010-12-13 05:34:18 +00003569 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3570 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003571 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003572
Chris Lattnerd7beca32010-12-14 06:17:25 +00003573 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
Dehao Chenf6c00832016-05-18 19:44:21 +00003574 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00003575 BB = NewBB;
3576 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00003577
3578 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00003579 // Convert pointer to int before we switch.
3580 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003581 CompVal = Builder.CreatePtrToInt(
3582 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00003583 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003584
Chris Lattnera69c4432010-12-13 05:03:41 +00003585 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00003586 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00003587
Chris Lattnera69c4432010-12-13 05:03:41 +00003588 // Add all of the 'cases' to the switch instruction.
3589 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3590 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003591
Chris Lattnera69c4432010-12-13 05:03:41 +00003592 // We added edges from PI to the EdgeBB. As such, if there were any
3593 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3594 // the number of edges added.
Dehao Chenf6c00832016-05-18 19:44:21 +00003595 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003596 PHINode *PN = cast<PHINode>(BBI);
3597 Value *InVal = PN->getIncomingValueForBlock(BB);
Dehao Chenf6c00832016-05-18 19:44:21 +00003598 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
Chris Lattnera69c4432010-12-13 05:03:41 +00003599 PN->addIncoming(InVal, BB);
3600 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003601
Chris Lattnera69c4432010-12-13 05:03:41 +00003602 // Erase the old branch instruction.
3603 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003604
Chris Lattnerd7beca32010-12-14 06:17:25 +00003605 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00003606 return true;
3607}
3608
Duncan Sands29192d02011-09-05 12:57:57 +00003609bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
Chen Li1689c2f2016-01-10 05:48:01 +00003610 if (isa<PHINode>(RI->getValue()))
3611 return SimplifyCommonResume(RI);
3612 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3613 RI->getValue() == RI->getParent()->getFirstNonPHI())
3614 // The resume must unwind the exception that caused control to branch here.
3615 return SimplifySingleResume(RI);
Chen Li509ff212016-01-11 19:20:53 +00003616
3617 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003618}
3619
3620// Simplify resume that is shared by several landing pads (phi of landing pad).
3621bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3622 BasicBlock *BB = RI->getParent();
3623
3624 // Check that there are no other instructions except for debug intrinsics
3625 // between the phi of landing pads (RI->getValue()) and resume instruction.
3626 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
Dehao Chenf6c00832016-05-18 19:44:21 +00003627 E = RI->getIterator();
Chen Li1689c2f2016-01-10 05:48:01 +00003628 while (++I != E)
3629 if (!isa<DbgInfoIntrinsic>(I))
3630 return false;
3631
3632 SmallSet<BasicBlock *, 4> TrivialUnwindBlocks;
3633 auto *PhiLPInst = cast<PHINode>(RI->getValue());
3634
3635 // Check incoming blocks to see if any of them are trivial.
Dehao Chenf6c00832016-05-18 19:44:21 +00003636 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
3637 Idx++) {
Chen Li1689c2f2016-01-10 05:48:01 +00003638 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3639 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3640
3641 // If the block has other successors, we can not delete it because
3642 // it has other dependents.
3643 if (IncomingBB->getUniqueSuccessor() != BB)
3644 continue;
3645
Dehao Chenf6c00832016-05-18 19:44:21 +00003646 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
Chen Li1689c2f2016-01-10 05:48:01 +00003647 // Not the landing pad that caused the control to branch here.
3648 if (IncomingValue != LandingPad)
3649 continue;
3650
3651 bool isTrivial = true;
3652
3653 I = IncomingBB->getFirstNonPHI()->getIterator();
3654 E = IncomingBB->getTerminator()->getIterator();
3655 while (++I != E)
3656 if (!isa<DbgInfoIntrinsic>(I)) {
3657 isTrivial = false;
3658 break;
3659 }
3660
3661 if (isTrivial)
3662 TrivialUnwindBlocks.insert(IncomingBB);
3663 }
3664
3665 // If no trivial unwind blocks, don't do any simplifications.
Dehao Chenf6c00832016-05-18 19:44:21 +00003666 if (TrivialUnwindBlocks.empty())
3667 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003668
3669 // Turn all invokes that unwind here into calls.
3670 for (auto *TrivialBB : TrivialUnwindBlocks) {
3671 // Blocks that will be simplified should be removed from the phi node.
3672 // Note there could be multiple edges to the resume block, and we need
3673 // to remove them all.
3674 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3675 BB->removePredecessor(TrivialBB, true);
3676
3677 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3678 PI != PE;) {
3679 BasicBlock *Pred = *PI++;
3680 removeUnwindEdge(Pred);
3681 }
3682
3683 // In each SimplifyCFG run, only the current processed block can be erased.
3684 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3685 // of erasing TrivialBB, we only remove the branch to the common resume
3686 // block so that we can later erase the resume block since it has no
3687 // predecessors.
3688 TrivialBB->getTerminator()->eraseFromParent();
3689 new UnreachableInst(RI->getContext(), TrivialBB);
3690 }
3691
3692 // Delete the resume block if all its predecessors have been removed.
3693 if (pred_empty(BB))
3694 BB->eraseFromParent();
3695
3696 return !TrivialUnwindBlocks.empty();
3697}
3698
3699// Simplify resume that is only used by a single (non-phi) landing pad.
3700bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
Duncan Sands29192d02011-09-05 12:57:57 +00003701 BasicBlock *BB = RI->getParent();
3702 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
Dehao Chenf6c00832016-05-18 19:44:21 +00003703 assert(RI->getValue() == LPInst &&
3704 "Resume must unwind the exception that caused control to here");
Duncan Sands29192d02011-09-05 12:57:57 +00003705
Chen Li7009cd32015-10-23 21:13:01 +00003706 // Check that there are no other instructions except for debug intrinsics.
3707 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
Duncan Sands29192d02011-09-05 12:57:57 +00003708 while (++I != E)
3709 if (!isa<DbgInfoIntrinsic>(I))
3710 return false;
3711
Chen Lic6e28782015-10-22 20:48:38 +00003712 // Turn all invokes that unwind here into calls and delete the basic block.
Chen Li7009cd32015-10-23 21:13:01 +00003713 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3714 BasicBlock *Pred = *PI++;
3715 removeUnwindEdge(Pred);
Chen Lic6e28782015-10-22 20:48:38 +00003716 }
3717
Chen Li7009cd32015-10-23 21:13:01 +00003718 // The landingpad is now unreachable. Zap it.
3719 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00003720 if (LoopHeaders)
3721 LoopHeaders->erase(BB);
Chen Li7009cd32015-10-23 21:13:01 +00003722 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00003723}
3724
David Majnemer1efa23d2016-02-20 01:07:45 +00003725static bool removeEmptyCleanup(CleanupReturnInst *RI) {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003726 // If this is a trivial cleanup pad that executes no instructions, it can be
3727 // eliminated. If the cleanup pad continues to the caller, any predecessor
3728 // that is an EH pad will be updated to continue to the caller and any
3729 // predecessor that terminates with an invoke instruction will have its invoke
3730 // instruction converted to a call instruction. If the cleanup pad being
3731 // simplified does not continue to the caller, each predecessor will be
3732 // updated to continue to the unwind destination of the cleanup pad being
3733 // simplified.
3734 BasicBlock *BB = RI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003735 CleanupPadInst *CPInst = RI->getCleanupPad();
3736 if (CPInst->getParent() != BB)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003737 // This isn't an empty cleanup.
3738 return false;
3739
David Majnemer2482e1c2016-06-04 23:50:03 +00003740 // We cannot kill the pad if it has multiple uses. This typically arises
3741 // from unreachable basic blocks.
3742 if (!CPInst->hasOneUse())
3743 return false;
3744
David Majnemer9f92f4c2016-05-21 05:12:32 +00003745 // Check that there are no other instructions except for benign intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003746 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
David Majnemer9f92f4c2016-05-21 05:12:32 +00003747 while (++I != E) {
3748 auto *II = dyn_cast<IntrinsicInst>(I);
3749 if (!II)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003750 return false;
3751
David Majnemer9f92f4c2016-05-21 05:12:32 +00003752 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
3753 switch (IntrinsicID) {
3754 case Intrinsic::dbg_declare:
3755 case Intrinsic::dbg_value:
3756 case Intrinsic::lifetime_end:
3757 break;
3758 default:
3759 return false;
3760 }
3761 }
3762
David Majnemer8a1c45d2015-12-12 05:38:55 +00003763 // If the cleanup return we are simplifying unwinds to the caller, this will
3764 // set UnwindDest to nullptr.
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003765 BasicBlock *UnwindDest = RI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003766 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003767
3768 // We're about to remove BB from the control flow. Before we do, sink any
3769 // PHINodes into the unwind destination. Doing this before changing the
3770 // control flow avoids some potentially slow checks, since we can currently
3771 // be certain that UnwindDest and BB have no common predecessors (since they
3772 // are both EH pads).
3773 if (UnwindDest) {
3774 // First, go through the PHI nodes in UnwindDest and update any nodes that
3775 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003776 for (BasicBlock::iterator I = UnwindDest->begin(),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003777 IE = DestEHPad->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003778 I != IE; ++I) {
3779 PHINode *DestPN = cast<PHINode>(I);
James Molloy4de84dd2015-11-04 15:28:04 +00003780
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003781 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003782 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003783 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003784 // This PHI node has an incoming value that corresponds to a control
3785 // path through the cleanup pad we are removing. If the incoming
3786 // value is in the cleanup pad, it must be a PHINode (because we
3787 // verified above that the block is otherwise empty). Otherwise, the
3788 // value is either a constant or a value that dominates the cleanup
3789 // pad being removed.
3790 //
3791 // Because BB and UnwindDest are both EH pads, all of their
3792 // predecessors must unwind to these blocks, and since no instruction
3793 // can have multiple unwind destinations, there will be no overlap in
3794 // incoming blocks between SrcPN and DestPN.
3795 Value *SrcVal = DestPN->getIncomingValue(Idx);
3796 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3797
3798 // Remove the entry for the block we are deleting.
3799 DestPN->removeIncomingValue(Idx, false);
3800
3801 if (SrcPN && SrcPN->getParent() == BB) {
3802 // If the incoming value was a PHI node in the cleanup pad we are
3803 // removing, we need to merge that PHI node's incoming values into
3804 // DestPN.
James Molloy4de84dd2015-11-04 15:28:04 +00003805 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
Dehao Chenf6c00832016-05-18 19:44:21 +00003806 SrcIdx != SrcE; ++SrcIdx) {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003807 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3808 SrcPN->getIncomingBlock(SrcIdx));
3809 }
3810 } else {
3811 // Otherwise, the incoming value came from above BB and
3812 // so we can just reuse it. We must associate all of BB's
3813 // predecessors with this value.
3814 for (auto *pred : predecessors(BB)) {
3815 DestPN->addIncoming(SrcVal, pred);
3816 }
3817 }
3818 }
3819
3820 // Sink any remaining PHI nodes directly into UnwindDest.
David Majnemer8a1c45d2015-12-12 05:38:55 +00003821 Instruction *InsertPt = DestEHPad;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003822 for (BasicBlock::iterator I = BB->begin(),
3823 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003824 I != IE;) {
3825 // The iterator must be incremented here because the instructions are
3826 // being moved to another block.
3827 PHINode *PN = cast<PHINode>(I++);
3828 if (PN->use_empty())
3829 // If the PHI node has no uses, just leave it. It will be erased
3830 // when we erase BB below.
3831 continue;
3832
3833 // Otherwise, sink this PHI node into UnwindDest.
3834 // Any predecessors to UnwindDest which are not already represented
3835 // must be back edges which inherit the value from the path through
3836 // BB. In this case, the PHI value must reference itself.
3837 for (auto *pred : predecessors(UnwindDest))
3838 if (pred != BB)
3839 PN->addIncoming(PN, pred);
3840 PN->moveBefore(InsertPt);
3841 }
3842 }
3843
3844 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3845 // The iterator must be updated here because we are removing this pred.
3846 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003847 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003848 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003849 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003850 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003851 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003852 }
3853 }
3854
3855 // The cleanup pad is now unreachable. Zap it.
3856 BB->eraseFromParent();
3857 return true;
3858}
3859
David Majnemer1efa23d2016-02-20 01:07:45 +00003860// Try to merge two cleanuppads together.
3861static bool mergeCleanupPad(CleanupReturnInst *RI) {
3862 // Skip any cleanuprets which unwind to caller, there is nothing to merge
3863 // with.
3864 BasicBlock *UnwindDest = RI->getUnwindDest();
3865 if (!UnwindDest)
3866 return false;
3867
3868 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
3869 // be safe to merge without code duplication.
3870 if (UnwindDest->getSinglePredecessor() != RI->getParent())
3871 return false;
3872
3873 // Verify that our cleanuppad's unwind destination is another cleanuppad.
3874 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
3875 if (!SuccessorCleanupPad)
3876 return false;
3877
3878 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
3879 // Replace any uses of the successor cleanupad with the predecessor pad
3880 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
3881 // funclet bundle operands.
3882 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
3883 // Remove the old cleanuppad.
3884 SuccessorCleanupPad->eraseFromParent();
3885 // Now, we simply replace the cleanupret with a branch to the unwind
3886 // destination.
3887 BranchInst::Create(UnwindDest, RI->getParent());
3888 RI->eraseFromParent();
3889
3890 return true;
3891}
3892
3893bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00003894 // It is possible to transiantly have an undef cleanuppad operand because we
3895 // have deleted some, but not all, dead blocks.
3896 // Eventually, this block will be deleted.
3897 if (isa<UndefValue>(RI->getOperand(0)))
3898 return false;
3899
David Majnemer9f92f4c2016-05-21 05:12:32 +00003900 if (mergeCleanupPad(RI))
David Majnemer1efa23d2016-02-20 01:07:45 +00003901 return true;
3902
David Majnemer9f92f4c2016-05-21 05:12:32 +00003903 if (removeEmptyCleanup(RI))
David Majnemer1efa23d2016-02-20 01:07:45 +00003904 return true;
3905
3906 return false;
3907}
3908
Devang Pateldd14e0f2011-05-18 21:33:11 +00003909bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003910 BasicBlock *BB = RI->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00003911 if (!BB->getFirstNonPHIOrDbg()->isTerminator())
3912 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003913
Chris Lattner25c3af32010-12-13 06:25:44 +00003914 // Find predecessors that end with branches.
Dehao Chenf6c00832016-05-18 19:44:21 +00003915 SmallVector<BasicBlock *, 8> UncondBranchPreds;
3916 SmallVector<BranchInst *, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003917 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3918 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003919 TerminatorInst *PTI = P->getTerminator();
3920 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3921 if (BI->isUnconditional())
3922 UncondBranchPreds.push_back(P);
3923 else
3924 CondBranchPreds.push_back(BI);
3925 }
3926 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003927
Chris Lattner25c3af32010-12-13 06:25:44 +00003928 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00003929 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003930 while (!UncondBranchPreds.empty()) {
3931 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3932 DEBUG(dbgs() << "FOLDING: " << *BB
Dehao Chenf6c00832016-05-18 19:44:21 +00003933 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00003934 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00003935 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003936
Chris Lattner25c3af32010-12-13 06:25:44 +00003937 // If we eliminated all predecessors of the block, delete the block now.
Hyojin Sung4673f102016-03-29 04:08:57 +00003938 if (pred_empty(BB)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003939 // We know there are no successors, so just nuke the block.
3940 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00003941 if (LoopHeaders)
3942 LoopHeaders->erase(BB);
Hyojin Sung4673f102016-03-29 04:08:57 +00003943 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003944
Chris Lattner25c3af32010-12-13 06:25:44 +00003945 return true;
3946 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003947
Chris Lattner25c3af32010-12-13 06:25:44 +00003948 // Check out all of the conditional branches going to this return
3949 // instruction. If any of them just select between returns, change the
3950 // branch itself into a select/return pair.
3951 while (!CondBranchPreds.empty()) {
3952 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003953
Chris Lattner25c3af32010-12-13 06:25:44 +00003954 // Check to see if the non-BB successor is also a return block.
3955 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3956 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003957 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003958 return true;
3959 }
3960 return false;
3961}
3962
Chris Lattner25c3af32010-12-13 06:25:44 +00003963bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3964 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003965
Chris Lattner25c3af32010-12-13 06:25:44 +00003966 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003967
Chris Lattner25c3af32010-12-13 06:25:44 +00003968 // If there are any instructions immediately before the unreachable that can
3969 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003970 while (UI->getIterator() != BB->begin()) {
3971 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00003972 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003973 // Do not delete instructions that can have side effects which might cause
3974 // the unreachable to not be reachable; specifically, calls and volatile
3975 // operations may have this effect.
Dehao Chenf6c00832016-05-18 19:44:21 +00003976 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
3977 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003978
3979 if (BBI->mayHaveSideEffects()) {
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003980 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003981 if (SI->isVolatile())
3982 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003983 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003984 if (LI->isVolatile())
3985 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003986 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003987 if (RMWI->isVolatile())
3988 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003989 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003990 if (CXI->isVolatile())
3991 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00003992 } else if (isa<CatchPadInst>(BBI)) {
3993 // A catchpad may invoke exception object constructors and such, which
3994 // in some languages can be arbitrary code, so be conservative by
3995 // default.
3996 // For CoreCLR, it just involves a type test, so can be removed.
3997 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
3998 EHPersonality::CoreCLR)
3999 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004000 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4001 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004002 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004003 }
Bill Wendling55d875f2011-08-16 20:41:17 +00004004 // Note that deleting LandingPad's here is in fact okay, although it
4005 // involves a bit of subtle reasoning. If this inst is a LandingPad,
4006 // all the predecessors of this block will be the unwind edges of Invokes,
4007 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004008 }
4009
Eli Friedmanaac35b32011-03-09 00:48:33 +00004010 // Delete this instruction (any uses are guaranteed to be dead)
4011 if (!BBI->use_empty())
4012 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00004013 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00004014 Changed = true;
4015 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004016
Chris Lattner25c3af32010-12-13 06:25:44 +00004017 // If the unreachable instruction is the first in the block, take a gander
4018 // at all of the predecessors of this instruction, and simplify them.
Dehao Chenf6c00832016-05-18 19:44:21 +00004019 if (&BB->front() != UI)
4020 return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004021
Dehao Chenf6c00832016-05-18 19:44:21 +00004022 SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner25c3af32010-12-13 06:25:44 +00004023 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
4024 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00004025 IRBuilder<> Builder(TI);
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004026 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004027 if (BI->isUnconditional()) {
4028 if (BI->getSuccessor(0) == BB) {
4029 new UnreachableInst(TI->getContext(), TI);
4030 TI->eraseFromParent();
4031 Changed = true;
4032 }
4033 } else {
4034 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00004035 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00004036 EraseTerminatorInstAndDCECond(BI);
4037 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00004038 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00004039 EraseTerminatorInstAndDCECond(BI);
4040 Changed = true;
4041 }
4042 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004043 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Dehao Chenf6c00832016-05-18 19:44:21 +00004044 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e;
4045 ++i)
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00004046 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004047 BB->removePredecessor(SI->getParent());
4048 SI->removeCase(i);
Dehao Chenf6c00832016-05-18 19:44:21 +00004049 --i;
4050 --e;
Chris Lattner25c3af32010-12-13 06:25:44 +00004051 Changed = true;
4052 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004053 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
4054 if (II->getUnwindDest() == BB) {
4055 removeUnwindEdge(TI->getParent());
4056 Changed = true;
4057 }
4058 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4059 if (CSI->getUnwindDest() == BB) {
4060 removeUnwindEdge(TI->getParent());
4061 Changed = true;
4062 continue;
4063 }
4064
4065 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
4066 E = CSI->handler_end();
4067 I != E; ++I) {
4068 if (*I == BB) {
4069 CSI->removeHandler(I);
4070 --I;
4071 --E;
4072 Changed = true;
4073 }
4074 }
4075 if (CSI->getNumHandlers() == 0) {
4076 BasicBlock *CatchSwitchBB = CSI->getParent();
4077 if (CSI->hasUnwindDest()) {
4078 // Redirect preds to the unwind dest
4079 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
4080 } else {
4081 // Rewrite all preds to unwind to caller (or from invoke to call).
4082 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
4083 for (BasicBlock *EHPred : EHPreds)
4084 removeUnwindEdge(EHPred);
4085 }
4086 // The catchswitch is no longer reachable.
4087 new UnreachableInst(CSI->getContext(), CSI);
4088 CSI->eraseFromParent();
4089 Changed = true;
4090 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004091 } else if (isa<CleanupReturnInst>(TI)) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00004092 new UnreachableInst(TI->getContext(), TI);
4093 TI->eraseFromParent();
4094 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004095 }
4096 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004097
Chris Lattner25c3af32010-12-13 06:25:44 +00004098 // If this block is now dead, remove it.
Dehao Chenf6c00832016-05-18 19:44:21 +00004099 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004100 // We know there are no successors, so just nuke the block.
4101 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00004102 if (LoopHeaders)
4103 LoopHeaders->erase(BB);
Chris Lattner25c3af32010-12-13 06:25:44 +00004104 return true;
4105 }
4106
4107 return Changed;
4108}
4109
Hans Wennborg68000082015-01-26 19:52:32 +00004110static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
4111 assert(Cases.size() >= 1);
4112
4113 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
4114 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
4115 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
4116 return false;
4117 }
4118 return true;
4119}
4120
4121/// Turn a switch with two reachable destinations into an integer range
4122/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004123static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00004124 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004125
Hans Wennborg68000082015-01-26 19:52:32 +00004126 bool HasDefault =
4127 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00004128
Hans Wennborg68000082015-01-26 19:52:32 +00004129 // Partition the cases into two sets with different destinations.
4130 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
4131 BasicBlock *DestB = nullptr;
Dehao Chenf6c00832016-05-18 19:44:21 +00004132 SmallVector<ConstantInt *, 16> CasesA;
4133 SmallVector<ConstantInt *, 16> CasesB;
Hans Wennborg68000082015-01-26 19:52:32 +00004134
4135 for (SwitchInst::CaseIt I : SI->cases()) {
4136 BasicBlock *Dest = I.getCaseSuccessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00004137 if (!DestA)
4138 DestA = Dest;
Hans Wennborg68000082015-01-26 19:52:32 +00004139 if (Dest == DestA) {
4140 CasesA.push_back(I.getCaseValue());
4141 continue;
4142 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004143 if (!DestB)
4144 DestB = Dest;
Hans Wennborg68000082015-01-26 19:52:32 +00004145 if (Dest == DestB) {
4146 CasesB.push_back(I.getCaseValue());
4147 continue;
4148 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004149 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00004150 }
4151
Dehao Chenf6c00832016-05-18 19:44:21 +00004152 assert(DestA && DestB &&
4153 "Single-destination switch should have been folded.");
Hans Wennborg68000082015-01-26 19:52:32 +00004154 assert(DestA != DestB);
4155 assert(DestB != SI->getDefaultDest());
4156 assert(!CasesB.empty() && "There must be non-default cases.");
4157 assert(!CasesA.empty() || HasDefault);
4158
4159 // Figure out if one of the sets of cases form a contiguous range.
4160 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
4161 BasicBlock *ContiguousDest = nullptr;
4162 BasicBlock *OtherDest = nullptr;
4163 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
4164 ContiguousCases = &CasesA;
4165 ContiguousDest = DestA;
4166 OtherDest = DestB;
4167 } else if (CasesAreContiguous(CasesB)) {
4168 ContiguousCases = &CasesB;
4169 ContiguousDest = DestB;
4170 OtherDest = DestA;
4171 } else
4172 return false;
4173
4174 // Start building the compare and branch.
4175
4176 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
Dehao Chenf6c00832016-05-18 19:44:21 +00004177 Constant *NumCases =
4178 ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004179
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00004180 Value *Sub = SI->getCondition();
4181 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00004182 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
4183
Hans Wennborgc9e1d992013-04-16 08:35:36 +00004184 Value *Cmp;
4185 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00004186 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00004187 Cmp = ConstantInt::getTrue(SI->getContext());
4188 else
4189 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00004190 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004191
Manman Ren56575552012-09-18 00:47:33 +00004192 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00004193 if (HasBranchWeights(SI)) {
4194 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00004195 GetBranchWeights(SI, Weights);
4196 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00004197 uint64_t TrueWeight = 0;
4198 uint64_t FalseWeight = 0;
4199 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
4200 if (SI->getSuccessor(I) == ContiguousDest)
4201 TrueWeight += Weights[I];
4202 else
4203 FalseWeight += Weights[I];
4204 }
4205 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4206 TrueWeight /= 2;
4207 FalseWeight /= 2;
4208 }
Manman Ren56575552012-09-18 00:47:33 +00004209 NewBI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00004210 MDBuilder(SI->getContext())
4211 .createBranchWeights((uint32_t)TrueWeight,
4212 (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00004213 }
4214 }
4215
Hans Wennborg68000082015-01-26 19:52:32 +00004216 // Prune obsolete incoming values off the successors' PHI nodes.
4217 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
4218 unsigned PreviousEdges = ContiguousCases->size();
Dehao Chenf6c00832016-05-18 19:44:21 +00004219 if (ContiguousDest == SI->getDefaultDest())
4220 ++PreviousEdges;
Hans Wennborg68000082015-01-26 19:52:32 +00004221 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004222 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4223 }
Hans Wennborg68000082015-01-26 19:52:32 +00004224 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
4225 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
Dehao Chenf6c00832016-05-18 19:44:21 +00004226 if (OtherDest == SI->getDefaultDest())
4227 ++PreviousEdges;
Hans Wennborg68000082015-01-26 19:52:32 +00004228 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4229 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4230 }
4231
4232 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004233 SI->eraseFromParent();
4234
4235 return true;
4236}
Chris Lattner25c3af32010-12-13 06:25:44 +00004237
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004238/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004239/// and use it to remove dead cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004240static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
4241 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004242 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00004243 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004244 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00004245 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004246
Sanjay Patel75892a12016-05-20 14:53:09 +00004247 // We can also eliminate cases by determining that their values are outside of
4248 // the limited range of the condition based on how many significant (non-sign)
4249 // bits are in the condition value.
4250 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
4251 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4252
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004253 // Gather dead cases.
Dehao Chenf6c00832016-05-18 19:44:21 +00004254 SmallVector<ConstantInt *, 8> DeadCases;
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004255 for (auto &Case : SI->cases()) {
Sanjay Patel75892a12016-05-20 14:53:09 +00004256 APInt CaseVal = Case.getCaseValue()->getValue();
4257 if ((CaseVal & KnownZero) != 0 || (CaseVal & KnownOne) != KnownOne ||
4258 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004259 DeadCases.push_back(Case.getCaseValue());
Sanjay Patel75892a12016-05-20 14:53:09 +00004260 DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal << " is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004261 }
4262 }
4263
Dehao Chenf6c00832016-05-18 19:44:21 +00004264 // If we can prove that the cases must cover all possible values, the
4265 // default destination becomes dead and we can remove it. If we know some
Philip Reames05370132015-09-10 17:44:47 +00004266 // of the bits in the value, we can use that to more precisely compute the
4267 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00004268 bool HasDefault =
Dehao Chenf6c00832016-05-18 19:44:21 +00004269 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4270 const unsigned NumUnknownBits =
4271 Bits - (KnownZero.Or(KnownOne)).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00004272 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00004273 if (HasDefault && DeadCases.empty() &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004274 NumUnknownBits < 64 /* avoid overflow */ &&
Philip Reames05370132015-09-10 17:44:47 +00004275 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00004276 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
Dehao Chenf6c00832016-05-18 19:44:21 +00004277 BasicBlock *NewDefault =
4278 SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004279 SI->setDefaultDest(&*NewDefault);
4280 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00004281 auto *OldTI = NewDefault->getTerminator();
4282 new UnreachableInst(SI->getContext(), OldTI);
4283 EraseTerminatorInstAndDCECond(OldTI);
4284 return true;
4285 }
4286
Manman Ren56575552012-09-18 00:47:33 +00004287 SmallVector<uint64_t, 8> Weights;
4288 bool HasWeight = HasBranchWeights(SI);
4289 if (HasWeight) {
4290 GetBranchWeights(SI, Weights);
4291 HasWeight = (Weights.size() == 1 + SI->getNumCases());
4292 }
4293
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004294 // Remove dead cases from the switch.
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004295 for (ConstantInt *DeadCase : DeadCases) {
4296 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCase);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00004297 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00004298 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00004299 if (HasWeight) {
Dehao Chenf6c00832016-05-18 19:44:21 +00004300 std::swap(Weights[Case.getCaseIndex() + 1], Weights.back());
Manman Ren56575552012-09-18 00:47:33 +00004301 Weights.pop_back();
4302 }
4303
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004304 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00004305 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004306 SI->removeCase(Case);
4307 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00004308 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00004309 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
4310 SI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00004311 MDBuilder(SI->getParent()->getContext())
4312 .createBranchWeights(MDWeights));
Manman Ren56575552012-09-18 00:47:33 +00004313 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004314
4315 return !DeadCases.empty();
4316}
4317
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004318/// If BB would be eligible for simplification by
4319/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004320/// by an unconditional branch), look at the phi node for BB in the successor
4321/// block and see if the incoming value is equal to CaseValue. If so, return
4322/// the phi node, and set PhiIndex to BB's index in the phi node.
4323static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
Dehao Chenf6c00832016-05-18 19:44:21 +00004324 BasicBlock *BB, int *PhiIndex) {
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004325 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00004326 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004327 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00004328 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004329
4330 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
4331 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00004332 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004333
4334 BasicBlock *Succ = Branch->getSuccessor(0);
4335
4336 BasicBlock::iterator I = Succ->begin();
4337 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4338 int Idx = PHI->getBasicBlockIndex(BB);
4339 assert(Idx >= 0 && "PHI has no entry for predecessor?");
4340
4341 Value *InValue = PHI->getIncomingValue(Idx);
Dehao Chenf6c00832016-05-18 19:44:21 +00004342 if (InValue != CaseValue)
4343 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004344
4345 *PhiIndex = Idx;
4346 return PHI;
4347 }
4348
Craig Topperf40110f2014-04-25 05:29:35 +00004349 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004350}
4351
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004352/// Try to forward the condition of a switch instruction to a phi node
4353/// dominated by the switch, if that would mean that some of the destination
4354/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004355/// Returns true if a change is made.
4356static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
Dehao Chenf6c00832016-05-18 19:44:21 +00004357 typedef DenseMap<PHINode *, SmallVector<int, 4>> ForwardingNodesMap;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004358 ForwardingNodesMap ForwardingNodes;
4359
Dehao Chenf6c00832016-05-18 19:44:21 +00004360 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E;
4361 ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00004362 ConstantInt *CaseValue = I.getCaseValue();
4363 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004364
4365 int PhiIndex;
Dehao Chenf6c00832016-05-18 19:44:21 +00004366 PHINode *PHI =
4367 FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIndex);
4368 if (!PHI)
4369 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004370
4371 ForwardingNodes[PHI].push_back(PhiIndex);
4372 }
4373
4374 bool Changed = false;
4375
4376 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
Dehao Chenf6c00832016-05-18 19:44:21 +00004377 E = ForwardingNodes.end();
4378 I != E; ++I) {
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004379 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00004380 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004381
Dehao Chenf6c00832016-05-18 19:44:21 +00004382 if (Indexes.size() < 2)
4383 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004384
4385 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
4386 Phi->setIncomingValue(Indexes[I], SI->getCondition());
4387 Changed = true;
4388 }
4389
4390 return Changed;
4391}
4392
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004393/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004394/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00004395static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00004396 if (C->isThreadDependent())
4397 return false;
4398 if (C->isDLLImportDependent())
4399 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004400
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00004401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
4402 return CE->isGEPWithNoNotionalOverIndexing();
4403
Dehao Chenf6c00832016-05-18 19:44:21 +00004404 return isa<ConstantFP>(C) || isa<ConstantInt>(C) ||
4405 isa<ConstantPointerNull>(C) || isa<GlobalValue>(C) ||
4406 isa<UndefValue>(C);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004407}
4408
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004409/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004410/// its constant value in ConstantPool, returning 0 if it's not there.
Dehao Chenf6c00832016-05-18 19:44:21 +00004411static Constant *
4412LookupConstant(Value *V,
4413 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00004414 if (Constant *C = dyn_cast<Constant>(V))
4415 return C;
4416 return ConstantPool.lookup(V);
4417}
4418
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004419/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004420/// simple instructions such as binary operations where both operands are
4421/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004422/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00004423static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004424ConstantFold(Instruction *I, const DataLayout &DL,
4425 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004426 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00004427 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
4428 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00004429 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00004430 if (A->isAllOnesValue())
4431 return LookupConstant(Select->getTrueValue(), ConstantPool);
4432 if (A->isNullValue())
4433 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00004434 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004435 }
4436
Benjamin Kramer7c302602013-11-12 12:24:36 +00004437 SmallVector<Constant *, 4> COps;
4438 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
4439 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
4440 COps.push_back(A);
4441 else
Craig Topperf40110f2014-04-25 05:29:35 +00004442 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004443 }
4444
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004445 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00004446 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4447 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004448 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00004449
Manuel Jacobe9024592016-01-21 06:33:22 +00004450 return ConstantFoldInstOperands(I, COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004451}
4452
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004453/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004454/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004455/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004456/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00004457static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004458GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00004459 BasicBlock **CommonDest,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004460 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
4461 const DataLayout &DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004462 // The block from which we enter the common destination.
4463 BasicBlock *Pred = SI->getParent();
4464
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004465 // If CaseDest is empty except for some side-effect free instructions through
4466 // which we can constant-propagate the CaseVal, continue to its successor.
Dehao Chenf6c00832016-05-18 19:44:21 +00004467 SmallDenseMap<Value *, Constant *> ConstantPool;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004468 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4469 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4470 ++I) {
4471 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4472 // If the terminator is a simple branch, continue to the next block.
4473 if (T->getNumSuccessors() != 1)
4474 return false;
4475 Pred = CaseDest;
4476 CaseDest = T->getSuccessor(0);
4477 } else if (isa<DbgInfoIntrinsic>(I)) {
4478 // Skip debug intrinsic.
4479 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004480 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004481 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00004482
4483 // If the instruction has uses outside this block or a phi node slot for
4484 // the block, it is not safe to bypass the instruction since it would then
4485 // no longer dominate all its uses.
4486 for (auto &Use : I->uses()) {
4487 User *User = Use.getUser();
4488 if (Instruction *I = dyn_cast<Instruction>(User))
4489 if (I->getParent() == CaseDest)
4490 continue;
4491 if (PHINode *Phi = dyn_cast<PHINode>(User))
4492 if (Phi->getIncomingBlock(Use) == CaseDest)
4493 continue;
4494 return false;
4495 }
4496
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004497 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004498 } else {
4499 break;
4500 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004501 }
4502
4503 // If we did not have a CommonDest before, use the current one.
4504 if (!*CommonDest)
4505 *CommonDest = CaseDest;
4506 // If the destination isn't the common one, abort.
4507 if (CaseDest != *CommonDest)
4508 return false;
4509
4510 // Get the values for this case from phi nodes in the destination block.
4511 BasicBlock::iterator I = (*CommonDest)->begin();
4512 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4513 int Idx = PHI->getBasicBlockIndex(Pred);
4514 if (Idx == -1)
4515 continue;
4516
Dehao Chenf6c00832016-05-18 19:44:21 +00004517 Constant *ConstVal =
4518 LookupConstant(PHI->getIncomingValue(Idx), ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004519 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004520 return false;
4521
4522 // Be conservative about which kinds of constants we support.
4523 if (!ValidLookupTableConstant(ConstVal))
4524 return false;
4525
4526 Res.push_back(std::make_pair(PHI, ConstVal));
4527 }
4528
Hans Wennborgac114a32014-01-12 00:44:41 +00004529 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004530}
4531
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004532// Helper function used to add CaseVal to the list of cases that generate
4533// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004534static void MapCaseToResult(ConstantInt *CaseVal,
Dehao Chenf6c00832016-05-18 19:44:21 +00004535 SwitchCaseResultVectorTy &UniqueResults,
4536 Constant *Result) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004537 for (auto &I : UniqueResults) {
4538 if (I.first == Result) {
4539 I.second.push_back(CaseVal);
4540 return;
4541 }
4542 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004543 UniqueResults.push_back(
4544 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004545}
4546
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004547// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004548// results for the PHI node of the common destination block for a switch
4549// instruction. Returns false if multiple PHI nodes have been found or if
4550// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004551static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4552 BasicBlock *&CommonDest,
4553 SwitchCaseResultVectorTy &UniqueResults,
4554 Constant *&DefaultResult,
4555 const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004556 for (auto &I : SI->cases()) {
4557 ConstantInt *CaseVal = I.getCaseValue();
4558
4559 // Resulting value at phi nodes for this case value.
4560 SwitchCaseResultsTy Results;
4561 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
4562 DL))
4563 return false;
4564
4565 // Only one value per case is permitted
4566 if (Results.size() > 1)
4567 return false;
4568 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4569
4570 // Check the PHI consistency.
4571 if (!PHI)
4572 PHI = Results[0].first;
4573 else if (PHI != Results[0].first)
4574 return false;
4575 }
4576 // Find the default result value.
4577 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4578 BasicBlock *DefaultDest = SI->getDefaultDest();
4579 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
4580 DL);
4581 // If the default value is not found abort unless the default destination
4582 // is unreachable.
4583 DefaultResult =
4584 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4585 if ((!DefaultResult &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004586 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004587 return false;
4588
4589 return true;
4590}
4591
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004592// Helper function that checks if it is possible to transform a switch with only
4593// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004594// Example:
4595// switch (a) {
4596// case 10: %0 = icmp eq i32 %a, 10
4597// return 10; %1 = select i1 %0, i32 10, i32 4
4598// case 20: ----> %2 = icmp eq i32 %a, 20
4599// return 2; %3 = select i1 %2, i32 2, i32 %1
4600// default:
4601// return 4;
4602// }
Dehao Chenf6c00832016-05-18 19:44:21 +00004603static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4604 Constant *DefaultResult, Value *Condition,
4605 IRBuilder<> &Builder) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004606 assert(ResultVector.size() == 2 &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004607 "We should have exactly two unique results at this point");
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004608 // If we are selecting between only two cases transform into a simple
4609 // select or a two-way select if default is possible.
4610 if (ResultVector[0].second.size() == 1 &&
4611 ResultVector[1].second.size() == 1) {
4612 ConstantInt *const FirstCase = ResultVector[0].second[0];
4613 ConstantInt *const SecondCase = ResultVector[1].second[0];
4614
4615 bool DefaultCanTrigger = DefaultResult;
4616 Value *SelectValue = ResultVector[1].first;
4617 if (DefaultCanTrigger) {
4618 Value *const ValueCompare =
4619 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4620 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4621 DefaultResult, "switch.select");
4622 }
4623 Value *const ValueCompare =
4624 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
Dehao Chenf6c00832016-05-18 19:44:21 +00004625 return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
4626 SelectValue, "switch.select");
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004627 }
4628
4629 return nullptr;
4630}
4631
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004632// Helper function to cleanup a switch instruction that has been converted into
4633// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004634static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4635 Value *SelectValue,
4636 IRBuilder<> &Builder) {
4637 BasicBlock *SelectBB = SI->getParent();
4638 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4639 PHI->removeIncomingValue(SelectBB);
4640 PHI->addIncoming(SelectValue, SelectBB);
4641
4642 Builder.CreateBr(PHI->getParent());
4643
4644 // Remove the switch.
4645 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4646 BasicBlock *Succ = SI->getSuccessor(i);
4647
4648 if (Succ == PHI->getParent())
4649 continue;
4650 Succ->removePredecessor(SelectBB);
4651 }
4652 SI->eraseFromParent();
4653}
4654
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004655/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004656/// phi nodes in a common successor block with only two different
4657/// constant values, replace the switch with select.
4658static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004659 AssumptionCache *AC, const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004660 Value *const Cond = SI->getCondition();
4661 PHINode *PHI = nullptr;
4662 BasicBlock *CommonDest = nullptr;
4663 Constant *DefaultResult;
4664 SwitchCaseResultVectorTy UniqueResults;
4665 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004666 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4667 DL))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004668 return false;
4669 // Selects choose between maximum two values.
4670 if (UniqueResults.size() != 2)
4671 return false;
4672 assert(PHI != nullptr && "PHI for value select not found");
4673
4674 Builder.SetInsertPoint(SI);
Dehao Chenf6c00832016-05-18 19:44:21 +00004675 Value *SelectValue =
4676 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004677 if (SelectValue) {
4678 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4679 return true;
4680 }
4681 // The switch couldn't be converted into a select.
4682 return false;
4683}
4684
Hans Wennborg776d7122012-09-26 09:34:53 +00004685namespace {
Dehao Chenf6c00832016-05-18 19:44:21 +00004686/// This class represents a lookup table that can be used to replace a switch.
4687class SwitchLookupTable {
4688public:
4689 /// Create a lookup table to use as a switch replacement with the contents
4690 /// of Values, using DefaultValue to fill any holes in the table.
4691 SwitchLookupTable(
4692 Module &M, uint64_t TableSize, ConstantInt *Offset,
4693 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4694 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004695
Dehao Chenf6c00832016-05-18 19:44:21 +00004696 /// Build instructions with Builder to retrieve the value at
4697 /// the position given by Index in the lookup table.
4698 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00004699
Dehao Chenf6c00832016-05-18 19:44:21 +00004700 /// Return true if a table with TableSize elements of
4701 /// type ElementType would fit in a target-legal register.
4702 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
4703 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004704
Dehao Chenf6c00832016-05-18 19:44:21 +00004705private:
4706 // Depending on the contents of the table, it can be represented in
4707 // different ways.
4708 enum {
4709 // For tables where each element contains the same value, we just have to
4710 // store that single value and return it for each lookup.
4711 SingleValueKind,
Hans Wennborg776d7122012-09-26 09:34:53 +00004712
Dehao Chenf6c00832016-05-18 19:44:21 +00004713 // For tables where there is a linear relationship between table index
4714 // and values. We calculate the result with a simple multiplication
4715 // and addition instead of a table lookup.
4716 LinearMapKind,
Erik Eckstein105374f2014-11-17 09:13:57 +00004717
Dehao Chenf6c00832016-05-18 19:44:21 +00004718 // For small tables with integer elements, we can pack them into a bitmap
4719 // that fits into a target-legal register. Values are retrieved by
4720 // shift and mask operations.
4721 BitMapKind,
Hans Wennborg39583b82012-09-26 09:44:49 +00004722
Dehao Chenf6c00832016-05-18 19:44:21 +00004723 // The table is stored as an array of values. Values are retrieved by load
4724 // instructions from the table.
4725 ArrayKind
4726 } Kind;
Hans Wennborg776d7122012-09-26 09:34:53 +00004727
Dehao Chenf6c00832016-05-18 19:44:21 +00004728 // For SingleValueKind, this is the single value.
4729 Constant *SingleValue;
Hans Wennborg776d7122012-09-26 09:34:53 +00004730
Dehao Chenf6c00832016-05-18 19:44:21 +00004731 // For BitMapKind, this is the bitmap.
4732 ConstantInt *BitMap;
4733 IntegerType *BitMapElementTy;
Hans Wennborg39583b82012-09-26 09:44:49 +00004734
Dehao Chenf6c00832016-05-18 19:44:21 +00004735 // For LinearMapKind, these are the constants used to derive the value.
4736 ConstantInt *LinearOffset;
4737 ConstantInt *LinearMultiplier;
Erik Eckstein105374f2014-11-17 09:13:57 +00004738
Dehao Chenf6c00832016-05-18 19:44:21 +00004739 // For ArrayKind, this is the array.
4740 GlobalVariable *Array;
4741};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00004742}
Hans Wennborg776d7122012-09-26 09:34:53 +00004743
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004744SwitchLookupTable::SwitchLookupTable(
4745 Module &M, uint64_t TableSize, ConstantInt *Offset,
4746 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4747 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00004748 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00004749 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004750 assert(Values.size() && "Can't build lookup table without values!");
4751 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004752
4753 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00004754 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004755
Hans Wennborgac114a32014-01-12 00:44:41 +00004756 Type *ValueType = Values.begin()->second->getType();
4757
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004758 // Build up the table contents.
Dehao Chenf6c00832016-05-18 19:44:21 +00004759 SmallVector<Constant *, 64> TableContents(TableSize);
Hans Wennborg776d7122012-09-26 09:34:53 +00004760 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4761 ConstantInt *CaseVal = Values[I].first;
4762 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00004763 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004764
Dehao Chenf6c00832016-05-18 19:44:21 +00004765 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004766 TableContents[Idx] = CaseRes;
4767
Hans Wennborg776d7122012-09-26 09:34:53 +00004768 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004769 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004770 }
4771
4772 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00004773 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00004774 assert(DefaultValue &&
4775 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00004776 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00004777 for (uint64_t I = 0; I < TableSize; ++I) {
4778 if (!TableContents[I])
4779 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004780 }
4781
Hans Wennborg776d7122012-09-26 09:34:53 +00004782 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004783 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004784 }
4785
Hans Wennborg776d7122012-09-26 09:34:53 +00004786 // If each element in the table contains the same value, we only need to store
4787 // that single value.
4788 if (SingleValue) {
4789 Kind = SingleValueKind;
4790 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004791 }
4792
Erik Eckstein105374f2014-11-17 09:13:57 +00004793 // Check if we can derive the value with a linear transformation from the
4794 // table index.
4795 if (isa<IntegerType>(ValueType)) {
4796 bool LinearMappingPossible = true;
4797 APInt PrevVal;
4798 APInt DistToPrev;
4799 assert(TableSize >= 2 && "Should be a SingleValue table.");
4800 // Check if there is the same distance between two consecutive values.
4801 for (uint64_t I = 0; I < TableSize; ++I) {
4802 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4803 if (!ConstVal) {
4804 // This is an undef. We could deal with it, but undefs in lookup tables
4805 // are very seldom. It's probably not worth the additional complexity.
4806 LinearMappingPossible = false;
4807 break;
4808 }
4809 APInt Val = ConstVal->getValue();
4810 if (I != 0) {
4811 APInt Dist = Val - PrevVal;
4812 if (I == 1) {
4813 DistToPrev = Dist;
4814 } else if (Dist != DistToPrev) {
4815 LinearMappingPossible = false;
4816 break;
4817 }
4818 }
4819 PrevVal = Val;
4820 }
4821 if (LinearMappingPossible) {
4822 LinearOffset = cast<ConstantInt>(TableContents[0]);
4823 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4824 Kind = LinearMapKind;
4825 ++NumLinearMaps;
4826 return;
4827 }
4828 }
4829
Hans Wennborg39583b82012-09-26 09:44:49 +00004830 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004831 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004832 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004833 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4834 for (uint64_t I = TableSize; I > 0; --I) {
4835 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00004836 // Insert values into the bitmap. Undef values are set to zero.
4837 if (!isa<UndefValue>(TableContents[I - 1])) {
4838 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4839 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4840 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004841 }
4842 BitMap = ConstantInt::get(M.getContext(), TableInt);
4843 BitMapElementTy = IT;
4844 Kind = BitMapKind;
4845 ++NumBitMaps;
4846 return;
4847 }
4848
Hans Wennborg776d7122012-09-26 09:34:53 +00004849 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004850 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004851 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4852
Dehao Chenf6c00832016-05-18 19:44:21 +00004853 Array = new GlobalVariable(M, ArrayTy, /*constant=*/true,
4854 GlobalVariable::PrivateLinkage, Initializer,
Hans Wennborg776d7122012-09-26 09:34:53 +00004855 "switch.table");
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004856 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Hans Wennborg776d7122012-09-26 09:34:53 +00004857 Kind = ArrayKind;
4858}
4859
Manman Ren4d189fb2014-07-24 21:13:20 +00004860Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004861 switch (Kind) {
Dehao Chenf6c00832016-05-18 19:44:21 +00004862 case SingleValueKind:
4863 return SingleValue;
4864 case LinearMapKind: {
4865 // Derive the result value from the input value.
4866 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4867 false, "switch.idx.cast");
4868 if (!LinearMultiplier->isOne())
4869 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4870 if (!LinearOffset->isZero())
4871 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4872 return Result;
4873 }
4874 case BitMapKind: {
4875 // Type of the bitmap (e.g. i59).
4876 IntegerType *MapTy = BitMap->getType();
Hans Wennborg39583b82012-09-26 09:44:49 +00004877
Dehao Chenf6c00832016-05-18 19:44:21 +00004878 // Cast Index to the same type as the bitmap.
4879 // Note: The Index is <= the number of elements in the table, so
4880 // truncating it to the width of the bitmask is safe.
4881 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004882
Dehao Chenf6c00832016-05-18 19:44:21 +00004883 // Multiply the shift amount by the element width.
4884 ShiftAmt = Builder.CreateMul(
4885 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4886 "switch.shiftamt");
Hans Wennborg39583b82012-09-26 09:44:49 +00004887
Dehao Chenf6c00832016-05-18 19:44:21 +00004888 // Shift down.
4889 Value *DownShifted =
4890 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
4891 // Mask off.
4892 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
4893 }
4894 case ArrayKind: {
4895 // Make sure the table index will not overflow when treated as signed.
4896 IntegerType *IT = cast<IntegerType>(Index->getType());
4897 uint64_t TableSize =
4898 Array->getInitializer()->getType()->getArrayNumElements();
4899 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4900 Index = Builder.CreateZExt(
4901 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
4902 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00004903
Dehao Chenf6c00832016-05-18 19:44:21 +00004904 Value *GEPIndices[] = {Builder.getInt32(0), Index};
4905 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4906 GEPIndices, "switch.gep");
4907 return Builder.CreateLoad(GEP, "switch.load");
4908 }
Hans Wennborg776d7122012-09-26 09:34:53 +00004909 }
4910 llvm_unreachable("Unknown lookup table kind!");
4911}
4912
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004913bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00004914 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004915 Type *ElementType) {
4916 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004917 if (!IT)
4918 return false;
4919 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4920 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004921
4922 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
Dehao Chenf6c00832016-05-18 19:44:21 +00004923 if (TableSize >= UINT_MAX / IT->getBitWidth())
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004924 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004925 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00004926}
4927
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004928/// Determine whether a lookup table should be built for this switch, based on
4929/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004930static bool
4931ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4932 const TargetTransformInfo &TTI, const DataLayout &DL,
4933 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004934 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4935 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00004936
Chandler Carruth77d433d2012-11-30 09:26:25 +00004937 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00004938 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00004939 for (const auto &I : ResultTypes) {
4940 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004941
4942 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004943 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004944
4945 // Saturate this flag to false.
Dehao Chenf6c00832016-05-18 19:44:21 +00004946 AllTablesFitInRegister =
4947 AllTablesFitInRegister &&
4948 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004949
4950 // If both flags saturate, we're done. NOTE: This *only* works with
4951 // saturating flags, and all flags have to saturate first due to the
4952 // non-deterministic behavior of iterating over a dense map.
4953 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00004954 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00004955 }
Evan Cheng65df8082012-11-30 02:02:42 +00004956
Chandler Carruth77d433d2012-11-30 09:26:25 +00004957 // If each table would fit in a register, we should build it anyway.
4958 if (AllTablesFitInRegister)
4959 return true;
4960
4961 // Don't build a table that doesn't fit in-register if it has illegal types.
4962 if (HasIllegalType)
4963 return false;
4964
4965 // The table density should be at least 40%. This is the same criterion as for
4966 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4967 // FIXME: Find the best cut-off.
4968 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004969}
4970
Erik Eckstein0d86c762014-11-27 15:13:14 +00004971/// Try to reuse the switch table index compare. Following pattern:
4972/// \code
4973/// if (idx < tablesize)
4974/// r = table[idx]; // table does not contain default_value
4975/// else
4976/// r = default_value;
4977/// if (r != default_value)
4978/// ...
4979/// \endcode
4980/// Is optimized to:
4981/// \code
4982/// cond = idx < tablesize;
4983/// if (cond)
4984/// r = table[idx];
4985/// else
4986/// r = default_value;
4987/// if (cond)
4988/// ...
4989/// \endcode
4990/// Jump threading will then eliminate the second if(cond).
Dehao Chenf6c00832016-05-18 19:44:21 +00004991static void reuseTableCompare(
4992 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
4993 Constant *DefaultValue,
4994 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
Erik Eckstein0d86c762014-11-27 15:13:14 +00004995
4996 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4997 if (!CmpInst)
4998 return;
4999
5000 // We require that the compare is in the same block as the phi so that jump
5001 // threading can do its work afterwards.
5002 if (CmpInst->getParent() != PhiBlock)
5003 return;
5004
5005 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
5006 if (!CmpOp1)
5007 return;
5008
5009 Value *RangeCmp = RangeCheckBranch->getCondition();
5010 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
5011 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
5012
5013 // Check if the compare with the default value is constant true or false.
5014 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5015 DefaultValue, CmpOp1, true);
5016 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5017 return;
5018
5019 // Check if the compare with the case values is distinct from the default
5020 // compare result.
5021 for (auto ValuePair : Values) {
5022 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
Dehao Chenf6c00832016-05-18 19:44:21 +00005023 ValuePair.second, CmpOp1, true);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005024 if (!CaseConst || CaseConst == DefaultConst)
5025 return;
5026 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5027 "Expect true or false as compare result.");
5028 }
Dehao Chenf6c00832016-05-18 19:44:21 +00005029
Erik Eckstein0d86c762014-11-27 15:13:14 +00005030 // Check if the branch instruction dominates the phi node. It's a simple
5031 // dominance check, but sufficient for our needs.
5032 // Although this check is invariant in the calling loops, it's better to do it
5033 // at this late stage. Practically we do it at most once for a switch.
5034 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
5035 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
5036 BasicBlock *Pred = *PI;
5037 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
5038 return;
5039 }
5040
5041 if (DefaultConst == FalseConst) {
5042 // The compare yields the same result. We can replace it.
5043 CmpInst->replaceAllUsesWith(RangeCmp);
5044 ++NumTableCmpReuses;
5045 } else {
5046 // The compare yields the same result, just inverted. We can replace it.
Dehao Chenf6c00832016-05-18 19:44:21 +00005047 Value *InvertedTableCmp = BinaryOperator::CreateXor(
5048 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
5049 RangeCheckBranch);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005050 CmpInst->replaceAllUsesWith(InvertedTableCmp);
5051 ++NumTableCmpReuses;
5052 }
5053}
5054
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005055/// If the switch is only used to initialize one or more phi nodes in a common
5056/// successor block with different constant values, replace the switch with
5057/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005058static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
5059 const DataLayout &DL,
5060 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005061 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00005062
Hans Wennborgc3c8d952012-11-07 21:35:12 +00005063 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005064 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00005065 return false;
5066
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005067 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
5068 // split off a dense part and build a lookup table for that.
5069
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005070 // FIXME: This creates arrays of GEPs to constant strings, which means each
5071 // GEP needs a runtime relocation in PIC code. We should just build one big
5072 // string and lookup indices into that.
5073
Dehao Chenf6c00832016-05-18 19:44:21 +00005074 // Ignore switches with less than three cases. Lookup tables will not make
5075 // them
Hans Wennborg4744ac12014-01-15 05:00:27 +00005076 // faster, so we don't analyze them.
5077 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005078 return false;
5079
5080 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00005081 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005082 assert(SI->case_begin() != SI->case_end());
5083 SwitchInst::CaseIt CI = SI->case_begin();
5084 ConstantInt *MinCaseVal = CI.getCaseValue();
5085 ConstantInt *MaxCaseVal = CI.getCaseValue();
5086
Craig Topperf40110f2014-04-25 05:29:35 +00005087 BasicBlock *CommonDest = nullptr;
Dehao Chenf6c00832016-05-18 19:44:21 +00005088 typedef SmallVector<std::pair<ConstantInt *, Constant *>, 4> ResultListTy;
5089 SmallDenseMap<PHINode *, ResultListTy> ResultLists;
5090 SmallDenseMap<PHINode *, Constant *> DefaultResults;
5091 SmallDenseMap<PHINode *, Type *> ResultTypes;
5092 SmallVector<PHINode *, 4> PHIs;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005093
5094 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
5095 ConstantInt *CaseVal = CI.getCaseValue();
5096 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
5097 MinCaseVal = CaseVal;
5098 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
5099 MaxCaseVal = CaseVal;
5100
5101 // Resulting value at phi nodes for this case value.
Dehao Chenf6c00832016-05-18 19:44:21 +00005102 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> ResultsTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005103 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00005104 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005105 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005106 return false;
5107
5108 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00005109 for (const auto &I : Results) {
5110 PHINode *PHI = I.first;
5111 Constant *Value = I.second;
5112 if (!ResultLists.count(PHI))
5113 PHIs.push_back(PHI);
5114 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005115 }
5116 }
5117
Hans Wennborgac114a32014-01-12 00:44:41 +00005118 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00005119 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00005120 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5121 }
5122
5123 uint64_t NumResults = ResultLists[PHIs[0]].size();
5124 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
5125 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
5126 bool TableHasHoles = (NumResults < TableSize);
5127
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005128 // If the table has holes, we need a constant result for the default case
5129 // or a bitmask that fits in a register.
Dehao Chenf6c00832016-05-18 19:44:21 +00005130 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00005131 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005132 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00005133
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005134 bool NeedMask = (TableHasHoles && !HasDefaultResults);
5135 if (NeedMask) {
5136 // As an extra penalty for the validity test we require more cases.
Dehao Chenf6c00832016-05-18 19:44:21 +00005137 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005138 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005139 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005140 return false;
5141 }
Hans Wennborgac114a32014-01-12 00:44:41 +00005142
Hans Wennborga6a11a92014-11-18 02:37:11 +00005143 for (const auto &I : DefaultResultsList) {
5144 PHINode *PHI = I.first;
5145 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00005146 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005147 }
5148
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005149 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005150 return false;
5151
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005152 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00005153 Module &Mod = *CommonDest->getParent()->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00005154 BasicBlock *LookupBB = BasicBlock::Create(
5155 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005156
Michael Gottesmanc024f322013-10-20 07:04:37 +00005157 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005158 Builder.SetInsertPoint(SI);
Dehao Chenf6c00832016-05-18 19:44:21 +00005159 Value *TableIndex =
5160 Builder.CreateSub(SI->getCondition(), MinCaseVal, "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00005161
5162 // Compute the maximum table size representable by the integer type we are
5163 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005164 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00005165 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00005166 assert(MaxTableSize >= TableSize &&
5167 "It is impossible for a switch to have more entries than the max "
5168 "representable value of its input integer type's size.");
5169
Hans Wennborgb64cb272015-01-26 19:52:34 +00005170 // If the default destination is unreachable, or if the lookup table covers
5171 // all values of the conditional variable, branch directly to the lookup table
5172 // BB. Otherwise, check that the condition is within the case range.
5173 const bool DefaultIsReachable =
5174 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5175 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005176 BranchInst *RangeCheckBranch = nullptr;
5177
Hans Wennborgb64cb272015-01-26 19:52:34 +00005178 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00005179 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00005180 // Note: We call removeProdecessor later since we need to be able to get the
5181 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00005182 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00005183 Value *Cmp = Builder.CreateICmpULT(
5184 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
5185 RangeCheckBranch =
5186 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00005187 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005188
5189 // Populate the BB that does the lookups.
5190 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005191
5192 if (NeedMask) {
5193 // Before doing the lookup we do the hole check.
5194 // The LookupBB is therefore re-purposed to do the hole check
5195 // and we create a new LookupBB.
5196 BasicBlock *MaskBB = LookupBB;
5197 MaskBB->setName("switch.hole_check");
Dehao Chenf6c00832016-05-18 19:44:21 +00005198 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
5199 CommonDest->getParent(), CommonDest);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005200
Juergen Ributzkac9591e92014-11-17 19:39:56 +00005201 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
5202 // unnecessary illegal types.
5203 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
5204 APInt MaskInt(TableSizePowOf2, 0);
5205 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005206 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005207 const ResultListTy &ResultList = ResultLists[PHIs[0]];
5208 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005209 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
5210 .getLimitedValue();
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005211 MaskInt |= One << Idx;
5212 }
5213 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
5214
5215 // Get the TableIndex'th bit of the bitmask.
5216 // If this bit is 0 (meaning hole) jump to the default destination,
5217 // else continue with table lookup.
5218 IntegerType *MapTy = TableMask->getType();
Dehao Chenf6c00832016-05-18 19:44:21 +00005219 Value *MaskIndex =
5220 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
5221 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
5222 Value *LoBit = Builder.CreateTrunc(
5223 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005224 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
5225
5226 Builder.SetInsertPoint(LookupBB);
5227 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
5228 }
5229
Hans Wennborg86ac6302015-04-24 20:57:56 +00005230 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
5231 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
5232 // do not delete PHINodes here.
5233 SI->getDefaultDest()->removePredecessor(SI->getParent(),
5234 /*DontDeleteUselessPHIs=*/true);
5235 }
5236
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005237 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00005238 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
5239 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00005240 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005241
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005242 // If using a bitmask, use any value to fill the lookup table holes.
5243 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00005244 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00005245
Manman Ren4d189fb2014-07-24 21:13:20 +00005246 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005247
Hans Wennborgf744fa92012-09-19 14:24:21 +00005248 // If the result is used to return immediately from the function, we want to
5249 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005250 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5251 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00005252 Builder.CreateRet(Result);
5253 ReturnedEarly = true;
5254 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005255 }
5256
Erik Eckstein0d86c762014-11-27 15:13:14 +00005257 // Do a small peephole optimization: re-use the switch table compare if
5258 // possible.
5259 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5260 BasicBlock *PhiBlock = PHI->getParent();
5261 // Search for compare instructions which use the phi.
5262 for (auto *User : PHI->users()) {
5263 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
5264 }
5265 }
5266
Hans Wennborgf744fa92012-09-19 14:24:21 +00005267 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005268 }
5269
5270 if (!ReturnedEarly)
5271 Builder.CreateBr(CommonDest);
5272
5273 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005274 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005275 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00005276
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005277 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00005278 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005279 Succ->removePredecessor(SI->getParent());
5280 }
5281 SI->eraseFromParent();
5282
5283 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005284 if (NeedMask)
5285 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005286 return true;
5287}
5288
James Molloyb2e436d2016-08-01 07:45:11 +00005289static bool isSwitchDense(ArrayRef<int64_t> Values) {
5290 // See also SelectionDAGBuilder::isDense(), which this function was based on.
5291 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
5292 uint64_t Range = Diff + 1;
5293 uint64_t NumCases = Values.size();
5294 // 40% is the default density for building a jump table in optsize/minsize mode.
5295 uint64_t MinDensity = 40;
Junmo Parkdb8f6ee2016-08-02 04:38:27 +00005296
James Molloyb2e436d2016-08-01 07:45:11 +00005297 return NumCases * 100 >= Range * MinDensity;
5298}
5299
5300// Try and transform a switch that has "holes" in it to a contiguous sequence
5301// of cases.
5302//
5303// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
5304// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
5305//
5306// This converts a sparse switch into a dense switch which allows better
5307// lowering and could also allow transforming into a lookup table.
5308static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
5309 const DataLayout &DL,
5310 const TargetTransformInfo &TTI) {
5311 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
5312 if (CondTy->getIntegerBitWidth() > 64 ||
5313 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
5314 return false;
5315 // Only bother with this optimization if there are more than 3 switch cases;
5316 // SDAG will only bother creating jump tables for 4 or more cases.
5317 if (SI->getNumCases() < 4)
5318 return false;
5319
5320 // This transform is agnostic to the signedness of the input or case values. We
5321 // can treat the case values as signed or unsigned. We can optimize more common
5322 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
5323 // as signed.
5324 SmallVector<int64_t,4> Values;
5325 for (auto &C : SI->cases())
5326 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
5327 std::sort(Values.begin(), Values.end());
5328
5329 // If the switch is already dense, there's nothing useful to do here.
5330 if (isSwitchDense(Values))
5331 return false;
5332
5333 // First, transform the values such that they start at zero and ascend.
5334 int64_t Base = Values[0];
5335 for (auto &V : Values)
5336 V -= Base;
5337
5338 // Now we have signed numbers that have been shifted so that, given enough
5339 // precision, there are no negative values. Since the rest of the transform
5340 // is bitwise only, we switch now to an unsigned representation.
5341 uint64_t GCD = 0;
5342 for (auto &V : Values)
5343 GCD = llvm::GreatestCommonDivisor64(GCD, (uint64_t)V);
5344
5345 // This transform can be done speculatively because it is so cheap - it results
5346 // in a single rotate operation being inserted. This can only happen if the
5347 // factor extracted is a power of 2.
5348 // FIXME: If the GCD is an odd number we can multiply by the multiplicative
5349 // inverse of GCD and then perform this transform.
5350 // FIXME: It's possible that optimizing a switch on powers of two might also
5351 // be beneficial - flag values are often powers of two and we could use a CLZ
5352 // as the key function.
5353 if (GCD <= 1 || !llvm::isPowerOf2_64(GCD))
5354 // No common divisor found or too expensive to compute key function.
5355 return false;
5356
5357 unsigned Shift = llvm::Log2_64(GCD);
5358 for (auto &V : Values)
5359 V = (int64_t)((uint64_t)V >> Shift);
5360
5361 if (!isSwitchDense(Values))
5362 // Transform didn't create a dense switch.
5363 return false;
5364
5365 // The obvious transform is to shift the switch condition right and emit a
5366 // check that the condition actually cleanly divided by GCD, i.e.
5367 // C & (1 << Shift - 1) == 0
5368 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
5369 //
5370 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
5371 // shift and puts the shifted-off bits in the uppermost bits. If any of these
5372 // are nonzero then the switch condition will be very large and will hit the
5373 // default case.
Junmo Parkdb8f6ee2016-08-02 04:38:27 +00005374
James Molloyb2e436d2016-08-01 07:45:11 +00005375 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
5376 Builder.SetInsertPoint(SI);
5377 auto *ShiftC = ConstantInt::get(Ty, Shift);
5378 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
Benjamin Krameraa160c22016-08-05 14:55:02 +00005379 auto *LShr = Builder.CreateLShr(Sub, ShiftC);
5380 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
5381 auto *Rot = Builder.CreateOr(LShr, Shl);
James Molloyb2e436d2016-08-01 07:45:11 +00005382 SI->replaceUsesOfWith(SI->getCondition(), Rot);
5383
James Molloybade86c2016-08-01 09:34:48 +00005384 for (SwitchInst::CaseIt C = SI->case_begin(), E = SI->case_end(); C != E;
5385 ++C) {
James Molloyb2e436d2016-08-01 07:45:11 +00005386 auto *Orig = C.getCaseValue();
5387 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
James Molloybade86c2016-08-01 09:34:48 +00005388 C.setValue(
5389 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
James Molloyb2e436d2016-08-01 07:45:11 +00005390 }
5391 return true;
5392}
5393
Devang Patela7ec47d2011-05-18 20:35:38 +00005394bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005395 BasicBlock *BB = SI->getParent();
5396
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005397 if (isValueEqualityComparison(SI)) {
5398 // If we only have one predecessor, and if it is a branch on this value,
5399 // see if that predecessor totally determines the outcome of this switch.
5400 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5401 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005402 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00005403
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005404 Value *Cond = SI->getCondition();
5405 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
5406 if (SimplifySwitchOnSelect(SI, Select))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005407 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00005408
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005409 // If the block only contains the switch, see if we can fold the block
5410 // away into any preds.
5411 BasicBlock::iterator BBI = BB->begin();
5412 // Ignore dbg intrinsics.
5413 while (isa<DbgInfoIntrinsic>(BBI))
5414 ++BBI;
5415 if (SI == &*BBI)
5416 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005417 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005418 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00005419
5420 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00005421 if (TurnSwitchRangeIntoICmp(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005422 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00005423
5424 // Remove unreachable cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005425 if (EliminateDeadSwitchCases(SI, AC, DL))
5426 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00005427
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005428 if (SwitchToSelect(SI, Builder, AC, DL))
5429 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00005430
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00005431 if (ForwardSwitchConditionToPHI(SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005432 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00005433
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005434 if (SwitchToLookupTable(SI, Builder, DL, TTI))
5435 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005436
James Molloyb2e436d2016-08-01 07:45:11 +00005437 if (ReduceSwitchRange(SI, Builder, DL, TTI))
5438 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5439
Chris Lattner25c3af32010-12-13 06:25:44 +00005440 return false;
5441}
5442
5443bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
5444 BasicBlock *BB = IBI->getParent();
5445 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005446
Chris Lattner25c3af32010-12-13 06:25:44 +00005447 // Eliminate redundant destinations.
5448 SmallPtrSet<Value *, 8> Succs;
5449 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
5450 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00005451 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005452 Dest->removePredecessor(BB);
5453 IBI->removeDestination(i);
Dehao Chenf6c00832016-05-18 19:44:21 +00005454 --i;
5455 --e;
Chris Lattner25c3af32010-12-13 06:25:44 +00005456 Changed = true;
5457 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005458 }
Chris Lattner25c3af32010-12-13 06:25:44 +00005459
5460 if (IBI->getNumDestinations() == 0) {
5461 // If the indirectbr has no successors, change it to unreachable.
5462 new UnreachableInst(IBI->getContext(), IBI);
5463 EraseTerminatorInstAndDCECond(IBI);
5464 return true;
5465 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005466
Chris Lattner25c3af32010-12-13 06:25:44 +00005467 if (IBI->getNumDestinations() == 1) {
5468 // If the indirectbr has one successor, change it to a direct branch.
5469 BranchInst::Create(IBI->getDestination(0), IBI);
5470 EraseTerminatorInstAndDCECond(IBI);
5471 return true;
5472 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005473
Chris Lattner25c3af32010-12-13 06:25:44 +00005474 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
5475 if (SimplifyIndirectBrOnSelect(IBI, SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005476 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005477 }
5478 return Changed;
5479}
5480
Philip Reames2b969d72015-03-24 22:28:45 +00005481/// Given an block with only a single landing pad and a unconditional branch
5482/// try to find another basic block which this one can be merged with. This
5483/// handles cases where we have multiple invokes with unique landing pads, but
5484/// a shared handler.
5485///
5486/// We specifically choose to not worry about merging non-empty blocks
5487/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
5488/// practice, the optimizer produces empty landing pad blocks quite frequently
5489/// when dealing with exception dense code. (see: instcombine, gvn, if-else
5490/// sinking in this file)
5491///
5492/// This is primarily a code size optimization. We need to avoid performing
5493/// any transform which might inhibit optimization (such as our ability to
5494/// specialize a particular handler via tail commoning). We do this by not
5495/// merging any blocks which require us to introduce a phi. Since the same
5496/// values are flowing through both blocks, we don't loose any ability to
5497/// specialize. If anything, we make such specialization more likely.
5498///
5499/// TODO - This transformation could remove entries from a phi in the target
5500/// block when the inputs in the phi are the same for the two blocks being
5501/// merged. In some cases, this could result in removal of the PHI entirely.
5502static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
5503 BasicBlock *BB) {
5504 auto Succ = BB->getUniqueSuccessor();
5505 assert(Succ);
5506 // If there's a phi in the successor block, we'd likely have to introduce
5507 // a phi into the merged landing pad block.
5508 if (isa<PHINode>(*Succ->begin()))
5509 return false;
5510
5511 for (BasicBlock *OtherPred : predecessors(Succ)) {
5512 if (BB == OtherPred)
5513 continue;
5514 BasicBlock::iterator I = OtherPred->begin();
5515 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
5516 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
5517 continue;
Dehao Chenf6c00832016-05-18 19:44:21 +00005518 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {
5519 }
Philip Reames2b969d72015-03-24 22:28:45 +00005520 BranchInst *BI2 = dyn_cast<BranchInst>(I);
5521 if (!BI2 || !BI2->isIdenticalTo(BI))
5522 continue;
5523
David Majnemer1efa23d2016-02-20 01:07:45 +00005524 // We've found an identical block. Update our predecessors to take that
Philip Reames2b969d72015-03-24 22:28:45 +00005525 // path instead and make ourselves dead.
5526 SmallSet<BasicBlock *, 16> Preds;
5527 Preds.insert(pred_begin(BB), pred_end(BB));
5528 for (BasicBlock *Pred : Preds) {
5529 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
Dehao Chenf6c00832016-05-18 19:44:21 +00005530 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
5531 "unexpected successor");
Philip Reames2b969d72015-03-24 22:28:45 +00005532 II->setUnwindDest(OtherPred);
5533 }
5534
5535 // The debug info in OtherPred doesn't cover the merged control flow that
5536 // used to go through BB. We need to delete it or update it.
Dehao Chenf6c00832016-05-18 19:44:21 +00005537 for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
5538 Instruction &Inst = *I;
5539 I++;
Philip Reames2b969d72015-03-24 22:28:45 +00005540 if (isa<DbgInfoIntrinsic>(Inst))
5541 Inst.eraseFromParent();
5542 }
5543
5544 SmallSet<BasicBlock *, 16> Succs;
5545 Succs.insert(succ_begin(BB), succ_end(BB));
5546 for (BasicBlock *Succ : Succs) {
5547 Succ->removePredecessor(BB);
5548 }
5549
5550 IRBuilder<> Builder(BI);
5551 Builder.CreateUnreachable();
5552 BI->eraseFromParent();
5553 return true;
5554 }
5555 return false;
5556}
5557
Dehao Chenf6c00832016-05-18 19:44:21 +00005558bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI,
5559 IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005560 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005561
Manman Ren93ab6492012-09-20 22:37:36 +00005562 if (SinkCommon && SinkThenElseCodeToEnd(BI))
5563 return true;
Reid Klecknerbca59d22016-05-02 19:43:22 +00005564
5565 // If the Terminator is the only non-phi instruction, simplify the block.
5566 // if LoopHeader is provided, check if the block is a loop header
Hyojin Sung4673f102016-03-29 04:08:57 +00005567 // (This is for early invocations before loop simplify and vectorization
5568 // to keep canonical loop forms for nested loops.
5569 // These blocks can be eliminated when the pass is invoked later
5570 // in the back-end.)
Reid Klecknerbca59d22016-05-02 19:43:22 +00005571 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00005572 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
Hans Wennborge9134892016-04-11 20:35:01 +00005573 (!LoopHeaders || !LoopHeaders->count(BB)) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00005574 TryToSimplifyUncondBranchFromEmptyBlock(BB))
5575 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005576
Chris Lattner25c3af32010-12-13 06:25:44 +00005577 // If the only instruction in the block is a seteq/setne comparison
5578 // against a constant, try to simplify the block.
5579 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5580 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5581 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5582 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005583 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005584 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
5585 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00005586 return true;
5587 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005588
Philip Reames2b969d72015-03-24 22:28:45 +00005589 // See if we can merge an empty landing pad block with another which is
5590 // equivalent.
5591 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005592 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {
5593 }
5594 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
Philip Reames2b969d72015-03-24 22:28:45 +00005595 return true;
5596 }
5597
Manman Rend33f4ef2012-06-13 05:43:29 +00005598 // If this basic block is ONLY a compare and a branch, and if a predecessor
5599 // branches to us and our successor, fold the comparison into the
5600 // predecessor and use logical operations to update the incoming value
5601 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005602 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5603 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005604 return false;
5605}
5606
James Molloy4de84dd2015-11-04 15:28:04 +00005607static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5608 BasicBlock *PredPred = nullptr;
5609 for (auto *P : predecessors(BB)) {
5610 BasicBlock *PPred = P->getSinglePredecessor();
5611 if (!PPred || (PredPred && PredPred != PPred))
5612 return nullptr;
5613 PredPred = PPred;
5614 }
5615 return PredPred;
5616}
Chris Lattner25c3af32010-12-13 06:25:44 +00005617
Devang Patela7ec47d2011-05-18 20:35:38 +00005618bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005619 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005620
Chris Lattner25c3af32010-12-13 06:25:44 +00005621 // Conditional branch
5622 if (isValueEqualityComparison(BI)) {
5623 // If we only have one predecessor, and if it is a branch on this value,
5624 // see if that predecessor totally determines the outcome of this
5625 // switch.
5626 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00005627 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005628 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005629
Chris Lattner25c3af32010-12-13 06:25:44 +00005630 // This block must be empty, except for the setcond inst, if it exists.
5631 // Ignore dbg intrinsics.
5632 BasicBlock::iterator I = BB->begin();
5633 // Ignore dbg intrinsics.
5634 while (isa<DbgInfoIntrinsic>(I))
5635 ++I;
5636 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00005637 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005638 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Dehao Chenf6c00832016-05-18 19:44:21 +00005639 } else if (&*I == cast<Instruction>(BI->getCondition())) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005640 ++I;
5641 // Ignore dbg intrinsics.
5642 while (isa<DbgInfoIntrinsic>(I))
5643 ++I;
Devang Patel58380552011-05-18 20:53:17 +00005644 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005645 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005646 }
5647 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005648
Chris Lattner25c3af32010-12-13 06:25:44 +00005649 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005650 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00005651 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005652
Chad Rosier4ab37c02016-05-06 14:25:14 +00005653 // If this basic block has a single dominating predecessor block and the
5654 // dominating block's condition implies BI's condition, we know the direction
5655 // of the BI branch.
5656 if (BasicBlock *Dom = BB->getSinglePredecessor()) {
5657 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
5658 if (PBI && PBI->isConditional() &&
5659 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
5660 (PBI->getSuccessor(0) == BB || PBI->getSuccessor(1) == BB)) {
5661 bool CondIsFalse = PBI->getSuccessor(1) == BB;
5662 Optional<bool> Implication = isImpliedCondition(
5663 PBI->getCondition(), BI->getCondition(), DL, CondIsFalse);
5664 if (Implication) {
5665 // Turn this into a branch on constant.
5666 auto *OldCond = BI->getCondition();
5667 ConstantInt *CI = *Implication
5668 ? ConstantInt::getTrue(BB->getContext())
5669 : ConstantInt::getFalse(BB->getContext());
5670 BI->setCondition(CI);
5671 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
5672 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
5673 }
5674 }
5675 }
5676
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00005677 // If this basic block is ONLY a compare and a branch, and if a predecessor
5678 // branches to us and one of our successors, fold the comparison into the
5679 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005680 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
5681 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005682
Chris Lattner25c3af32010-12-13 06:25:44 +00005683 // We have a conditional branch to two blocks that are only reachable
5684 // from BI. We know that the condbr dominates the two blocks, so see if
5685 // there is any identical code in the "then" and "else" blocks. If so, we
5686 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00005687 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5688 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005689 if (HoistThenElseCodeToIf(BI, TTI))
5690 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005691 } else {
5692 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005693 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00005694 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5695 if (Succ0TI->getNumSuccessors() == 1 &&
5696 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005697 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
5698 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005699 }
Craig Topperf40110f2014-04-25 05:29:35 +00005700 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005701 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005702 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00005703 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5704 if (Succ1TI->getNumSuccessors() == 1 &&
5705 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005706 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
5707 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005708 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005709
Chris Lattner25c3af32010-12-13 06:25:44 +00005710 // If this is a branch on a phi node in the current block, thread control
5711 // through this block if any PHI node entries are constants.
5712 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5713 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005714 if (FoldCondBranchOnPHI(BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005715 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005716
Chris Lattner25c3af32010-12-13 06:25:44 +00005717 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00005718 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5719 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00005720 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00005721 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005722 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005723
James Molloy4de84dd2015-11-04 15:28:04 +00005724 // Look for diamond patterns.
5725 if (MergeCondStores)
5726 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5727 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5728 if (PBI != BI && PBI->isConditional())
5729 if (mergeConditionalStores(PBI, BI))
5730 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Dehao Chenf6c00832016-05-18 19:44:21 +00005731
Chris Lattner25c3af32010-12-13 06:25:44 +00005732 return false;
5733}
5734
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005735/// Check if passing a value to an instruction will cause undefined behavior.
5736static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5737 Constant *C = dyn_cast<Constant>(V);
5738 if (!C)
5739 return false;
5740
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005741 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005742 return false;
5743
David Majnemer1fea77c2016-06-25 07:37:27 +00005744 if (C->isNullValue() || isa<UndefValue>(C)) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005745 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00005746 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005747
5748 // Now make sure that there are no instructions in between that can alter
5749 // control flow (eg. calls)
Duncan P. N. Exon Smith0a12729f2016-08-16 23:57:56 +00005750 for (BasicBlock::iterator
5751 i = ++BasicBlock::iterator(I),
5752 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
5753 i != UI; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00005754 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005755 return false;
5756
5757 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5758 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5759 if (GEP->getPointerOperand() == I)
5760 return passingValueIsAlwaysUndefined(V, GEP);
5761
5762 // Look through bitcasts.
5763 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5764 return passingValueIsAlwaysUndefined(V, BC);
5765
Benjamin Kramer0655b782011-08-26 02:25:55 +00005766 // Load from null is undefined.
5767 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005768 if (!LI->isVolatile())
5769 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005770
Benjamin Kramer0655b782011-08-26 02:25:55 +00005771 // Store to null is undefined.
5772 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005773 if (!SI->isVolatile())
Dehao Chenf6c00832016-05-18 19:44:21 +00005774 return SI->getPointerAddressSpace() == 0 &&
5775 SI->getPointerOperand() == I;
David Majnemer1fea77c2016-06-25 07:37:27 +00005776
5777 // A call to null is undefined.
5778 if (auto CS = CallSite(Use))
5779 return CS.getCalledValue() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005780 }
5781 return false;
5782}
5783
5784/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005785/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005786static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5787 for (BasicBlock::iterator i = BB->begin();
5788 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5789 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5790 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5791 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5792 IRBuilder<> Builder(T);
5793 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5794 BB->removePredecessor(PHI->getIncomingBlock(i));
5795 // Turn uncoditional branches into unreachables and remove the dead
5796 // destination from conditional branches.
5797 if (BI->isUnconditional())
5798 Builder.CreateUnreachable();
5799 else
Dehao Chenf6c00832016-05-18 19:44:21 +00005800 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
5801 : BI->getSuccessor(0));
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005802 BI->eraseFromParent();
5803 return true;
5804 }
5805 // TODO: SwitchInst.
5806 }
5807
5808 return false;
5809}
5810
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005811bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00005812 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00005813
Chris Lattnerd7beca32010-12-14 06:17:25 +00005814 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00005815 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00005816
Dan Gohman4a63fad2010-08-14 00:29:42 +00005817 // Remove basic blocks that have no predecessors (except the entry block)...
5818 // or that just have themself as a predecessor. These are unreachable.
Dehao Chenf6c00832016-05-18 19:44:21 +00005819 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00005820 BB->getSinglePredecessor() == BB) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00005821 DEBUG(dbgs() << "Removing BB: \n" << *BB);
5822 DeleteDeadBlock(BB);
5823 return true;
Chris Lattner466a0492002-05-21 20:50:24 +00005824 }
5825
Chris Lattner031340a2003-08-17 19:41:53 +00005826 // Check to see if we can constant propagate this terminator instruction
5827 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00005828 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00005829
Dan Gohman1a951062009-10-30 22:39:04 +00005830 // Check for and eliminate duplicate PHI nodes in this block.
5831 Changed |= EliminateDuplicatePHINodes(BB);
5832
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005833 // Check for and remove branches that will always cause undefined behavior.
5834 Changed |= removeUndefIntroducingPredecessor(BB);
5835
Chris Lattner2e3832d2010-12-13 05:10:48 +00005836 // Merge basic blocks into their predecessor if there is only one distinct
5837 // pred, and if there is only one distinct successor of the predecessor, and
5838 // if there are no PHI nodes.
5839 //
5840 if (MergeBlockIntoPredecessor(BB))
5841 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005842
Devang Patel15ad6762011-05-18 18:01:27 +00005843 IRBuilder<> Builder(BB);
5844
Dan Gohman20af5a02008-03-11 21:53:06 +00005845 // If there is a trivial two-entry PHI node in this basic block, and we can
5846 // eliminate it, do so now.
5847 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5848 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005849 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00005850
Devang Patela7ec47d2011-05-18 20:35:38 +00005851 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00005852 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00005853 if (BI->isUnconditional()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005854 if (SimplifyUncondBranch(BI, Builder))
5855 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005856 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00005857 if (SimplifyCondBranch(BI, Builder))
5858 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005859 }
5860 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005861 if (SimplifyReturn(RI, Builder))
5862 return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00005863 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005864 if (SimplifyResume(RI, Builder))
5865 return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00005866 } else if (CleanupReturnInst *RI =
Dehao Chenf6c00832016-05-18 19:44:21 +00005867 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5868 if (SimplifyCleanupReturn(RI))
5869 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005870 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005871 if (SimplifySwitch(SI, Builder))
5872 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005873 } else if (UnreachableInst *UI =
Dehao Chenf6c00832016-05-18 19:44:21 +00005874 dyn_cast<UnreachableInst>(BB->getTerminator())) {
5875 if (SimplifyUnreachable(UI))
5876 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005877 } else if (IndirectBrInst *IBI =
Dehao Chenf6c00832016-05-18 19:44:21 +00005878 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
5879 if (SimplifyIndirectBr(IBI))
5880 return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00005881 }
5882
Chris Lattner031340a2003-08-17 19:41:53 +00005883 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00005884}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005885
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005886/// This function is used to do simplification of a CFG.
5887/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005888/// eliminates unreachable basic blocks, and does other "peephole" optimization
5889/// of the CFG. It returns true if a modification was made.
5890///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005891bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Hyojin Sung4673f102016-03-29 04:08:57 +00005892 unsigned BonusInstThreshold, AssumptionCache *AC,
5893 SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005894 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
Dehao Chenf6c00832016-05-18 19:44:21 +00005895 BonusInstThreshold, AC, LoopHeaders)
5896 .run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005897}