blob: ce550dc7fd1585071e4962a900bd154c9ea90dcc [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000021#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000025#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000026#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/MDBuilder.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000038#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Type.h"
Evan Chengd983eba2011-01-29 04:46:23 +000042#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Rafael Espindolaea46c322014-08-15 15:46:38 +000046#include "llvm/Transforms/Utils/Local.h"
Jingyue Wufc029672014-09-30 22:23:38 +000047#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000048#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000049#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000051using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000052using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000053
Chandler Carruth964daaa2014-04-22 02:55:47 +000054#define DEBUG_TYPE "simplifycfg"
55
James Molloy1b6207e2015-02-13 10:48:30 +000056// Chosen as 2 so as to be cheap, but still to have enough power to fold
57// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
58// To catch this, we need to fold a compare and a select, hence '2' being the
59// minimum reasonable default.
Peter Collingbourne616044a2011-04-29 18:47:38 +000060static cl::opt<unsigned>
James Molloy1b6207e2015-02-13 10:48:30 +000061PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
62 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
Peter Collingbourne616044a2011-04-29 18:47:38 +000063
Evan Chengd983eba2011-01-29 04:46:23 +000064static cl::opt<bool>
65DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
66 cl::desc("Duplicate return instructions into unconditional branches"));
67
Manman Ren93ab6492012-09-20 22:37:36 +000068static cl::opt<bool>
69SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
70 cl::desc("Sink common instructions down to the end block"));
71
Alp Tokercb402912014-01-24 17:20:08 +000072static cl::opt<bool> HoistCondStores(
73 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
74 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000075
Hans Wennborg39583b82012-09-26 09:44:49 +000076STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000077STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000078STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +000079STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +000080STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Manman Ren93ab6492012-09-20 22:37:36 +000081STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000082STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +000083
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000084namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +000085 // The first field contains the value that the switch produces when a certain
Sanjay Patel9361d352015-09-10 16:31:19 +000086 // case group is selected, and the second field is a vector containing the
87 // cases composing the case group.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +000088 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
89 SwitchCaseResultVectorTy;
90 // The first field contains the phi node that generates a result of the switch
Sanjay Patel9361d352015-09-10 16:31:19 +000091 // and the second field contains the value generated for a certain case in the
92 // switch for that PHI.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +000093 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
94
Eric Christopherb65acc62012-07-02 23:22:21 +000095 /// ValueEqualityComparisonCase - Represents a case of a switch.
96 struct ValueEqualityComparisonCase {
97 ConstantInt *Value;
98 BasicBlock *Dest;
99
100 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
101 : Value(Value), Dest(Dest) {}
102
103 bool operator<(ValueEqualityComparisonCase RHS) const {
104 // Comparing pointers is ok as we only rely on the order for uniquing.
105 return Value < RHS.Value;
106 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000107
108 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000109 };
110
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000111class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000112 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000113 const DataLayout &DL;
Jingyue Wufc029672014-09-30 22:23:38 +0000114 unsigned BonusInstThreshold;
Chandler Carruth66b31302015-01-04 12:03:27 +0000115 AssumptionCache *AC;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000116 Value *isValueEqualityComparison(TerminatorInst *TI);
117 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000118 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000119 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000120 BasicBlock *Pred,
121 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000122 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
123 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000124
Devang Pateldd14e0f2011-05-18 21:33:11 +0000125 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000126 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000127 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000128 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000129 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000130 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000131 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000132 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000133
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000134public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000135 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
136 unsigned BonusInstThreshold, AssumptionCache *AC)
137 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000138 bool run(BasicBlock *BB);
139};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000140}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000141
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000142/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000143/// terminator instructions together.
Chris Lattner76dc2042005-08-03 00:19:45 +0000144static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
145 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000146
Chris Lattner76dc2042005-08-03 00:19:45 +0000147 // It is not safe to merge these two switch instructions if they have a common
148 // successor, and if that successor has a PHI node, and if *that* PHI node has
149 // conflicting incoming values from the two switch blocks.
150 BasicBlock *SI1BB = SI1->getParent();
151 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000152 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000153
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000154 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
155 if (SI1Succs.count(*I))
156 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000157 isa<PHINode>(BBI); ++BBI) {
158 PHINode *PN = cast<PHINode>(BBI);
159 if (PN->getIncomingValueForBlock(SI1BB) !=
160 PN->getIncomingValueForBlock(SI2BB))
161 return false;
162 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000163
Chris Lattner76dc2042005-08-03 00:19:45 +0000164 return true;
165}
166
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000167/// Return true if it is safe and profitable to merge these two terminator
168/// instructions together, where SI1 is an unconditional branch. PhiNodes will
169/// store all PHI nodes in common successors.
Manman Rend33f4ef2012-06-13 05:43:29 +0000170static bool isProfitableToFoldUnconditional(BranchInst *SI1,
171 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000172 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000173 SmallVectorImpl<PHINode*> &PhiNodes) {
174 if (SI1 == SI2) return false; // Can't merge with self!
175 assert(SI1->isUnconditional() && SI2->isConditional());
176
177 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000178 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000179 // 1> We have a constant incoming value for the conditional branch;
180 // 2> We have "Cond" as the incoming value for the unconditional branch;
181 // 3> SI2->getCondition() and Cond have same operands.
182 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
183 if (!Ci2) return false;
184 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
185 Cond->getOperand(1) == Ci2->getOperand(1)) &&
186 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
187 Cond->getOperand(1) == Ci2->getOperand(0)))
188 return false;
189
190 BasicBlock *SI1BB = SI1->getParent();
191 BasicBlock *SI2BB = SI2->getParent();
192 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000193 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
194 if (SI1Succs.count(*I))
195 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000196 isa<PHINode>(BBI); ++BBI) {
197 PHINode *PN = cast<PHINode>(BBI);
198 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000199 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000200 return false;
201 PhiNodes.push_back(PN);
202 }
203 return true;
204}
205
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000206/// Update PHI nodes in Succ to indicate that there will now be entries in it
207/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
208/// will be the same as those coming in from ExistPred, an existing predecessor
209/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000210static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
211 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000212 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000213
Chris Lattner80b03a12008-07-13 22:23:11 +0000214 PHINode *PN;
215 for (BasicBlock::iterator I = Succ->begin();
216 (PN = dyn_cast<PHINode>(I)); ++I)
217 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000218}
219
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000220/// Compute an abstract "cost" of speculating the given instruction,
221/// which is assumed to be safe to speculate. TCC_Free means cheap,
222/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000223/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000224static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000225 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000226 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000227 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000228 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000229}
Sanjay Patelf9b77632015-09-15 15:24:42 +0000230
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000231/// If we have a merge point of an "if condition" as accepted above,
232/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000233/// don't handle the true generality of domination here, just a special case
234/// which works well enough for us.
235///
236/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000237/// see if V (which must be an instruction) and its recursive operands
238/// that do not dominate BB have a combined cost lower than CostRemaining and
239/// are non-trapping. If both are true, the instruction is inserted into the
240/// set and true is returned.
241///
242/// The cost for most non-trapping instructions is defined as 1 except for
243/// Select whose cost is 2.
244///
245/// After this function returns, CostRemaining is decreased by the cost of
246/// V plus its non-dominating operands. If that cost is greater than
247/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000248static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000249 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000250 unsigned &CostRemaining,
James Molloy7c336572015-02-11 12:15:41 +0000251 const TargetTransformInfo &TTI) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000252 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000253 if (!I) {
254 // Non-instructions all dominate instructions, but not all constantexprs
255 // can be executed unconditionally.
256 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
257 if (C->canTrap())
258 return false;
259 return true;
260 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000261 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000262
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000263 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000264 // the bottom of this block.
265 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000266
Chris Lattner0aa56562004-04-09 22:50:22 +0000267 // If this instruction is defined in a block that contains an unconditional
268 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000269 // statement". If not, it definitely dominates the region.
270 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000271 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000272 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000273
Chris Lattner9ac168d2010-12-14 07:41:39 +0000274 // If we aren't allowing aggressive promotion anymore, then don't consider
275 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000276 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000277
Peter Collingbournee3511e12011-04-29 18:47:31 +0000278 // If we have seen this instruction before, don't count it again.
279 if (AggressiveInsts->count(I)) return true;
280
Chris Lattner9ac168d2010-12-14 07:41:39 +0000281 // Okay, it looks like the instruction IS in the "condition". Check to
282 // see if it's a cheap instruction to unconditionally compute, and if it
283 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000284 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000285 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000286
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000287 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000288
Peter Collingbournee3511e12011-04-29 18:47:31 +0000289 if (Cost > CostRemaining)
290 return false;
291
292 CostRemaining -= Cost;
293
294 // Okay, we can only really hoist these out if their operands do
295 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000296 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000297 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000298 return false;
299 // Okay, it's safe to do this! Remember this instruction.
300 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000301 return true;
302}
Chris Lattner466a0492002-05-21 20:50:24 +0000303
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000304/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000305/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000306static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000307 // Normal constant int.
308 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000309 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000310 return CI;
311
312 // This is some kind of pointer constant. Turn it into a pointer-sized
313 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000314 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000315
316 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
317 if (isa<ConstantPointerNull>(V))
318 return ConstantInt::get(PtrTy, 0);
319
320 // IntToPtr const int.
321 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
322 if (CE->getOpcode() == Instruction::IntToPtr)
323 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
324 // The constant is very likely to have the right type already.
325 if (CI->getType() == PtrTy)
326 return CI;
327 else
328 return cast<ConstantInt>
329 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
330 }
Craig Topperf40110f2014-04-25 05:29:35 +0000331 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000332}
333
Mehdi Aminiffd01002014-11-20 22:40:25 +0000334namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000335
Mehdi Aminiffd01002014-11-20 22:40:25 +0000336/// Given a chain of or (||) or and (&&) comparison of a value against a
337/// constant, this will try to recover the information required for a switch
338/// structure.
339/// It will depth-first traverse the chain of comparison, seeking for patterns
340/// like %a == 12 or %a < 4 and combine them to produce a set of integer
341/// representing the different cases for the switch.
342/// Note that if the chain is composed of '||' it will build the set of elements
343/// that matches the comparisons (i.e. any of this value validate the chain)
344/// while for a chain of '&&' it will build the set elements that make the test
345/// fail.
346struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000347 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000348 Value *CompValue; /// Value found for the switch comparison
349 Value *Extra; /// Extra clause to be checked before the switch
350 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
351 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000352
Mehdi Aminiffd01002014-11-20 22:40:25 +0000353 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000354 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
355 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
356 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000357 }
358
Mehdi Aminiffd01002014-11-20 22:40:25 +0000359 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000360 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000361 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000362 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000363
Mehdi Aminiffd01002014-11-20 22:40:25 +0000364private:
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000365
Mehdi Aminiffd01002014-11-20 22:40:25 +0000366 /// Try to set the current value used for the comparison, it succeeds only if
367 /// it wasn't set before or if the new value is the same as the old one
368 bool setValueOnce(Value *NewVal) {
369 if(CompValue && CompValue != NewVal) return false;
370 CompValue = NewVal;
371 return (CompValue != nullptr);
372 }
373
374 /// Try to match Instruction "I" as a comparison against a constant and
375 /// populates the array Vals with the set of values that match (or do not
376 /// match depending on isEQ).
377 /// Return false on failure. On success, the Value the comparison matched
378 /// against is placed in CompValue.
379 /// If CompValue is already set, the function is expected to fail if a match
380 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000381 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000382 // If this is an icmp against a constant, handle this as one of the cases.
383 ICmpInst *ICI;
384 ConstantInt *C;
385 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
386 (C = GetConstantInt(I->getOperand(1), DL)))) {
387 return false;
388 }
389
390 Value *RHSVal;
391 ConstantInt *RHSC;
392
393 // Pattern match a special case
394 // (x & ~2^x) == y --> x == y || x == y|2^x
395 // This undoes a transformation done by instcombine to fuse 2 compares.
396 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
397 if (match(ICI->getOperand(0),
398 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
399 APInt Not = ~RHSC->getValue();
400 if (Not.isPowerOf2()) {
401 // If we already have a value for the switch, it has to match!
402 if(!setValueOnce(RHSVal))
403 return false;
404
405 Vals.push_back(C);
406 Vals.push_back(ConstantInt::get(C->getContext(),
407 C->getValue() | Not));
408 UsedICmps++;
409 return true;
410 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000411 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000412
413 // If we already have a value for the switch, it has to match!
414 if(!setValueOnce(ICI->getOperand(0)))
415 return false;
416
417 UsedICmps++;
418 Vals.push_back(C);
419 return ICI->getOperand(0);
420 }
421
422 // 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 +0000423 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
424 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000425
426 // Shift the range if the compare is fed by an add. This is the range
427 // compare idiom as emitted by instcombine.
428 Value *CandidateVal = I->getOperand(0);
429 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
430 Span = Span.subtract(RHSC->getValue());
431 CandidateVal = RHSVal;
432 }
433
434 // If this is an and/!= check, then we are looking to build the set of
435 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
436 // x != 0 && x != 1.
437 if (!isEQ)
438 Span = Span.inverse();
439
440 // If there are a ton of values, we don't want to make a ginormous switch.
441 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
442 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000443 }
444
445 // If we already have a value for the switch, it has to match!
Mehdi Aminiffd01002014-11-20 22:40:25 +0000446 if(!setValueOnce(CandidateVal))
447 return false;
448
449 // Add all values from the range to the set
450 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
451 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000452
453 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000454 return true;
455
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000456 }
457
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000458 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000459 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
460 /// the value being compared, and stick the list constants into the Vals
461 /// vector.
462 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000463 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000464 Instruction *I = dyn_cast<Instruction>(V);
465 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000466
Mehdi Aminiffd01002014-11-20 22:40:25 +0000467 // Keep a stack (SmallVector for efficiency) for depth-first traversal
468 SmallVector<Value *, 8> DFT;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000469
Mehdi Aminiffd01002014-11-20 22:40:25 +0000470 // Initialize
471 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000472
Mehdi Aminiffd01002014-11-20 22:40:25 +0000473 while(!DFT.empty()) {
474 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000475
Mehdi Aminiffd01002014-11-20 22:40:25 +0000476 if (Instruction *I = dyn_cast<Instruction>(V)) {
477 // If it is a || (or && depending on isEQ), process the operands.
478 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
479 DFT.push_back(I->getOperand(1));
480 DFT.push_back(I->getOperand(0));
481 continue;
482 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000483
Mehdi Aminiffd01002014-11-20 22:40:25 +0000484 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000485 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000486 // Match succeed, continue the loop
487 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000488 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000489
Mehdi Aminiffd01002014-11-20 22:40:25 +0000490 // One element of the sequence of || (or &&) could not be match as a
491 // comparison against the same value as the others.
492 // We allow only one "Extra" case to be checked before the switch
493 if (!Extra) {
494 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000495 continue;
496 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000497 // Failed to parse a proper sequence, abort now
498 CompValue = nullptr;
499 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000500 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000501 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000502};
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000503
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000504}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000505
Eli Friedmancb61afb2008-12-16 20:54:32 +0000506static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000507 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000508 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
509 Cond = dyn_cast<Instruction>(SI->getCondition());
510 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
511 if (BI->isConditional())
512 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000513 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
514 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000515 }
516
517 TI->eraseFromParent();
518 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
519}
520
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000521/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000522/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000523Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000524 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000525 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
526 // Do not permit merging of large switch instructions into their
527 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000528 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
529 pred_end(SI->getParent())) <= 128)
530 CV = SI->getCondition();
531 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000532 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000533 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000534 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000535 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000536 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000537
538 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000539 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000540 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
541 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000542 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000543 CV = Ptr;
544 }
545 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000546 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000547}
548
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000549/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000550/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000551BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000552GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000553 std::vector<ValueEqualityComparisonCase>
554 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000555 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000556 Cases.reserve(SI->getNumCases());
557 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
558 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
559 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000560 return SI->getDefaultDest();
561 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000562
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000563 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000564 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000565 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
566 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000567 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000568 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000569 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000570}
571
Eric Christopherb65acc62012-07-02 23:22:21 +0000572
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000573/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000574/// in the list that match the specified block.
575static void EliminateBlockCases(BasicBlock *BB,
576 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000577 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000578}
579
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000580/// Return true if there are any keys in C1 that exist in C2 as well.
Eric Christopherb65acc62012-07-02 23:22:21 +0000581static bool
582ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
583 std::vector<ValueEqualityComparisonCase > &C2) {
584 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
585
586 // Make V1 be smaller than V2.
587 if (V1->size() > V2->size())
588 std::swap(V1, V2);
589
590 if (V1->size() == 0) return false;
591 if (V1->size() == 1) {
592 // Just scan V2.
593 ConstantInt *TheVal = (*V1)[0].Value;
594 for (unsigned i = 0, e = V2->size(); i != e; ++i)
595 if (TheVal == (*V2)[i].Value)
596 return true;
597 }
598
599 // Otherwise, just sort both lists and compare element by element.
600 array_pod_sort(V1->begin(), V1->end());
601 array_pod_sort(V2->begin(), V2->end());
602 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
603 while (i1 != e1 && i2 != e2) {
604 if ((*V1)[i1].Value == (*V2)[i2].Value)
605 return true;
606 if ((*V1)[i1].Value < (*V2)[i2].Value)
607 ++i1;
608 else
609 ++i2;
610 }
611 return false;
612}
613
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000614/// If TI is known to be a terminator instruction and its block is known to
615/// only have a single predecessor block, check to see if that predecessor is
616/// also a value comparison with the same value, and if that comparison
617/// determines the outcome of this comparison. If so, simplify TI. This does a
618/// very limited form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000619bool SimplifyCFGOpt::
620SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000621 BasicBlock *Pred,
622 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000623 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
624 if (!PredVal) return false; // Not a value comparison in predecessor.
625
626 Value *ThisVal = isValueEqualityComparison(TI);
627 assert(ThisVal && "This isn't a value comparison!!");
628 if (ThisVal != PredVal) return false; // Different predicates.
629
Andrew Trick3051aa12012-08-29 21:46:38 +0000630 // TODO: Preserve branch weight metadata, similarly to how
631 // FoldValueComparisonIntoPredecessors preserves it.
632
Chris Lattner1cca9592005-02-24 06:17:52 +0000633 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000634 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000635 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
636 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000637 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000638
Chris Lattner1cca9592005-02-24 06:17:52 +0000639 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000640 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000641 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000642 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000643
644 // If TI's block is the default block from Pred's comparison, potentially
645 // simplify TI based on this knowledge.
646 if (PredDef == TI->getParent()) {
647 // If we are here, we know that the value is none of those cases listed in
648 // PredCases. If there are any cases in ThisCases that are in PredCases, we
649 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000650 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000651 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000652
Chris Lattner4088e2b2010-12-13 01:47:07 +0000653 if (isa<BranchInst>(TI)) {
654 // Okay, one of the successors of this condbr is dead. Convert it to a
655 // uncond br.
656 assert(ThisCases.size() == 1 && "Branch can only have one case!");
657 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000658 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000659 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000660
Chris Lattner4088e2b2010-12-13 01:47:07 +0000661 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000662 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000663
Chris Lattner4088e2b2010-12-13 01:47:07 +0000664 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
665 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000666
Chris Lattner4088e2b2010-12-13 01:47:07 +0000667 EraseTerminatorInstAndDCECond(TI);
668 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000669 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000670
Chris Lattner4088e2b2010-12-13 01:47:07 +0000671 SwitchInst *SI = cast<SwitchInst>(TI);
672 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000673 SmallPtrSet<Constant*, 16> DeadCases;
674 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
675 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000676
David Greene725c7c32010-01-05 01:26:52 +0000677 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000678 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000679
Manman Ren8691e522012-09-14 21:53:06 +0000680 // Collect branch weights into a vector.
681 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000682 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000683 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
684 if (HasWeight)
685 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
686 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000687 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000688 Weights.push_back(CI->getValue().getZExtValue());
689 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000690 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
691 --i;
692 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000693 if (HasWeight) {
694 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
695 Weights.pop_back();
696 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000697 i.getCaseSuccessor()->removePredecessor(TI->getParent());
698 SI->removeCase(i);
699 }
700 }
Manman Ren97c18762012-10-11 22:28:34 +0000701 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000702 SI->setMetadata(LLVMContext::MD_prof,
703 MDBuilder(SI->getParent()->getContext()).
704 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000705
706 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000707 return true;
708 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000709
Chris Lattner4088e2b2010-12-13 01:47:07 +0000710 // Otherwise, TI's block must correspond to some matched value. Find out
711 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000712 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000713 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000714 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
715 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000716 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000717 return false; // Cannot handle multiple values coming to this block.
718 TIV = PredCases[i].Value;
719 }
720 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000721
722 // Okay, we found the one constant that our value can be if we get into TI's
723 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000724 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000725 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
726 if (ThisCases[i].Value == TIV) {
727 TheRealDest = ThisCases[i].Dest;
728 break;
729 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000730
731 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000732 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000733
734 // Remove PHI node entries for dead edges.
735 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000736 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
737 if (*SI != CheckEdge)
738 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000739 else
Craig Topperf40110f2014-04-25 05:29:35 +0000740 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000741
742 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000743 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000744 (void) NI;
745
746 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
747 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
748
749 EraseTerminatorInstAndDCECond(TI);
750 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000751}
752
Dale Johannesen7f99d222009-03-12 21:01:11 +0000753namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000754 /// This class implements a stable ordering of constant
Dale Johannesen7f99d222009-03-12 21:01:11 +0000755 /// integers that does not depend on their address. This is important for
756 /// applications that sort ConstantInt's to ensure uniqueness.
757 struct ConstantIntOrdering {
758 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
759 return LHS->getValue().ult(RHS->getValue());
760 }
761 };
762}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000763
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000764static int ConstantIntSortPredicate(ConstantInt *const *P1,
765 ConstantInt *const *P2) {
766 const ConstantInt *LHS = *P1;
767 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000768 if (LHS->getValue().ult(RHS->getValue()))
769 return 1;
770 if (LHS->getValue() == RHS->getValue())
771 return 0;
772 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000773}
774
Andrew Trick3051aa12012-08-29 21:46:38 +0000775static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000776 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000777 if (ProfMD && ProfMD->getOperand(0))
778 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
779 return MDS->getString().equals("branch_weights");
780
781 return false;
782}
783
Manman Ren571d9e42012-09-11 17:43:35 +0000784/// Get Weights of a given TerminatorInst, the default weight is at the front
785/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
786/// metadata.
787static void GetBranchWeights(TerminatorInst *TI,
788 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000789 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000790 assert(MD);
791 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000792 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000793 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000794 }
795
Manman Ren571d9e42012-09-11 17:43:35 +0000796 // If TI is a conditional eq, the default case is the false case,
797 // and the corresponding branch-weight data is at index 2. We swap the
798 // default weight to be the first entry.
799 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
800 assert(Weights.size() == 2);
801 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
802 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
803 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000804 }
805}
806
Manman Renf1cb16e2014-01-27 23:39:03 +0000807/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000808static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000809 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
810 if (Max > UINT_MAX) {
811 unsigned Offset = 32 - countLeadingZeros(Max);
812 for (uint64_t &I : Weights)
813 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000814 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000815}
816
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000817/// The specified terminator is a value equality comparison instruction
818/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000819/// See if any of the predecessors of the terminator block are value comparisons
820/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000821bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
822 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000823 BasicBlock *BB = TI->getParent();
824 Value *CV = isValueEqualityComparison(TI); // CondVal
825 assert(CV && "Not a comparison?");
826 bool Changed = false;
827
Chris Lattner6b39cb92008-02-18 07:42:56 +0000828 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000829 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000830 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000831
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000832 // See if the predecessor is a comparison with the same value.
833 TerminatorInst *PTI = Pred->getTerminator();
834 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
835
836 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
837 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000838 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000839 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
840
Eric Christopherb65acc62012-07-02 23:22:21 +0000841 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000842 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
843
844 // Based on whether the default edge from PTI goes to BB or not, fill in
845 // PredCases and PredDefault with the new switch cases we would like to
846 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000847 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000848
Andrew Trick3051aa12012-08-29 21:46:38 +0000849 // Update the branch weight metadata along the way
850 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000851 bool PredHasWeights = HasBranchWeights(PTI);
852 bool SuccHasWeights = HasBranchWeights(TI);
853
Manman Ren5e5049d2012-09-14 19:05:19 +0000854 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000855 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000856 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000857 if (Weights.size() != 1 + PredCases.size())
858 PredHasWeights = SuccHasWeights = false;
859 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000860 // If there are no predecessor weights but there are successor weights,
861 // populate Weights with 1, which will later be scaled to the sum of
862 // successor's weights
863 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000864
Manman Ren571d9e42012-09-11 17:43:35 +0000865 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000866 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000867 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000868 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000869 if (SuccWeights.size() != 1 + BBCases.size())
870 PredHasWeights = SuccHasWeights = false;
871 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000872 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000873
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000874 if (PredDefault == BB) {
875 // If this is the default destination from PTI, only the edges in TI
876 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000877 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
878 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
879 if (PredCases[i].Dest != BB)
880 PTIHandled.insert(PredCases[i].Value);
881 else {
882 // The default destination is BB, we don't need explicit targets.
883 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000884
Manman Ren571d9e42012-09-11 17:43:35 +0000885 if (PredHasWeights || SuccHasWeights) {
886 // Increase weight for the default case.
887 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000888 std::swap(Weights[i+1], Weights.back());
889 Weights.pop_back();
890 }
891
Eric Christopherb65acc62012-07-02 23:22:21 +0000892 PredCases.pop_back();
893 --i; --e;
894 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000895
Eric Christopherb65acc62012-07-02 23:22:21 +0000896 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000897 if (PredDefault != BBDefault) {
898 PredDefault->removePredecessor(Pred);
899 PredDefault = BBDefault;
900 NewSuccessors.push_back(BBDefault);
901 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000902
Manman Ren571d9e42012-09-11 17:43:35 +0000903 unsigned CasesFromPred = Weights.size();
904 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000905 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
906 if (!PTIHandled.count(BBCases[i].Value) &&
907 BBCases[i].Dest != BBDefault) {
908 PredCases.push_back(BBCases[i]);
909 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000910 if (SuccHasWeights || PredHasWeights) {
911 // The default weight is at index 0, so weight for the ith case
912 // should be at index i+1. Scale the cases from successor by
913 // PredDefaultWeight (Weights[0]).
914 Weights.push_back(Weights[0] * SuccWeights[i+1]);
915 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000916 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000917 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000918
Manman Ren571d9e42012-09-11 17:43:35 +0000919 if (SuccHasWeights || PredHasWeights) {
920 ValidTotalSuccWeight += SuccWeights[0];
921 // Scale the cases from predecessor by ValidTotalSuccWeight.
922 for (unsigned i = 1; i < CasesFromPred; ++i)
923 Weights[i] *= ValidTotalSuccWeight;
924 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
925 Weights[0] *= SuccWeights[0];
926 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000927 } else {
928 // If this is not the default destination from PSI, only the edges
929 // in SI that occur in PSI with a destination of BB will be
930 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000931 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000932 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000933 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
934 if (PredCases[i].Dest == BB) {
935 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000936
937 if (PredHasWeights || SuccHasWeights) {
938 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
939 std::swap(Weights[i+1], Weights.back());
940 Weights.pop_back();
941 }
942
Eric Christopherb65acc62012-07-02 23:22:21 +0000943 std::swap(PredCases[i], PredCases.back());
944 PredCases.pop_back();
945 --i; --e;
946 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000947
948 // Okay, now we know which constants were sent to BB from the
949 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000950 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
951 if (PTIHandled.count(BBCases[i].Value)) {
952 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000953 if (PredHasWeights || SuccHasWeights)
954 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000955 PredCases.push_back(BBCases[i]);
956 NewSuccessors.push_back(BBCases[i].Dest);
957 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
958 }
959
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000960 // If there are any constants vectored to BB that TI doesn't handle,
961 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000962 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000963 PTIHandled.begin(),
964 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000965 if (PredHasWeights || SuccHasWeights)
966 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000967 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000968 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000969 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000970 }
971
972 // Okay, at this point, we know which new successor Pred will get. Make
973 // sure we update the number of entries in the PHI nodes for these
974 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +0000975 for (BasicBlock *NewSuccessor : NewSuccessors)
976 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000977
Devang Patel58380552011-05-18 20:53:17 +0000978 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000979 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +0000980 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000981 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +0000982 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000983 }
984
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000985 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +0000986 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
987 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +0000988 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +0000989 for (ValueEqualityComparisonCase &V : PredCases)
990 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +0000991
Andrew Trick3051aa12012-08-29 21:46:38 +0000992 if (PredHasWeights || SuccHasWeights) {
993 // Halve the weights if any of them cannot fit in an uint32_t
994 FitWeights(Weights);
995
996 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
997
998 NewSI->setMetadata(LLVMContext::MD_prof,
999 MDBuilder(BB->getContext()).
1000 createBranchWeights(MDWeights));
1001 }
1002
Eli Friedmancb61afb2008-12-16 20:54:32 +00001003 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001004
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001005 // Okay, last check. If BB is still a successor of PSI, then we must
1006 // have an infinite loop case. If so, add an infinitely looping block
1007 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001008 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001009 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1010 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001011 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001012 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001013 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001014 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1015 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001016 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001017 }
1018 NewSI->setSuccessor(i, InfLoopBlock);
1019 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001020
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001021 Changed = true;
1022 }
1023 }
1024 return Changed;
1025}
1026
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001027// If we would need to insert a select that uses the value of this invoke
1028// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1029// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001030static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1031 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001032 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001033 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001034 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001035 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1036 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1037 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1038 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1039 return false;
1040 }
1041 }
1042 }
1043 return true;
1044}
1045
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001046static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1047
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001048/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1049/// in the two blocks up into the branch block. The caller of this function
1050/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001051static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001052 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001053 // This does very trivial matching, with limited scanning, to find identical
1054 // instructions in the two blocks. In particular, we don't want to get into
1055 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1056 // such, we currently just scan for obviously identical instructions in an
1057 // identical order.
1058 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1059 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1060
Devang Patelf10e2872009-02-04 00:03:08 +00001061 BasicBlock::iterator BB1_Itr = BB1->begin();
1062 BasicBlock::iterator BB2_Itr = BB2->begin();
1063
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001064 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001065 // Skip debug info if it is not identical.
1066 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1067 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1068 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1069 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001070 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001071 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001072 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001073 }
Devang Patele48ddf82011-04-07 00:30:15 +00001074 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001075 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001076 return false;
1077
Chris Lattner389cfac2004-11-30 00:29:14 +00001078 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001079
David Majnemerc82f27a2013-06-03 20:43:12 +00001080 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001081 do {
1082 // If we are hoisting the terminator instruction, don't move one (making a
1083 // broken BB), instead clone it, and remove BI.
1084 if (isa<TerminatorInst>(I1))
1085 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001086
Chad Rosier54390052015-02-23 19:15:16 +00001087 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1088 return Changed;
1089
Chris Lattner389cfac2004-11-30 00:29:14 +00001090 // For a normal instruction, we just move one to right before the branch,
1091 // then replace all uses of the other with the first. Finally, we remove
1092 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001093 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001094 if (!I2->use_empty())
1095 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001096 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001097 unsigned KnownIDs[] = {
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001098 LLVMContext::MD_tbaa, LLVMContext::MD_range,
1099 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1100 LLVMContext::MD_nonnull, LLVMContext::MD_invariant_group};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001101 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001102 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001103 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001104
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001105 I1 = &*BB1_Itr++;
1106 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001107 // Skip debug info if it is not identical.
1108 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1109 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1110 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1111 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001112 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001113 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001114 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001115 }
Devang Patele48ddf82011-04-07 00:30:15 +00001116 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001117
1118 return true;
1119
1120HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001121 // It may not be possible to hoist an invoke.
1122 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001123 return Changed;
1124
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001125 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001126 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001127 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001128 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1129 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1130 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1131 if (BB1V == BB2V)
1132 continue;
1133
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001134 // Check for passingValueIsAlwaysUndefined here because we would rather
1135 // eliminate undefined control flow then converting it to a select.
1136 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1137 passingValueIsAlwaysUndefined(BB2V, PN))
1138 return Changed;
1139
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001140 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001141 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001142 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001143 return Changed;
1144 }
1145 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001146
Chris Lattner389cfac2004-11-30 00:29:14 +00001147 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001148 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001149 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001150 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001151 I1->replaceAllUsesWith(NT);
1152 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001153 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001154 }
1155
Devang Patel1407fb42011-05-19 20:52:46 +00001156 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001157 // Hoisting one of the terminators from our successor is a great thing.
1158 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1159 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1160 // nodes, so we insert select instruction to compute the final result.
1161 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001162 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001163 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001164 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001165 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001166 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1167 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001168 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001169
Chris Lattner4088e2b2010-12-13 01:47:07 +00001170 // These values do not agree. Insert a select instruction before NT
1171 // that determines the right value.
1172 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001173 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001174 SI = cast<SelectInst>
1175 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1176 BB1V->getName()+"."+BB2V->getName()));
1177
Chris Lattner4088e2b2010-12-13 01:47:07 +00001178 // Make the PHI node use the select for all incoming values for BB1/BB2
1179 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1180 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1181 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001182 }
1183 }
1184
1185 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001186 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1187 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001188
Eli Friedmancb61afb2008-12-16 20:54:32 +00001189 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001190 return true;
1191}
1192
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001193/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001194/// check whether BBEnd has only two predecessors and the other predecessor
1195/// ends with an unconditional branch. If it is true, sink any common code
1196/// in the two predecessors to BBEnd.
1197static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1198 assert(BI1->isUnconditional());
1199 BasicBlock *BB1 = BI1->getParent();
1200 BasicBlock *BBEnd = BI1->getSuccessor(0);
1201
1202 // Check that BBEnd has two predecessors and the other predecessor ends with
1203 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001204 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1205 BasicBlock *Pred0 = *PI++;
1206 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001207 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001208 BasicBlock *Pred1 = *PI++;
1209 if (PI != PE) // More than two predecessors.
1210 return false;
1211 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001212 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1213 if (!BI2 || !BI2->isUnconditional())
1214 return false;
1215
1216 // Gather the PHI nodes in BBEnd.
Michael Liao5313da32014-12-23 08:26:55 +00001217 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
Craig Topperf40110f2014-04-25 05:29:35 +00001218 Instruction *FirstNonPhiInBBEnd = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001219 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
Manman Ren93ab6492012-09-20 22:37:36 +00001220 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1221 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001222 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Michael Liao5313da32014-12-23 08:26:55 +00001223 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
Manman Ren93ab6492012-09-20 22:37:36 +00001224 } else {
1225 FirstNonPhiInBBEnd = &*I;
1226 break;
1227 }
1228 }
1229 if (!FirstNonPhiInBBEnd)
1230 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001231
Manman Ren93ab6492012-09-20 22:37:36 +00001232 // This does very trivial matching, with limited scanning, to find identical
1233 // instructions in the two blocks. We scan backward for obviously identical
1234 // instructions in an identical order.
1235 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
Michael Liao5313da32014-12-23 08:26:55 +00001236 RE1 = BB1->getInstList().rend(),
1237 RI2 = BB2->getInstList().rbegin(),
1238 RE2 = BB2->getInstList().rend();
Manman Ren93ab6492012-09-20 22:37:36 +00001239 // Skip debug info.
1240 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1241 if (RI1 == RE1)
1242 return false;
1243 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1244 if (RI2 == RE2)
1245 return false;
1246 // Skip the unconditional branches.
1247 ++RI1;
1248 ++RI2;
1249
1250 bool Changed = false;
1251 while (RI1 != RE1 && RI2 != RE2) {
1252 // Skip debug info.
1253 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1254 if (RI1 == RE1)
1255 return Changed;
1256 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1257 if (RI2 == RE2)
1258 return Changed;
1259
1260 Instruction *I1 = &*RI1, *I2 = &*RI2;
Michael Liao5313da32014-12-23 08:26:55 +00001261 auto InstPair = std::make_pair(I1, I2);
Manman Ren93ab6492012-09-20 22:37:36 +00001262 // I1 and I2 should have a single use in the same PHI node, and they
1263 // perform the same operation.
1264 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1265 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1266 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
David Majnemerba275f92015-08-19 19:54:02 +00001267 I1->isEHPad() || I2->isEHPad() ||
Manman Ren93ab6492012-09-20 22:37:36 +00001268 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1269 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1270 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1271 !I1->hasOneUse() || !I2->hasOneUse() ||
Michael Liao5313da32014-12-23 08:26:55 +00001272 !JointValueMap.count(InstPair))
Manman Ren93ab6492012-09-20 22:37:36 +00001273 return Changed;
1274
1275 // Check whether we should swap the operands of ICmpInst.
Michael Liao5313da32014-12-23 08:26:55 +00001276 // TODO: Add support of communativity.
Manman Ren93ab6492012-09-20 22:37:36 +00001277 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1278 bool SwapOpnds = false;
1279 if (ICmp1 && ICmp2 &&
1280 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1281 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1282 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1283 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1284 ICmp2->swapOperands();
1285 SwapOpnds = true;
1286 }
1287 if (!I1->isSameOperationAs(I2)) {
1288 if (SwapOpnds)
1289 ICmp2->swapOperands();
1290 return Changed;
1291 }
1292
1293 // The operands should be either the same or they need to be generated
1294 // with a PHI node after sinking. We only handle the case where there is
1295 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001296 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001297 unsigned Op1Idx = ~0U;
Manman Ren93ab6492012-09-20 22:37:36 +00001298 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1299 if (I1->getOperand(I) == I2->getOperand(I))
1300 continue;
Michael Liao5313da32014-12-23 08:26:55 +00001301 // Early exit if we have more-than one pair of different operands or if
1302 // we need a PHI node to replace a constant.
1303 if (Op1Idx != ~0U ||
Manman Ren93ab6492012-09-20 22:37:36 +00001304 isa<Constant>(I1->getOperand(I)) ||
1305 isa<Constant>(I2->getOperand(I))) {
1306 // If we can't sink the instructions, undo the swapping.
1307 if (SwapOpnds)
1308 ICmp2->swapOperands();
1309 return Changed;
1310 }
1311 DifferentOp1 = I1->getOperand(I);
1312 Op1Idx = I;
1313 DifferentOp2 = I2->getOperand(I);
1314 }
1315
Michael Liao5313da32014-12-23 08:26:55 +00001316 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1317 DEBUG(dbgs() << " " << *I2 << "\n");
1318
1319 // We insert the pair of different operands to JointValueMap and
1320 // remove (I1, I2) from JointValueMap.
1321 if (Op1Idx != ~0U) {
1322 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1323 if (!NewPN) {
1324 NewPN =
1325 PHINode::Create(DifferentOp1->getType(), 2,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001326 DifferentOp1->getName() + ".sink", &BBEnd->front());
Michael Liao5313da32014-12-23 08:26:55 +00001327 NewPN->addIncoming(DifferentOp1, BB1);
1328 NewPN->addIncoming(DifferentOp2, BB2);
1329 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1330 }
Manman Ren93ab6492012-09-20 22:37:36 +00001331 // I1 should use NewPN instead of DifferentOp1.
1332 I1->setOperand(Op1Idx, NewPN);
Manman Ren93ab6492012-09-20 22:37:36 +00001333 }
Michael Liao5313da32014-12-23 08:26:55 +00001334 PHINode *OldPN = JointValueMap[InstPair];
1335 JointValueMap.erase(InstPair);
Manman Ren93ab6492012-09-20 22:37:36 +00001336
Manman Ren93ab6492012-09-20 22:37:36 +00001337 // We need to update RE1 and RE2 if we are going to sink the first
1338 // instruction in the basic block down.
1339 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1340 // Sink the instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001341 BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(),
1342 BB1->getInstList(), I1);
Manman Ren93ab6492012-09-20 22:37:36 +00001343 if (!OldPN->use_empty())
1344 OldPN->replaceAllUsesWith(I1);
1345 OldPN->eraseFromParent();
1346
1347 if (!I2->use_empty())
1348 I2->replaceAllUsesWith(I1);
1349 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001350 // TODO: Use combineMetadata here to preserve what metadata we can
1351 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001352 I2->eraseFromParent();
1353
1354 if (UpdateRE1)
1355 RE1 = BB1->getInstList().rend();
1356 if (UpdateRE2)
1357 RE2 = BB2->getInstList().rend();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001358 FirstNonPhiInBBEnd = &*I1;
Manman Ren93ab6492012-09-20 22:37:36 +00001359 NumSinkCommons++;
1360 Changed = true;
1361 }
1362 return Changed;
1363}
1364
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001365/// \brief Determine if we can hoist sink a sole store instruction out of a
1366/// conditional block.
1367///
1368/// We are looking for code like the following:
1369/// BrBB:
1370/// store i32 %add, i32* %arrayidx2
1371/// ... // No other stores or function calls (we could be calling a memory
1372/// ... // function).
1373/// %cmp = icmp ult %x, %y
1374/// br i1 %cmp, label %EndBB, label %ThenBB
1375/// ThenBB:
1376/// store i32 %add5, i32* %arrayidx2
1377/// br label EndBB
1378/// EndBB:
1379/// ...
1380/// We are going to transform this into:
1381/// BrBB:
1382/// store i32 %add, i32* %arrayidx2
1383/// ... //
1384/// %cmp = icmp ult %x, %y
1385/// %add.add5 = select i1 %cmp, i32 %add, %add5
1386/// store i32 %add.add5, i32* %arrayidx2
1387/// ...
1388///
1389/// \return The pointer to the value of the previous store if the store can be
1390/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001391static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1392 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001393 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1394 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001395 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001396
1397 // Volatile or atomic.
1398 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001399 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001400
1401 Value *StorePtr = StoreToHoist->getPointerOperand();
1402
1403 // Look for a store to the same pointer in BrBB.
1404 unsigned MaxNumInstToLookAt = 10;
1405 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1406 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1407 Instruction *CurI = &*RI;
1408
1409 // Could be calling an instruction that effects memory like free().
1410 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001411 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001412
1413 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1414 // Found the previous store make sure it stores to the same location.
1415 if (SI && SI->getPointerOperand() == StorePtr)
1416 // Found the previous store, return its value operand.
1417 return SI->getValueOperand();
1418 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001419 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001420 }
1421
Craig Topperf40110f2014-04-25 05:29:35 +00001422 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001423}
1424
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001425/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001426///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001427/// Note that this is a very risky transform currently. Speculating
1428/// instructions like this is most often not desirable. Instead, there is an MI
1429/// pass which can do it with full awareness of the resource constraints.
1430/// However, some cases are "obvious" and we should do directly. An example of
1431/// this is speculating a single, reasonably cheap instruction.
1432///
1433/// There is only one distinct advantage to flattening the CFG at the IR level:
1434/// it makes very common but simplistic optimizations such as are common in
1435/// instcombine and the DAG combiner more powerful by removing CFG edges and
1436/// modeling their effects with easier to reason about SSA value graphs.
1437///
1438///
1439/// An illustration of this transform is turning this IR:
1440/// \code
1441/// BB:
1442/// %cmp = icmp ult %x, %y
1443/// br i1 %cmp, label %EndBB, label %ThenBB
1444/// ThenBB:
1445/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001446/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001447/// EndBB:
1448/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1449/// ...
1450/// \endcode
1451///
1452/// Into this IR:
1453/// \code
1454/// BB:
1455/// %cmp = icmp ult %x, %y
1456/// %sub = sub %x, %y
1457/// %cond = select i1 %cmp, 0, %sub
1458/// ...
1459/// \endcode
1460///
1461/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001462static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001463 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001464 // Be conservative for now. FP select instruction can often be expensive.
1465 Value *BrCond = BI->getCondition();
1466 if (isa<FCmpInst>(BrCond))
1467 return false;
1468
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001469 BasicBlock *BB = BI->getParent();
1470 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1471
1472 // If ThenBB is actually on the false edge of the conditional branch, remember
1473 // to swap the select operands later.
1474 bool Invert = false;
1475 if (ThenBB != BI->getSuccessor(0)) {
1476 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1477 Invert = true;
1478 }
1479 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1480
Chandler Carruthceff2222013-01-25 05:40:09 +00001481 // Keep a count of how many times instructions are used within CondBB when
1482 // they are candidates for sinking into CondBB. Specifically:
1483 // - They are defined in BB, and
1484 // - They have no side effects, and
1485 // - All of their uses are in CondBB.
1486 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1487
Chandler Carruth7481ca82013-01-24 11:52:58 +00001488 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001489 Value *SpeculatedStoreValue = nullptr;
1490 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001491 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001492 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001493 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001494 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001495 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001496 if (isa<DbgInfoIntrinsic>(I))
1497 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001498
Mark Lacey274f48b2015-04-12 18:18:51 +00001499 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001500 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001501 ++SpeculationCost;
1502 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001503 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001504
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001505 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001506 if (!isSafeToSpeculativelyExecute(I) &&
1507 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1508 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001509 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001510 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001511 ComputeSpeculationCost(I, TTI) >
1512 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001513 return false;
1514
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001515 // Store the store speculation candidate.
1516 if (SpeculatedStoreValue)
1517 SpeculatedStore = cast<StoreInst>(I);
1518
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001519 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001520 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001521 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001522 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001523 i != e; ++i) {
1524 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001525 if (!OpI || OpI->getParent() != BB ||
1526 OpI->mayHaveSideEffects())
1527 continue; // Not a candidate for sinking.
1528
1529 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001530 }
1531 }
Evan Cheng89200c92008-06-07 08:52:29 +00001532
Chandler Carruthceff2222013-01-25 05:40:09 +00001533 // Consider any sink candidates which are only used in CondBB as costs for
1534 // speculation. Note, while we iterate over a DenseMap here, we are summing
1535 // and so iteration order isn't significant.
1536 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1537 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1538 I != E; ++I)
1539 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001540 ++SpeculationCost;
1541 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001542 return false;
1543 }
1544
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001545 // Check that the PHI nodes can be converted to selects.
1546 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001547 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001548 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001549 Value *OrigV = PN->getIncomingValueForBlock(BB);
1550 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001551
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001552 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001553 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001554 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001555 continue;
1556
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001557 // Don't convert to selects if we could remove undefined behavior instead.
1558 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1559 passingValueIsAlwaysUndefined(ThenV, PN))
1560 return false;
1561
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001562 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001563 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1564 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1565 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001566 continue; // Known safe and cheap.
1567
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001568 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1569 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001570 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001571 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1572 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
James Molloy7c336572015-02-11 12:15:41 +00001573 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1574 TargetTransformInfo::TCC_Basic;
1575 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00001576 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001577
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001578 // Account for the cost of an unfolded ConstantExpr which could end up
1579 // getting expanded into Instructions.
1580 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001581 // constant expression.
1582 ++SpeculationCost;
1583 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001584 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001585 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001586
1587 // If there are no PHIs to process, bail early. This helps ensure idempotence
1588 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001589 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001590 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001591
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001592 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001593 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001594
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001595 // Insert a select of the value of the speculated store.
1596 if (SpeculatedStoreValue) {
1597 IRBuilder<true, NoFolder> Builder(BI);
1598 Value *TrueV = SpeculatedStore->getValueOperand();
1599 Value *FalseV = SpeculatedStoreValue;
1600 if (Invert)
1601 std::swap(TrueV, FalseV);
1602 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1603 "." + FalseV->getName());
1604 SpeculatedStore->setOperand(0, S);
1605 }
1606
Chandler Carruth7481ca82013-01-24 11:52:58 +00001607 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001608 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
1609 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001610
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001611 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001612 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001613 for (BasicBlock::iterator I = EndBB->begin();
1614 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1615 unsigned OrigI = PN->getBasicBlockIndex(BB);
1616 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1617 Value *OrigV = PN->getIncomingValue(OrigI);
1618 Value *ThenV = PN->getIncomingValue(ThenI);
1619
1620 // Skip PHIs which are trivial.
1621 if (OrigV == ThenV)
1622 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001623
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001624 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001625 // false value is the preexisting value. Swap them if the branch
1626 // destinations were inverted.
1627 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001628 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001629 std::swap(TrueV, FalseV);
1630 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1631 TrueV->getName() + "." + FalseV->getName());
1632 PN->setIncomingValue(OrigI, V);
1633 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001634 }
1635
Evan Cheng89553cc2008-06-12 21:15:59 +00001636 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001637 return true;
1638}
1639
Tom Stellarde1631dd2013-10-21 20:07:30 +00001640/// \returns True if this block contains a CallInst with the NoDuplicate
1641/// attribute.
1642static bool HasNoDuplicateCall(const BasicBlock *BB) {
1643 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1644 const CallInst *CI = dyn_cast<CallInst>(I);
1645 if (!CI)
1646 continue;
1647 if (CI->cannotDuplicate())
1648 return true;
1649 }
1650 return false;
1651}
1652
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001653/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001654static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1655 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001656 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001657
Devang Patel84fceff2009-03-10 18:00:05 +00001658 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001659 if (isa<DbgInfoIntrinsic>(BBI))
1660 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001661 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001662 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001663
Dale Johannesened6f5a82009-03-12 23:18:09 +00001664 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001665 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001666 for (User *U : BBI->users()) {
1667 Instruction *UI = cast<Instruction>(U);
1668 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001669 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001670
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001671 // Looks ok, continue checking.
1672 }
Chris Lattner6c701062005-09-20 01:48:40 +00001673
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001674 return true;
1675}
1676
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001677/// If we have a conditional branch on a PHI node value that is defined in the
1678/// same block as the branch and if any PHI entries are constants, thread edges
1679/// corresponding to that entry to be branches to their ultimate destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001680static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001681 BasicBlock *BB = BI->getParent();
1682 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001683 // NOTE: we currently cannot transform this case if the PHI node is used
1684 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001685 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1686 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001687
Chris Lattner748f9032005-09-19 23:49:37 +00001688 // Degenerate case of a single entry PHI.
1689 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001690 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001691 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001692 }
1693
1694 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001695 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001696
Tom Stellarde1631dd2013-10-21 20:07:30 +00001697 if (HasNoDuplicateCall(BB)) return false;
1698
Chris Lattner748f9032005-09-19 23:49:37 +00001699 // Okay, this is a simple enough basic block. See if any phi values are
1700 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001701 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001702 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001703 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001704
Chris Lattner4088e2b2010-12-13 01:47:07 +00001705 // Okay, we now know that all edges from PredBB should be revectored to
1706 // branch to RealDest.
1707 BasicBlock *PredBB = PN->getIncomingBlock(i);
1708 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001709
Chris Lattner4088e2b2010-12-13 01:47:07 +00001710 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001711 // Skip if the predecessor's terminator is an indirect branch.
1712 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001713
Chris Lattner4088e2b2010-12-13 01:47:07 +00001714 // The dest block might have PHI nodes, other predecessors and other
1715 // difficult cases. Instead of being smart about this, just insert a new
1716 // block that jumps to the destination block, effectively splitting
1717 // the edge we are about to create.
1718 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1719 RealDest->getName()+".critedge",
1720 RealDest->getParent(), RealDest);
1721 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001722
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001723 // Update PHI nodes.
1724 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001725
1726 // BB may have instructions that are being threaded over. Clone these
1727 // instructions into EdgeBB. We know that there will be no uses of the
1728 // cloned instructions outside of EdgeBB.
1729 BasicBlock::iterator InsertPt = EdgeBB->begin();
1730 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1731 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1732 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1733 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1734 continue;
1735 }
1736 // Clone the instruction.
1737 Instruction *N = BBI->clone();
1738 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001739
Chris Lattner4088e2b2010-12-13 01:47:07 +00001740 // Update operands due to translation.
1741 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1742 i != e; ++i) {
1743 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1744 if (PI != TranslateMap.end())
1745 *i = PI->second;
1746 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001747
Chris Lattner4088e2b2010-12-13 01:47:07 +00001748 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001749 if (Value *V = SimplifyInstruction(N, DL)) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001750 TranslateMap[&*BBI] = V;
Chris Lattnerd7beca32010-12-14 06:17:25 +00001751 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001752 } else {
1753 // Insert the new instruction into its new home.
1754 EdgeBB->getInstList().insert(InsertPt, N);
1755 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001756 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001757 }
1758 }
1759
1760 // Loop over all of the edges from PredBB to BB, changing them to branch
1761 // to EdgeBB instead.
1762 TerminatorInst *PredBBTI = PredBB->getTerminator();
1763 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1764 if (PredBBTI->getSuccessor(i) == BB) {
1765 BB->removePredecessor(PredBB);
1766 PredBBTI->setSuccessor(i, EdgeBB);
1767 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001768
Chris Lattner4088e2b2010-12-13 01:47:07 +00001769 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001770 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001771 }
Chris Lattner748f9032005-09-19 23:49:37 +00001772
1773 return false;
1774}
1775
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001776/// Given a BB that starts with the specified two-entry PHI node,
1777/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001778static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1779 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001780 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1781 // statement", which has a very simple dominance structure. Basically, we
1782 // are trying to find the condition that is being branched on, which
1783 // subsequently causes this merge to happen. We really want control
1784 // dependence information for this check, but simplifycfg can't keep it up
1785 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001786 BasicBlock *BB = PN->getParent();
1787 BasicBlock *IfTrue, *IfFalse;
1788 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001789 if (!IfCond ||
1790 // Don't bother if the branch will be constant folded trivially.
1791 isa<ConstantInt>(IfCond))
1792 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001793
Chris Lattner95adf8f12006-11-18 19:19:36 +00001794 // Okay, we found that we can merge this two-entry phi node into a select.
1795 // Doing so would require us to fold *all* two entry phi nodes in this block.
1796 // At some point this becomes non-profitable (particularly if the target
1797 // doesn't support cmov's). Only do this transformation if there are two or
1798 // fewer PHI nodes in this block.
1799 unsigned NumPhis = 0;
1800 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1801 if (NumPhis > 2)
1802 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001803
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001804 // Loop over the PHI's seeing if we can promote them all to select
1805 // instructions. While we are at it, keep track of the instructions
1806 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001807 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001808 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1809 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00001810 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1811 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001812
Chris Lattner7499b452010-12-14 08:46:09 +00001813 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1814 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001815 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001816 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001817 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001818 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001819 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001820
Peter Collingbournee3511e12011-04-29 18:47:31 +00001821 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001822 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001823 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001824 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001825 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001826 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001827
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001828 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001829 // we ran out of PHIs then we simplified them all.
1830 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001831 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001832
Chris Lattner7499b452010-12-14 08:46:09 +00001833 // Don't fold i1 branches on PHIs which contain binary operators. These can
1834 // often be turned into switches and other things.
1835 if (PN->getType()->isIntegerTy(1) &&
1836 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1837 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1838 isa<BinaryOperator>(IfCond)))
1839 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001840
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001841 // If we all PHI nodes are promotable, check to make sure that all
1842 // instructions in the predecessor blocks can be promoted as well. If
1843 // not, we won't be able to get rid of the control flow, so it's not
1844 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001845 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001846 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1847 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1848 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001849 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001850 } else {
1851 DomBlock = *pred_begin(IfBlock1);
1852 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001853 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001854 // This is not an aggressive instruction that we can promote.
1855 // Because of this, we won't be able to get rid of the control
1856 // flow, so the xform is not worth it.
1857 return false;
1858 }
1859 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001860
Chris Lattner9ac168d2010-12-14 07:41:39 +00001861 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001862 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001863 } else {
1864 DomBlock = *pred_begin(IfBlock2);
1865 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001866 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001867 // This is not an aggressive instruction that we can promote.
1868 // Because of this, we won't be able to get rid of the control
1869 // flow, so the xform is not worth it.
1870 return false;
1871 }
1872 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001873
Chris Lattner9fd838d2010-12-14 07:23:10 +00001874 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001875 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001876
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001877 // If we can still promote the PHI nodes after this gauntlet of tests,
1878 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001879 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001880 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001881
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001882 // Move all 'aggressive' instructions, which are defined in the
1883 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001884 if (IfBlock1)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001885 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001886 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001887 IfBlock1->getTerminator()->getIterator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001888 if (IfBlock2)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001889 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001890 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001891 IfBlock2->getTerminator()->getIterator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001892
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001893 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1894 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001895 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1896 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001897
1898 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001899 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001900 PN->replaceAllUsesWith(NV);
1901 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001902 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001903 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001904
Chris Lattner335f0e42010-12-14 08:01:53 +00001905 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1906 // has been flattened. Change DomBlock to jump directly to our new block to
1907 // avoid other simplifycfg's kicking in on the diamond.
1908 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001909 Builder.SetInsertPoint(OldTI);
1910 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001911 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001912 return true;
1913}
Chris Lattner748f9032005-09-19 23:49:37 +00001914
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001915/// If we found a conditional branch that goes to two returning blocks,
1916/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00001917/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001918static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001919 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001920 assert(BI->isConditional() && "Must be a conditional branch");
1921 BasicBlock *TrueSucc = BI->getSuccessor(0);
1922 BasicBlock *FalseSucc = BI->getSuccessor(1);
1923 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1924 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001925
Chris Lattner86bbf332008-04-24 00:01:19 +00001926 // Check to ensure both blocks are empty (just a return) or optionally empty
1927 // with PHI nodes. If there are other instructions, merging would cause extra
1928 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001929 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001930 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001931 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001932 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001933
Devang Pateldd14e0f2011-05-18 21:33:11 +00001934 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001935 // Okay, we found a branch that is going to two return nodes. If
1936 // there is no return value for this function, just change the
1937 // branch into a return.
1938 if (FalseRet->getNumOperands() == 0) {
1939 TrueSucc->removePredecessor(BI->getParent());
1940 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001941 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001942 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001943 return true;
1944 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001945
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001946 // Otherwise, figure out what the true and false return values are
1947 // so we can insert a new select instruction.
1948 Value *TrueValue = TrueRet->getReturnValue();
1949 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001950
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001951 // Unwrap any PHI nodes in the return blocks.
1952 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1953 if (TVPN->getParent() == TrueSucc)
1954 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1955 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1956 if (FVPN->getParent() == FalseSucc)
1957 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001958
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001959 // In order for this transformation to be safe, we must be able to
1960 // unconditionally execute both operands to the return. This is
1961 // normally the case, but we could have a potentially-trapping
1962 // constant expression that prevents this transformation from being
1963 // safe.
1964 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1965 if (TCV->canTrap())
1966 return false;
1967 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1968 if (FCV->canTrap())
1969 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001970
Chris Lattner86bbf332008-04-24 00:01:19 +00001971 // Okay, we collected all the mapped values and checked them for sanity, and
1972 // defined to really do this transformation. First, update the CFG.
1973 TrueSucc->removePredecessor(BI->getParent());
1974 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001975
Chris Lattner86bbf332008-04-24 00:01:19 +00001976 // Insert select instructions where needed.
1977 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001978 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001979 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001980 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1981 } else if (isa<UndefValue>(TrueValue)) {
1982 TrueValue = FalseValue;
1983 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00001984 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1985 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00001986 }
Chris Lattner86bbf332008-04-24 00:01:19 +00001987 }
1988
Andrew Trickf3cf1932012-08-29 21:46:36 +00001989 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00001990 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1991
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00001992 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001993
David Greene725c7c32010-01-05 01:26:52 +00001994 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00001995 << "\n " << *BI << "NewRet = " << *RI
1996 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001997
Eli Friedmancb61afb2008-12-16 20:54:32 +00001998 EraseTerminatorInstAndDCECond(BI);
1999
Chris Lattner86bbf332008-04-24 00:01:19 +00002000 return true;
2001}
2002
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002003/// Given a conditional BranchInstruction, retrieve the probabilities of the
2004/// branch taking each edge. Fills in the two APInt parameters and returns true,
2005/// or returns false if no or invalid metadata was found.
Juergen Ributzka194350a2014-12-09 17:32:12 +00002006static bool ExtractBranchMetadata(BranchInst *BI,
2007 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2008 assert(BI->isConditional() &&
2009 "Looking for probabilities on unconditional branch?");
2010 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2011 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002012 ConstantInt *CITrue =
2013 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2014 ConstantInt *CIFalse =
2015 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00002016 if (!CITrue || !CIFalse) return false;
2017 ProbTrue = CITrue->getValue().getZExtValue();
2018 ProbFalse = CIFalse->getValue().getZExtValue();
2019 return true;
2020}
2021
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002022/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002023/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002024static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002025 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2026 return false;
2027 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2028 Instruction *PBI = &*I;
2029 // Check whether Inst and PBI generate the same value.
2030 if (Inst->isIdenticalTo(PBI)) {
2031 Inst->replaceAllUsesWith(PBI);
2032 Inst->eraseFromParent();
2033 return true;
2034 }
2035 }
2036 return false;
2037}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002038
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002039/// If this basic block is simple enough, and if a predecessor branches to us
2040/// and one of our successors, fold the block into the predecessor and use
2041/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002042bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002043 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002044
Craig Topperf40110f2014-04-25 05:29:35 +00002045 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002046 if (BI->isConditional())
2047 Cond = dyn_cast<Instruction>(BI->getCondition());
2048 else {
2049 // For unconditional branch, check for a simple CFG pattern, where
2050 // BB has a single predecessor and BB's successor is also its predecessor's
2051 // successor. If such pattern exisits, check for CSE between BB and its
2052 // predecessor.
2053 if (BasicBlock *PB = BB->getSinglePredecessor())
2054 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2055 if (PBI->isConditional() &&
2056 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2057 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2058 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2059 I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002060 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002061 if (isa<CmpInst>(Curr)) {
2062 Cond = Curr;
2063 break;
2064 }
2065 // Quit if we can't remove this instruction.
2066 if (!checkCSEInPredecessor(Curr, PB))
2067 return false;
2068 }
2069 }
2070
Craig Topperf40110f2014-04-25 05:29:35 +00002071 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002072 return false;
2073 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002074
Craig Topperf40110f2014-04-25 05:29:35 +00002075 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2076 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002077 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002078
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002079 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002080 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002081
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002082 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002083 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002084
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002085 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002086 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002087
Jingyue Wufc029672014-09-30 22:23:38 +00002088 // Only allow this transformation if computing the condition doesn't involve
2089 // too many instructions and these involved instructions can be executed
2090 // unconditionally. We denote all involved instructions except the condition
2091 // as "bonus instructions", and only allow this transformation when the
2092 // number of the bonus instructions does not exceed a certain threshold.
2093 unsigned NumBonusInsts = 0;
2094 for (auto I = BB->begin(); Cond != I; ++I) {
2095 // Ignore dbg intrinsics.
2096 if (isa<DbgInfoIntrinsic>(I))
2097 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002098 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002099 return false;
2100 // I has only one use and can be executed unconditionally.
2101 Instruction *User = dyn_cast<Instruction>(I->user_back());
2102 if (User == nullptr || User->getParent() != BB)
2103 return false;
2104 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2105 // to use any other instruction, User must be an instruction between next(I)
2106 // and Cond.
2107 ++NumBonusInsts;
2108 // Early exits once we reach the limit.
2109 if (NumBonusInsts > BonusInstThreshold)
2110 return false;
2111 }
2112
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002113 // Cond is known to be a compare or binary operator. Check to make sure that
2114 // neither operand is a potentially-trapping constant expression.
2115 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2116 if (CE->canTrap())
2117 return false;
2118 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2119 if (CE->canTrap())
2120 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002121
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002122 // Finally, don't infinitely unroll conditional loops.
2123 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002124 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002125 if (TrueDest == BB || FalseDest == BB)
2126 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002127
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002128 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2129 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002130 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002131
Chris Lattner80b03a12008-07-13 22:23:11 +00002132 // Check that we have two conditional branches. If there is a PHI node in
2133 // the common successor, verify that the same value flows in from both
2134 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002135 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002136 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002137 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002138 !SafeToMergeTerminators(BI, PBI)) ||
2139 (!BI->isConditional() &&
2140 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002141 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002142
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002143 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002144 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002145 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002146
Manman Rend33f4ef2012-06-13 05:43:29 +00002147 if (BI->isConditional()) {
2148 if (PBI->getSuccessor(0) == TrueDest)
2149 Opc = Instruction::Or;
2150 else if (PBI->getSuccessor(1) == FalseDest)
2151 Opc = Instruction::And;
2152 else if (PBI->getSuccessor(0) == FalseDest)
2153 Opc = Instruction::And, InvertPredCond = true;
2154 else if (PBI->getSuccessor(1) == TrueDest)
2155 Opc = Instruction::Or, InvertPredCond = true;
2156 else
2157 continue;
2158 } else {
2159 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2160 continue;
2161 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002162
David Greene725c7c32010-01-05 01:26:52 +00002163 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002164 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002165
Chris Lattner55eaae12008-07-13 21:20:19 +00002166 // If we need to invert the condition in the pred block to match, do so now.
2167 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002168 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002169
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002170 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2171 CmpInst *CI = cast<CmpInst>(NewCond);
2172 CI->setPredicate(CI->getInversePredicate());
2173 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002174 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002175 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002176 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002177
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002178 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002179 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002180 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002181
Jingyue Wufc029672014-09-30 22:23:38 +00002182 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002183 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002184 // bonus instructions to a predecessor block.
2185 ValueToValueMapTy VMap; // maps original values to cloned values
2186 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002187 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002188 // instructions.
2189 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2190 if (isa<DbgInfoIntrinsic>(BonusInst))
2191 continue;
2192 Instruction *NewBonusInst = BonusInst->clone();
2193 RemapInstruction(NewBonusInst, VMap,
2194 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002195 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002196
2197 // If we moved a load, we cannot any longer claim any knowledge about
2198 // its potential value. The previous information might have been valid
2199 // only given the branch precondition.
2200 // For an analogous reason, we must also drop all the metadata whose
2201 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002202 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002203
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002204 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2205 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002206 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002207 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002208
Chris Lattner55eaae12008-07-13 21:20:19 +00002209 // Clone Cond into the predecessor basic block, and or/and the
2210 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002211 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002212 RemapInstruction(New, VMap,
2213 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002214 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002215 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002216 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002217
Manman Rend33f4ef2012-06-13 05:43:29 +00002218 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002219 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002220 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002221 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002222 PBI->setCondition(NewCond);
2223
Manman Renbfb9d432012-09-15 00:39:57 +00002224 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002225 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2226 PredFalseWeight);
2227 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2228 SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002229 SmallVector<uint64_t, 8> NewWeights;
2230
Manman Rend33f4ef2012-06-13 05:43:29 +00002231 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002232 if (PredHasWeights && SuccHasWeights) {
2233 // PBI: br i1 %x, BB, FalseDest
2234 // BI: br i1 %y, TrueDest, FalseDest
2235 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2236 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2237 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2238 // TrueWeight for PBI * FalseWeight for BI.
2239 // We assume that total weights of a BranchInst can fit into 32 bits.
2240 // Therefore, we will not have overflow using 64-bit arithmetic.
2241 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2242 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2243 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002244 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2245 PBI->setSuccessor(0, TrueDest);
2246 }
2247 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002248 if (PredHasWeights && SuccHasWeights) {
2249 // PBI: br i1 %x, TrueDest, BB
2250 // BI: br i1 %y, TrueDest, FalseDest
2251 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2252 // FalseWeight for PBI * TrueWeight for BI.
2253 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2254 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2255 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2256 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2257 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002258 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2259 PBI->setSuccessor(1, FalseDest);
2260 }
Manman Renbfb9d432012-09-15 00:39:57 +00002261 if (NewWeights.size() == 2) {
2262 // Halve the weights if any of them cannot fit in an uint32_t
2263 FitWeights(NewWeights);
2264
2265 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2266 PBI->setMetadata(LLVMContext::MD_prof,
2267 MDBuilder(BI->getContext()).
2268 createBranchWeights(MDWeights));
2269 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002270 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002271 } else {
2272 // Update PHI nodes in the common successors.
2273 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002274 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002275 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2276 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002277 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002278 if (PBI->getSuccessor(0) == TrueDest) {
2279 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2280 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2281 // is false: !PBI_Cond and BI_Value
2282 Instruction *NotCond =
2283 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2284 "not.cond"));
2285 MergedCond =
2286 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2287 NotCond, New,
2288 "and.cond"));
2289 if (PBI_C->isOne())
2290 MergedCond =
2291 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2292 PBI->getCondition(), MergedCond,
2293 "or.cond"));
2294 } else {
2295 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2296 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2297 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002298 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002299 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2300 PBI->getCondition(), New,
2301 "and.cond"));
2302 if (PBI_C->isOne()) {
2303 Instruction *NotCond =
2304 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2305 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002306 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002307 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2308 NotCond, MergedCond,
2309 "or.cond"));
2310 }
2311 }
2312 // Update PHI Node.
2313 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2314 MergedCond);
2315 }
2316 // Change PBI from Conditional to Unconditional.
2317 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2318 EraseTerminatorInstAndDCECond(PBI);
2319 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002320 }
Devang Pateld715ec82011-04-06 22:37:20 +00002321
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002322 // TODO: If BB is reachable from all paths through PredBlock, then we
2323 // could replace PBI's branch probabilities with BI's.
2324
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002325 // Copy any debug value intrinsics into the end of PredBlock.
2326 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2327 if (isa<DbgInfoIntrinsic>(*I))
2328 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002329
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002330 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002331 }
2332 return false;
2333}
2334
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002335/// If we have a conditional branch as a predecessor of another block,
2336/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00002337/// that PBI and BI are both conditional branches, and BI is in one of the
2338/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00002339static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
2340 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00002341 assert(PBI->isConditional() && BI->isConditional());
2342 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002343
Chris Lattner9aada1d2008-07-13 21:53:26 +00002344 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002345 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002346 // this conditional branch redundant.
2347 if (PBI->getCondition() == BI->getCondition() &&
2348 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2349 // Okay, the outcome of this conditional branch is statically
2350 // knowable. If this block had a single pred, handle specially.
2351 if (BB->getSinglePredecessor()) {
2352 // Turn this into a branch on constant.
2353 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002354 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002355 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002356 return true; // Nuke the branch on constant.
2357 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002358
Chris Lattner9aada1d2008-07-13 21:53:26 +00002359 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2360 // in the constant and simplify the block result. Subsequent passes of
2361 // simplifycfg will thread the block.
2362 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002363 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002364 PHINode *NewPN = PHINode::Create(
2365 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
2366 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00002367 // Okay, we're going to insert the PHI node. Since PBI is not the only
2368 // predecessor, compute the PHI'd conditional value for all of the preds.
2369 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002370 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002371 BasicBlock *P = *PI;
2372 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002373 PBI != BI && PBI->isConditional() &&
2374 PBI->getCondition() == BI->getCondition() &&
2375 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2376 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002377 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002378 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002379 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002380 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002381 }
Gabor Greif8629f122010-07-12 10:59:23 +00002382 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002383
Chris Lattner9aada1d2008-07-13 21:53:26 +00002384 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002385 return true;
2386 }
2387 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002388
Philip Reamesb42db212015-10-14 22:46:19 +00002389 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2390 if (CE->canTrap())
2391 return false;
2392
Chris Lattner9aada1d2008-07-13 21:53:26 +00002393 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002394 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002395 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002396 BasicBlock::iterator BBI = BB->begin();
2397 // Ignore dbg intrinsics.
2398 while (isa<DbgInfoIntrinsic>(BBI))
2399 ++BBI;
2400 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002401 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002402
Chris Lattner834ab4e2008-07-13 22:04:41 +00002403 int PBIOp, BIOp;
2404 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2405 PBIOp = BIOp = 0;
2406 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2407 PBIOp = 0, BIOp = 1;
2408 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2409 PBIOp = 1, BIOp = 0;
2410 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2411 PBIOp = BIOp = 1;
2412 else
2413 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002414
Chris Lattner834ab4e2008-07-13 22:04:41 +00002415 // Check to make sure that the other destination of this branch
2416 // isn't BB itself. If so, this is an infinite loop that will
2417 // keep getting unwound.
2418 if (PBI->getSuccessor(PBIOp) == BB)
2419 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002420
2421 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002422 // insertion of a large number of select instructions. For targets
2423 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002424
Sanjay Patela932da82014-07-07 21:19:00 +00002425 // Also do not perform this transformation if any phi node in the common
2426 // destination block can trap when reached by BB or PBB (PR17073). In that
2427 // case, it would be unsafe to hoist the operation into a select instruction.
2428
2429 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002430 unsigned NumPhis = 0;
2431 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002432 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002433 if (NumPhis > 2) // Disable this xform.
2434 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002435
Sanjay Patela932da82014-07-07 21:19:00 +00002436 PHINode *PN = cast<PHINode>(II);
2437 Value *BIV = PN->getIncomingValueForBlock(BB);
2438 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2439 if (CE->canTrap())
2440 return false;
2441
2442 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2443 Value *PBIV = PN->getIncomingValue(PBBIdx);
2444 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2445 if (CE->canTrap())
2446 return false;
2447 }
2448
Chris Lattner834ab4e2008-07-13 22:04:41 +00002449 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002450 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002451
David Greene725c7c32010-01-05 01:26:52 +00002452 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002453 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002454
2455
Chris Lattner80b03a12008-07-13 22:23:11 +00002456 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2457 // branch in it, where one edge (OtherDest) goes back to itself but the other
2458 // exits. We don't *know* that the program avoids the infinite loop
2459 // (even though that seems likely). If we do this xform naively, we'll end up
2460 // recursively unpeeling the loop. Since we know that (after the xform is
2461 // done) that the block *is* infinite if reached, we just make it an obviously
2462 // infinite loop with no cond branch.
2463 if (OtherDest == BB) {
2464 // Insert it at the end of the function, because it's either code,
2465 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002466 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2467 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002468 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2469 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002470 }
2471
David Greene725c7c32010-01-05 01:26:52 +00002472 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002473
Chris Lattner834ab4e2008-07-13 22:04:41 +00002474 // BI may have other predecessors. Because of this, we leave
2475 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002476
Chris Lattner834ab4e2008-07-13 22:04:41 +00002477 // Make sure we get to CommonDest on True&True directions.
2478 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002479 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002480 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002481 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2482
Chris Lattner834ab4e2008-07-13 22:04:41 +00002483 Value *BICond = BI->getCondition();
2484 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002485 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2486
Chris Lattner834ab4e2008-07-13 22:04:41 +00002487 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002488 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002489
Chris Lattner834ab4e2008-07-13 22:04:41 +00002490 // Modify PBI to branch on the new condition to the new dests.
2491 PBI->setCondition(Cond);
2492 PBI->setSuccessor(0, CommonDest);
2493 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002494
Manman Ren2d4c10f2012-09-17 21:30:40 +00002495 // Update branch weight for PBI.
2496 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002497 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2498 PredFalseWeight);
2499 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2500 SuccFalseWeight);
Manman Ren2d4c10f2012-09-17 21:30:40 +00002501 if (PredHasWeights && SuccHasWeights) {
2502 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2503 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2504 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2505 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2506 // The weight to CommonDest should be PredCommon * SuccTotal +
2507 // PredOther * SuccCommon.
2508 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00002509 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2510 PredOther * SuccCommon,
2511 PredOther * SuccOther};
Manman Ren2d4c10f2012-09-17 21:30:40 +00002512 // Halve the weights if any of them cannot fit in an uint32_t
2513 FitWeights(NewWeights);
2514
Manman Ren2d4c10f2012-09-17 21:30:40 +00002515 PBI->setMetadata(LLVMContext::MD_prof,
Benjamin Kramerea68a942015-02-19 15:26:17 +00002516 MDBuilder(BI->getContext())
2517 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00002518 }
2519
Chris Lattner834ab4e2008-07-13 22:04:41 +00002520 // OtherDest may have phi nodes. If so, add an entry from PBI's
2521 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002522 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002523
Chris Lattner834ab4e2008-07-13 22:04:41 +00002524 // We know that the CommonDest already had an edge from PBI to
2525 // it. If it has PHIs though, the PHIs may have different
2526 // entries for BB and PBI's BB. If so, insert a select to make
2527 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002528 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002529 for (BasicBlock::iterator II = CommonDest->begin();
2530 (PN = dyn_cast<PHINode>(II)); ++II) {
2531 Value *BIV = PN->getIncomingValueForBlock(BB);
2532 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2533 Value *PBIV = PN->getIncomingValue(PBBIdx);
2534 if (BIV != PBIV) {
2535 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002536 Value *NV = cast<SelectInst>
2537 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002538 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002539 }
2540 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002541
David Greene725c7c32010-01-05 01:26:52 +00002542 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2543 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002544
Chris Lattner834ab4e2008-07-13 22:04:41 +00002545 // This basic block is probably dead. We know it has at least
2546 // one fewer predecessor.
2547 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002548}
2549
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002550// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2551// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00002552// Takes care of updating the successors and removing the old terminator.
2553// Also makes sure not to introduce new successors by assuming that edges to
2554// non-successor TrueBBs and FalseBBs aren't reachable.
2555static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002556 BasicBlock *TrueBB, BasicBlock *FalseBB,
2557 uint32_t TrueWeight,
2558 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002559 // Remove any superfluous successor edges from the CFG.
2560 // First, figure out which successors to preserve.
2561 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2562 // successor.
2563 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002564 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002565
2566 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00002567 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002568 // Make sure only to keep exactly one copy of each edge.
2569 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002570 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002571 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002572 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002573 else
David Majnemerdc3b67b2015-10-21 18:22:24 +00002574 Succ->removePredecessor(OldTerm->getParent(),
2575 /*DontDeleteUselessPHIs=*/true);
Frits van Bommel8e158492011-01-11 12:52:11 +00002576 }
2577
Devang Patel2c2ea222011-05-18 18:43:31 +00002578 IRBuilder<> Builder(OldTerm);
2579 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2580
Frits van Bommel8e158492011-01-11 12:52:11 +00002581 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002582 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002583 if (TrueBB == FalseBB)
2584 // We were only looking for one successor, and it was present.
2585 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002586 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002587 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002588 // We found both of the successors we were looking for.
2589 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002590 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2591 if (TrueWeight != FalseWeight)
2592 NewBI->setMetadata(LLVMContext::MD_prof,
2593 MDBuilder(OldTerm->getContext()).
2594 createBranchWeights(TrueWeight, FalseWeight));
2595 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002596 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2597 // Neither of the selected blocks were successors, so this
2598 // terminator must be unreachable.
2599 new UnreachableInst(OldTerm->getContext(), OldTerm);
2600 } else {
2601 // One of the selected values was a successor, but the other wasn't.
2602 // Insert an unconditional branch to the one that was found;
2603 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002604 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002605 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002606 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002607 else
2608 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002609 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002610 }
2611
2612 EraseTerminatorInstAndDCECond(OldTerm);
2613 return true;
2614}
2615
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002616// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00002617// (switch (select cond, X, Y)) on constant X, Y
2618// with a branch - conditional if X and Y lead to distinct BBs,
2619// unconditional otherwise.
2620static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2621 // Check for constant integer values in the select.
2622 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2623 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2624 if (!TrueVal || !FalseVal)
2625 return false;
2626
2627 // Find the relevant condition and destinations.
2628 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002629 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2630 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002631
Manman Ren774246a2012-09-17 22:28:55 +00002632 // Get weight for TrueBB and FalseBB.
2633 uint32_t TrueWeight = 0, FalseWeight = 0;
2634 SmallVector<uint64_t, 8> Weights;
2635 bool HasWeights = HasBranchWeights(SI);
2636 if (HasWeights) {
2637 GetBranchWeights(SI, Weights);
2638 if (Weights.size() == 1 + SI->getNumCases()) {
2639 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2640 getSuccessorIndex()];
2641 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2642 getSuccessorIndex()];
2643 }
2644 }
2645
Frits van Bommel8ae07992011-02-28 09:44:07 +00002646 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002647 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2648 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002649}
2650
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002651// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002652// (indirectbr (select cond, blockaddress(@fn, BlockA),
2653// blockaddress(@fn, BlockB)))
2654// with
2655// (br cond, BlockA, BlockB).
2656static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2657 // Check that both operands of the select are block addresses.
2658 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2659 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2660 if (!TBA || !FBA)
2661 return false;
2662
2663 // Extract the actual blocks.
2664 BasicBlock *TrueBB = TBA->getBasicBlock();
2665 BasicBlock *FalseBB = FBA->getBasicBlock();
2666
Frits van Bommel8e158492011-01-11 12:52:11 +00002667 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002668 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2669 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002670}
2671
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002672/// This is called when we find an icmp instruction
2673/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002674/// block that ends with an uncond branch. We are looking for a very specific
2675/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2676/// this case, we merge the first two "or's of icmp" into a switch, but then the
2677/// default value goes to an uncond block with a seteq in it, we get something
2678/// like:
2679///
2680/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2681/// DEFAULT:
2682/// %tmp = icmp eq i8 %A, 92
2683/// br label %end
2684/// end:
2685/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00002686///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002687/// We prefer to split the edge to 'end' so that there is a true/false entry to
2688/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00002689static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002690 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
2691 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
2692 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002693 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00002694
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002695 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2696 // complex.
2697 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2698
2699 Value *V = ICI->getOperand(0);
2700 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002701
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002702 // The pattern we're looking for is where our only predecessor is a switch on
2703 // 'V' and this block is the default case for the switch. In this case we can
2704 // fold the compared value into the switch to simplify things.
2705 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00002706 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002707
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002708 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2709 if (SI->getCondition() != V)
2710 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002711
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002712 // If BB is reachable on a non-default case, then we simply know the value of
2713 // V in this block. Substitute it and constant fold the icmp instruction
2714 // away.
2715 if (SI->getDefaultDest() != BB) {
2716 ConstantInt *VVal = SI->findCaseDest(BB);
2717 assert(VVal && "Should have a unique destination value");
2718 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002719
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002720 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00002721 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002722 ICI->eraseFromParent();
2723 }
2724 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002725 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002726 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002727
Chris Lattner62cc76e2010-12-13 03:43:57 +00002728 // Ok, the block is reachable from the default dest. If the constant we're
2729 // comparing exists in one of the other edges, then we can constant fold ICI
2730 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002731 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00002732 Value *V;
2733 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2734 V = ConstantInt::getFalse(BB->getContext());
2735 else
2736 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002737
Chris Lattner62cc76e2010-12-13 03:43:57 +00002738 ICI->replaceAllUsesWith(V);
2739 ICI->eraseFromParent();
2740 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002741 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00002742 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002743
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002744 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2745 // the block.
2746 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00002747 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00002748 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002749 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2750 return false;
2751
2752 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2753 // true in the PHI.
2754 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2755 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2756
2757 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2758 std::swap(DefaultCst, NewCst);
2759
2760 // Replace ICI (which is used by the PHI for the default value) with true or
2761 // false depending on if it is EQ or NE.
2762 ICI->replaceAllUsesWith(DefaultCst);
2763 ICI->eraseFromParent();
2764
2765 // Okay, the switch goes to this block on a default value. Add an edge from
2766 // the switch to the merge point on the compared value.
2767 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2768 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00002769 SmallVector<uint64_t, 8> Weights;
2770 bool HasWeights = HasBranchWeights(SI);
2771 if (HasWeights) {
2772 GetBranchWeights(SI, Weights);
2773 if (Weights.size() == 1 + SI->getNumCases()) {
2774 // Split weight for default case to case for "Cst".
2775 Weights[0] = (Weights[0]+1) >> 1;
2776 Weights.push_back(Weights[0]);
2777
2778 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2779 SI->setMetadata(LLVMContext::MD_prof,
2780 MDBuilder(SI->getContext()).
2781 createBranchWeights(MDWeights));
2782 }
2783 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002784 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002785
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002786 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00002787 Builder.SetInsertPoint(NewBB);
2788 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2789 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002790 PHIUse->addIncoming(NewCst, NewBB);
2791 return true;
2792}
2793
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002794/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00002795/// Check to see if it is branching on an or/and chain of icmp instructions, and
2796/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002797static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
2798 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00002799 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00002800 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002801
Chris Lattnera69c4432010-12-13 05:03:41 +00002802 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2803 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2804 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002805
Mehdi Amini9a25cb82014-11-19 20:09:11 +00002806 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00002807 ConstantComparesGatherer ConstantCompare(Cond, DL);
2808 // Unpack the result
2809 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
2810 Value *CompVal = ConstantCompare.CompValue;
2811 unsigned UsedICmps = ConstantCompare.UsedICmps;
2812 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002813
Chris Lattnera69c4432010-12-13 05:03:41 +00002814 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00002815 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00002816
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002817 // Avoid turning single icmps into a switch.
2818 if (UsedICmps <= 1)
2819 return false;
2820
Mehdi Aminiffd01002014-11-20 22:40:25 +00002821 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
2822
Chris Lattnera69c4432010-12-13 05:03:41 +00002823 // There might be duplicate constants in the list, which the switch
2824 // instruction can't handle, remove them now.
2825 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2826 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002827
Chris Lattnera69c4432010-12-13 05:03:41 +00002828 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00002829 // transformation. A switch with one value is just a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00002830 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002831
Andrew Trick3051aa12012-08-29 21:46:38 +00002832 // TODO: Preserve branch weight metadata, similarly to how
2833 // FoldValueComparisonIntoPredecessors preserves it.
2834
Chris Lattnera69c4432010-12-13 05:03:41 +00002835 // Figure out which block is which destination.
2836 BasicBlock *DefaultBB = BI->getSuccessor(1);
2837 BasicBlock *EdgeBB = BI->getSuccessor(0);
2838 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002839
Chris Lattnera69c4432010-12-13 05:03:41 +00002840 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002841
Chris Lattnerd7beca32010-12-14 06:17:25 +00002842 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002843 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002844
Chris Lattnera69c4432010-12-13 05:03:41 +00002845 // If there are any extra values that couldn't be folded into the switch
2846 // then we evaluate them with an explicit branch first. Split the block
2847 // right before the condbr to handle it.
2848 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002849 BasicBlock *NewBB =
2850 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00002851 // Remove the uncond branch added to the old block.
2852 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00002853 Builder.SetInsertPoint(OldTI);
2854
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002855 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00002856 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002857 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00002858 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002859
Chris Lattnera69c4432010-12-13 05:03:41 +00002860 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002861
Chris Lattnercb570f82010-12-13 05:34:18 +00002862 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2863 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002864 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002865
Chris Lattnerd7beca32010-12-14 06:17:25 +00002866 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2867 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00002868 BB = NewBB;
2869 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00002870
2871 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00002872 // Convert pointer to int before we switch.
2873 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002874 CompVal = Builder.CreatePtrToInt(
2875 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00002876 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002877
Chris Lattnera69c4432010-12-13 05:03:41 +00002878 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00002879 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00002880
Chris Lattnera69c4432010-12-13 05:03:41 +00002881 // Add all of the 'cases' to the switch instruction.
2882 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2883 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002884
Chris Lattnera69c4432010-12-13 05:03:41 +00002885 // We added edges from PI to the EdgeBB. As such, if there were any
2886 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2887 // the number of edges added.
2888 for (BasicBlock::iterator BBI = EdgeBB->begin();
2889 isa<PHINode>(BBI); ++BBI) {
2890 PHINode *PN = cast<PHINode>(BBI);
2891 Value *InVal = PN->getIncomingValueForBlock(BB);
2892 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2893 PN->addIncoming(InVal, BB);
2894 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002895
Chris Lattnera69c4432010-12-13 05:03:41 +00002896 // Erase the old branch instruction.
2897 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002898
Chris Lattnerd7beca32010-12-14 06:17:25 +00002899 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00002900 return true;
2901}
2902
Duncan Sands29192d02011-09-05 12:57:57 +00002903bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2904 // If this is a trivial landing pad that just continues unwinding the caught
2905 // exception then zap the landing pad, turning its invokes into calls.
2906 BasicBlock *BB = RI->getParent();
2907 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
Chen Lic6e28782015-10-22 20:48:38 +00002908
2909 // If RI->getValue() is a landing pad, check if the first instruction is
2910 // the same landing pad that caused control to branch here. If RI->getValue
2911 // is a phi of landing pad, check its predecessor blocks to see if any of
2912 // them contains a trivial landing pad.
2913 if (RI->getValue() != LPInst && !isa<PHINode>(RI->getValue()))
Duncan Sands29192d02011-09-05 12:57:57 +00002914 return false;
2915
Chen Lic6e28782015-10-22 20:48:38 +00002916 // Check that there are no other instructions except for debug intrinsics
2917 // between the landing pad (or phi of landing pad) and resume instruction.
2918 BasicBlock::iterator I = cast<Instruction>(RI->getValue()), E = RI;
Duncan Sands29192d02011-09-05 12:57:57 +00002919 while (++I != E)
2920 if (!isa<DbgInfoIntrinsic>(I))
2921 return false;
2922
Chen Lic6e28782015-10-22 20:48:38 +00002923 SmallVector<BasicBlock *, 4> TrivialUnwindBlocks;
2924 if (RI->getValue() == LPInst) {
2925 // Landing pad is in current block, which has already been checked.
2926 TrivialUnwindBlocks.push_back(BB);
2927 } else {
2928 // Check incoming blocks to see if any of them are trivial.
2929 auto *PhiLPInst = cast<PHINode>(RI->getValue());
2930 for (unsigned i = 0; i < PhiLPInst->getNumIncomingValues(); i++) {
2931 auto *IncomingBB = PhiLPInst->getIncomingBlock(i);
2932 auto *IncomingValue = PhiLPInst->getIncomingValue(i);
2933
2934 auto *LandingPad =
2935 dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
2936 // Not the landing pad that caused the control to branch here.
2937 if (IncomingValue != LandingPad)
2938 continue;
2939
2940 bool isTrivial = true;
2941
2942 I = IncomingBB->getFirstNonPHI();
2943 E = IncomingBB->getTerminator();
2944 while (++I != E)
2945 if (!isa<DbgInfoIntrinsic>(I)) {
2946 isTrivial = false;
2947 break;
2948 }
2949
2950 if (isTrivial)
2951 TrivialUnwindBlocks.push_back(IncomingBB);
2952 }
Duncan Sands29192d02011-09-05 12:57:57 +00002953 }
2954
Chen Lic6e28782015-10-22 20:48:38 +00002955 // Turn all invokes that unwind here into calls and delete the basic block.
2956 for (auto *TrivialBB : TrivialUnwindBlocks) {
2957 if (isa<PHINode>(RI->getValue())) {
2958 // Blocks that will be deleted should also be removed
2959 // from the phi node.
2960 BB->removePredecessor(TrivialBB, true);
2961 }
2962
2963 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
2964 PI != PE;) {
2965 BasicBlock *Pred = *PI++;
2966 removeUnwindEdge(Pred);
2967 }
2968
2969 // The landingpad is now unreachable. Zap it.
2970 if (TrivialBB == BB)
2971 BB = nullptr;
2972 TrivialBB->eraseFromParent();
2973 }
2974
2975 // Delete the resume block if all its predecessors have been deleted, and we
2976 // haven't already deleted it above when deleting the landing pad blocks.
2977 if (BB && pred_begin(BB) == pred_end(BB)) {
2978 BB->eraseFromParent();
2979 }
2980
2981 return TrivialUnwindBlocks.size() != 0;
Duncan Sands29192d02011-09-05 12:57:57 +00002982}
2983
Andrew Kaylor50e4e862015-09-04 23:39:40 +00002984bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
2985 // If this is a trivial cleanup pad that executes no instructions, it can be
2986 // eliminated. If the cleanup pad continues to the caller, any predecessor
2987 // that is an EH pad will be updated to continue to the caller and any
2988 // predecessor that terminates with an invoke instruction will have its invoke
2989 // instruction converted to a call instruction. If the cleanup pad being
2990 // simplified does not continue to the caller, each predecessor will be
2991 // updated to continue to the unwind destination of the cleanup pad being
2992 // simplified.
2993 BasicBlock *BB = RI->getParent();
2994 Instruction *CPInst = dyn_cast<CleanupPadInst>(BB->getFirstNonPHI());
2995 if (!CPInst)
2996 // This isn't an empty cleanup.
2997 return false;
2998
2999 // Check that there are no other instructions except for debug intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003000 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003001 while (++I != E)
3002 if (!isa<DbgInfoIntrinsic>(I))
3003 return false;
3004
3005 // If the cleanup return we are simplifying unwinds to the caller, this
3006 // will set UnwindDest to nullptr.
3007 BasicBlock *UnwindDest = RI->getUnwindDest();
3008
3009 // We're about to remove BB from the control flow. Before we do, sink any
3010 // PHINodes into the unwind destination. Doing this before changing the
3011 // control flow avoids some potentially slow checks, since we can currently
3012 // be certain that UnwindDest and BB have no common predecessors (since they
3013 // are both EH pads).
3014 if (UnwindDest) {
3015 // First, go through the PHI nodes in UnwindDest and update any nodes that
3016 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003017 for (BasicBlock::iterator I = UnwindDest->begin(),
3018 IE = UnwindDest->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003019 I != IE; ++I) {
3020 PHINode *DestPN = cast<PHINode>(I);
3021
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003022 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003023 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003024 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003025 // This PHI node has an incoming value that corresponds to a control
3026 // path through the cleanup pad we are removing. If the incoming
3027 // value is in the cleanup pad, it must be a PHINode (because we
3028 // verified above that the block is otherwise empty). Otherwise, the
3029 // value is either a constant or a value that dominates the cleanup
3030 // pad being removed.
3031 //
3032 // Because BB and UnwindDest are both EH pads, all of their
3033 // predecessors must unwind to these blocks, and since no instruction
3034 // can have multiple unwind destinations, there will be no overlap in
3035 // incoming blocks between SrcPN and DestPN.
3036 Value *SrcVal = DestPN->getIncomingValue(Idx);
3037 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3038
3039 // Remove the entry for the block we are deleting.
3040 DestPN->removeIncomingValue(Idx, false);
3041
3042 if (SrcPN && SrcPN->getParent() == BB) {
3043 // If the incoming value was a PHI node in the cleanup pad we are
3044 // removing, we need to merge that PHI node's incoming values into
3045 // DestPN.
3046 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
3047 SrcIdx != SrcE; ++SrcIdx) {
3048 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3049 SrcPN->getIncomingBlock(SrcIdx));
3050 }
3051 } else {
3052 // Otherwise, the incoming value came from above BB and
3053 // so we can just reuse it. We must associate all of BB's
3054 // predecessors with this value.
3055 for (auto *pred : predecessors(BB)) {
3056 DestPN->addIncoming(SrcVal, pred);
3057 }
3058 }
3059 }
3060
3061 // Sink any remaining PHI nodes directly into UnwindDest.
3062 Instruction *InsertPt = UnwindDest->getFirstNonPHI();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003063 for (BasicBlock::iterator I = BB->begin(),
3064 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003065 I != IE;) {
3066 // The iterator must be incremented here because the instructions are
3067 // being moved to another block.
3068 PHINode *PN = cast<PHINode>(I++);
3069 if (PN->use_empty())
3070 // If the PHI node has no uses, just leave it. It will be erased
3071 // when we erase BB below.
3072 continue;
3073
3074 // Otherwise, sink this PHI node into UnwindDest.
3075 // Any predecessors to UnwindDest which are not already represented
3076 // must be back edges which inherit the value from the path through
3077 // BB. In this case, the PHI value must reference itself.
3078 for (auto *pred : predecessors(UnwindDest))
3079 if (pred != BB)
3080 PN->addIncoming(PN, pred);
3081 PN->moveBefore(InsertPt);
3082 }
3083 }
3084
3085 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3086 // The iterator must be updated here because we are removing this pred.
3087 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003088 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003089 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003090 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003091 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003092 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003093 }
3094 }
3095
3096 // The cleanup pad is now unreachable. Zap it.
3097 BB->eraseFromParent();
3098 return true;
3099}
3100
Devang Pateldd14e0f2011-05-18 21:33:11 +00003101bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003102 BasicBlock *BB = RI->getParent();
3103 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003104
Chris Lattner25c3af32010-12-13 06:25:44 +00003105 // Find predecessors that end with branches.
3106 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3107 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003108 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3109 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003110 TerminatorInst *PTI = P->getTerminator();
3111 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3112 if (BI->isUnconditional())
3113 UncondBranchPreds.push_back(P);
3114 else
3115 CondBranchPreds.push_back(BI);
3116 }
3117 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003118
Chris Lattner25c3af32010-12-13 06:25:44 +00003119 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00003120 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003121 while (!UncondBranchPreds.empty()) {
3122 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3123 DEBUG(dbgs() << "FOLDING: " << *BB
3124 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00003125 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00003126 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003127
Chris Lattner25c3af32010-12-13 06:25:44 +00003128 // If we eliminated all predecessors of the block, delete the block now.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003129 if (pred_empty(BB))
Chris Lattner25c3af32010-12-13 06:25:44 +00003130 // We know there are no successors, so just nuke the block.
3131 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003132
Chris Lattner25c3af32010-12-13 06:25:44 +00003133 return true;
3134 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003135
Chris Lattner25c3af32010-12-13 06:25:44 +00003136 // Check out all of the conditional branches going to this return
3137 // instruction. If any of them just select between returns, change the
3138 // branch itself into a select/return pair.
3139 while (!CondBranchPreds.empty()) {
3140 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003141
Chris Lattner25c3af32010-12-13 06:25:44 +00003142 // Check to see if the non-BB successor is also a return block.
3143 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3144 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003145 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003146 return true;
3147 }
3148 return false;
3149}
3150
Chris Lattner25c3af32010-12-13 06:25:44 +00003151bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3152 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003153
Chris Lattner25c3af32010-12-13 06:25:44 +00003154 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003155
Chris Lattner25c3af32010-12-13 06:25:44 +00003156 // If there are any instructions immediately before the unreachable that can
3157 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003158 while (UI->getIterator() != BB->begin()) {
3159 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00003160 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003161 // Do not delete instructions that can have side effects which might cause
3162 // the unreachable to not be reachable; specifically, calls and volatile
3163 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003164 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003165
3166 if (BBI->mayHaveSideEffects()) {
3167 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3168 if (SI->isVolatile())
3169 break;
3170 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3171 if (LI->isVolatile())
3172 break;
3173 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3174 if (RMWI->isVolatile())
3175 break;
3176 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3177 if (CXI->isVolatile())
3178 break;
3179 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3180 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003181 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003182 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003183 // Note that deleting LandingPad's here is in fact okay, although it
3184 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3185 // all the predecessors of this block will be the unwind edges of Invokes,
3186 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003187 }
3188
Eli Friedmanaac35b32011-03-09 00:48:33 +00003189 // Delete this instruction (any uses are guaranteed to be dead)
3190 if (!BBI->use_empty())
3191 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003192 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003193 Changed = true;
3194 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003195
Chris Lattner25c3af32010-12-13 06:25:44 +00003196 // If the unreachable instruction is the first in the block, take a gander
3197 // at all of the predecessors of this instruction, and simplify them.
3198 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003199
Chris Lattner25c3af32010-12-13 06:25:44 +00003200 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3201 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3202 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003203 IRBuilder<> Builder(TI);
Chris Lattner25c3af32010-12-13 06:25:44 +00003204 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3205 if (BI->isUnconditional()) {
3206 if (BI->getSuccessor(0) == BB) {
3207 new UnreachableInst(TI->getContext(), TI);
3208 TI->eraseFromParent();
3209 Changed = true;
3210 }
3211 } else {
3212 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003213 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003214 EraseTerminatorInstAndDCECond(BI);
3215 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003216 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003217 EraseTerminatorInstAndDCECond(BI);
3218 Changed = true;
3219 }
3220 }
3221 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003222 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003223 i != e; ++i)
3224 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003225 BB->removePredecessor(SI->getParent());
3226 SI->removeCase(i);
3227 --i; --e;
3228 Changed = true;
3229 }
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003230 } else if ((isa<InvokeInst>(TI) &&
3231 cast<InvokeInst>(TI)->getUnwindDest() == BB) ||
3232 isa<CatchEndPadInst>(TI) || isa<TerminatePadInst>(TI)) {
3233 removeUnwindEdge(TI->getParent());
3234 Changed = true;
3235 } else if (isa<CleanupReturnInst>(TI) || isa<CleanupEndPadInst>(TI) ||
3236 isa<CatchReturnInst>(TI)) {
3237 new UnreachableInst(TI->getContext(), TI);
3238 TI->eraseFromParent();
3239 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00003240 }
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003241 // TODO: If TI is a CatchPadInst, then (BB must be its normal dest and)
3242 // we can eliminate it, redirecting its preds to its unwind successor,
3243 // or to the next outer handler if the removed catch is the last for its
3244 // catchendpad.
Chris Lattner25c3af32010-12-13 06:25:44 +00003245 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003246
Chris Lattner25c3af32010-12-13 06:25:44 +00003247 // If this block is now dead, remove it.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003248 if (pred_empty(BB) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00003249 BB != &BB->getParent()->getEntryBlock()) {
3250 // We know there are no successors, so just nuke the block.
3251 BB->eraseFromParent();
3252 return true;
3253 }
3254
3255 return Changed;
3256}
3257
Hans Wennborg68000082015-01-26 19:52:32 +00003258static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3259 assert(Cases.size() >= 1);
3260
3261 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3262 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3263 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3264 return false;
3265 }
3266 return true;
3267}
3268
3269/// Turn a switch with two reachable destinations into an integer range
3270/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003271static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003272 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003273
Hans Wennborg68000082015-01-26 19:52:32 +00003274 bool HasDefault =
3275 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003276
Hans Wennborg68000082015-01-26 19:52:32 +00003277 // Partition the cases into two sets with different destinations.
3278 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3279 BasicBlock *DestB = nullptr;
3280 SmallVector <ConstantInt *, 16> CasesA;
3281 SmallVector <ConstantInt *, 16> CasesB;
3282
3283 for (SwitchInst::CaseIt I : SI->cases()) {
3284 BasicBlock *Dest = I.getCaseSuccessor();
3285 if (!DestA) DestA = Dest;
3286 if (Dest == DestA) {
3287 CasesA.push_back(I.getCaseValue());
3288 continue;
3289 }
3290 if (!DestB) DestB = Dest;
3291 if (Dest == DestB) {
3292 CasesB.push_back(I.getCaseValue());
3293 continue;
3294 }
3295 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003296 }
3297
Hans Wennborg68000082015-01-26 19:52:32 +00003298 assert(DestA && DestB && "Single-destination switch should have been folded.");
3299 assert(DestA != DestB);
3300 assert(DestB != SI->getDefaultDest());
3301 assert(!CasesB.empty() && "There must be non-default cases.");
3302 assert(!CasesA.empty() || HasDefault);
3303
3304 // Figure out if one of the sets of cases form a contiguous range.
3305 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3306 BasicBlock *ContiguousDest = nullptr;
3307 BasicBlock *OtherDest = nullptr;
3308 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3309 ContiguousCases = &CasesA;
3310 ContiguousDest = DestA;
3311 OtherDest = DestB;
3312 } else if (CasesAreContiguous(CasesB)) {
3313 ContiguousCases = &CasesB;
3314 ContiguousDest = DestB;
3315 OtherDest = DestA;
3316 } else
3317 return false;
3318
3319 // Start building the compare and branch.
3320
3321 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3322 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003323
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003324 Value *Sub = SI->getCondition();
3325 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00003326 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3327
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003328 Value *Cmp;
3329 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00003330 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003331 Cmp = ConstantInt::getTrue(SI->getContext());
3332 else
3333 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00003334 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003335
Manman Ren56575552012-09-18 00:47:33 +00003336 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00003337 if (HasBranchWeights(SI)) {
3338 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00003339 GetBranchWeights(SI, Weights);
3340 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00003341 uint64_t TrueWeight = 0;
3342 uint64_t FalseWeight = 0;
3343 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3344 if (SI->getSuccessor(I) == ContiguousDest)
3345 TrueWeight += Weights[I];
3346 else
3347 FalseWeight += Weights[I];
3348 }
3349 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3350 TrueWeight /= 2;
3351 FalseWeight /= 2;
3352 }
Manman Ren56575552012-09-18 00:47:33 +00003353 NewBI->setMetadata(LLVMContext::MD_prof,
Hans Wennborg68000082015-01-26 19:52:32 +00003354 MDBuilder(SI->getContext()).createBranchWeights(
3355 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00003356 }
3357 }
3358
Hans Wennborg68000082015-01-26 19:52:32 +00003359 // Prune obsolete incoming values off the successors' PHI nodes.
3360 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3361 unsigned PreviousEdges = ContiguousCases->size();
3362 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3363 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003364 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3365 }
Hans Wennborg68000082015-01-26 19:52:32 +00003366 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3367 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3368 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3369 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3370 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3371 }
3372
3373 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003374 SI->eraseFromParent();
3375
3376 return true;
3377}
Chris Lattner25c3af32010-12-13 06:25:44 +00003378
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003379/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003380/// and use it to remove dead cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003381static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3382 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003383 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003384 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003385 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003386 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003387
3388 // Gather dead cases.
3389 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003390 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003391 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3392 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3393 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003394 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003395 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003396 }
3397 }
3398
Philip Reames98a2dab2015-08-26 23:56:46 +00003399 // If we can prove that the cases must cover all possible values, the
Philip Reames05370132015-09-10 17:44:47 +00003400 // default destination becomes dead and we can remove it. If we know some
3401 // of the bits in the value, we can use that to more precisely compute the
3402 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00003403 bool HasDefault =
3404 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Philip Reames05370132015-09-10 17:44:47 +00003405 const unsigned NumUnknownBits = Bits -
3406 (KnownZero.Or(KnownOne)).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00003407 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00003408 if (HasDefault && DeadCases.empty() &&
3409 NumUnknownBits < 64 /* avoid overflow */ &&
3410 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00003411 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
3412 BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(),
3413 SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003414 SI->setDefaultDest(&*NewDefault);
3415 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00003416 auto *OldTI = NewDefault->getTerminator();
3417 new UnreachableInst(SI->getContext(), OldTI);
3418 EraseTerminatorInstAndDCECond(OldTI);
3419 return true;
3420 }
3421
Manman Ren56575552012-09-18 00:47:33 +00003422 SmallVector<uint64_t, 8> Weights;
3423 bool HasWeight = HasBranchWeights(SI);
3424 if (HasWeight) {
3425 GetBranchWeights(SI, Weights);
3426 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3427 }
3428
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003429 // Remove dead cases from the switch.
3430 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003431 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003432 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003433 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003434 if (HasWeight) {
3435 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3436 Weights.pop_back();
3437 }
3438
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003439 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003440 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003441 SI->removeCase(Case);
3442 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003443 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003444 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3445 SI->setMetadata(LLVMContext::MD_prof,
3446 MDBuilder(SI->getParent()->getContext()).
3447 createBranchWeights(MDWeights));
3448 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003449
3450 return !DeadCases.empty();
3451}
3452
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003453/// If BB would be eligible for simplification by
3454/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003455/// by an unconditional branch), look at the phi node for BB in the successor
3456/// block and see if the incoming value is equal to CaseValue. If so, return
3457/// the phi node, and set PhiIndex to BB's index in the phi node.
3458static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3459 BasicBlock *BB,
3460 int *PhiIndex) {
3461 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003462 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003463 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003464 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003465
3466 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3467 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003468 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003469
3470 BasicBlock *Succ = Branch->getSuccessor(0);
3471
3472 BasicBlock::iterator I = Succ->begin();
3473 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3474 int Idx = PHI->getBasicBlockIndex(BB);
3475 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3476
3477 Value *InValue = PHI->getIncomingValue(Idx);
3478 if (InValue != CaseValue) continue;
3479
3480 *PhiIndex = Idx;
3481 return PHI;
3482 }
3483
Craig Topperf40110f2014-04-25 05:29:35 +00003484 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003485}
3486
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003487/// Try to forward the condition of a switch instruction to a phi node
3488/// dominated by the switch, if that would mean that some of the destination
3489/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003490/// Returns true if a change is made.
3491static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3492 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3493 ForwardingNodesMap ForwardingNodes;
3494
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003495 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003496 ConstantInt *CaseValue = I.getCaseValue();
3497 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003498
3499 int PhiIndex;
3500 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3501 &PhiIndex);
3502 if (!PHI) continue;
3503
3504 ForwardingNodes[PHI].push_back(PhiIndex);
3505 }
3506
3507 bool Changed = false;
3508
3509 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3510 E = ForwardingNodes.end(); I != E; ++I) {
3511 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003512 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003513
3514 if (Indexes.size() < 2) continue;
3515
3516 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3517 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3518 Changed = true;
3519 }
3520
3521 return Changed;
3522}
3523
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003524/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003525/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003526static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003527 if (C->isThreadDependent())
3528 return false;
3529 if (C->isDLLImportDependent())
3530 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003531
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003532 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3533 return CE->isGEPWithNoNotionalOverIndexing();
3534
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003535 return isa<ConstantFP>(C) ||
3536 isa<ConstantInt>(C) ||
3537 isa<ConstantPointerNull>(C) ||
3538 isa<GlobalValue>(C) ||
3539 isa<UndefValue>(C);
3540}
3541
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003542/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003543/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003544static Constant *LookupConstant(Value *V,
3545 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3546 if (Constant *C = dyn_cast<Constant>(V))
3547 return C;
3548 return ConstantPool.lookup(V);
3549}
3550
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003551/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003552/// simple instructions such as binary operations where both operands are
3553/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003554/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003555static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003556ConstantFold(Instruction *I, const DataLayout &DL,
3557 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003558 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003559 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3560 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003561 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003562 if (A->isAllOnesValue())
3563 return LookupConstant(Select->getTrueValue(), ConstantPool);
3564 if (A->isNullValue())
3565 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003566 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003567 }
3568
Benjamin Kramer7c302602013-11-12 12:24:36 +00003569 SmallVector<Constant *, 4> COps;
3570 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3571 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3572 COps.push_back(A);
3573 else
Craig Topperf40110f2014-04-25 05:29:35 +00003574 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003575 }
3576
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003577 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00003578 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3579 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003580 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00003581
3582 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003583}
3584
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003585/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003586/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003587/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003588/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003589static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003590GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00003591 BasicBlock **CommonDest,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003592 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
3593 const DataLayout &DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003594 // The block from which we enter the common destination.
3595 BasicBlock *Pred = SI->getParent();
3596
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003597 // If CaseDest is empty except for some side-effect free instructions through
3598 // which we can constant-propagate the CaseVal, continue to its successor.
3599 SmallDenseMap<Value*, Constant*> ConstantPool;
3600 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3601 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3602 ++I) {
3603 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3604 // If the terminator is a simple branch, continue to the next block.
3605 if (T->getNumSuccessors() != 1)
3606 return false;
3607 Pred = CaseDest;
3608 CaseDest = T->getSuccessor(0);
3609 } else if (isa<DbgInfoIntrinsic>(I)) {
3610 // Skip debug intrinsic.
3611 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003612 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003613 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00003614
3615 // If the instruction has uses outside this block or a phi node slot for
3616 // the block, it is not safe to bypass the instruction since it would then
3617 // no longer dominate all its uses.
3618 for (auto &Use : I->uses()) {
3619 User *User = Use.getUser();
3620 if (Instruction *I = dyn_cast<Instruction>(User))
3621 if (I->getParent() == CaseDest)
3622 continue;
3623 if (PHINode *Phi = dyn_cast<PHINode>(User))
3624 if (Phi->getIncomingBlock(Use) == CaseDest)
3625 continue;
3626 return false;
3627 }
3628
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003629 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003630 } else {
3631 break;
3632 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003633 }
3634
3635 // If we did not have a CommonDest before, use the current one.
3636 if (!*CommonDest)
3637 *CommonDest = CaseDest;
3638 // If the destination isn't the common one, abort.
3639 if (CaseDest != *CommonDest)
3640 return false;
3641
3642 // Get the values for this case from phi nodes in the destination block.
3643 BasicBlock::iterator I = (*CommonDest)->begin();
3644 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3645 int Idx = PHI->getBasicBlockIndex(Pred);
3646 if (Idx == -1)
3647 continue;
3648
Hans Wennborg09acdb92012-10-31 15:14:39 +00003649 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3650 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003651 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003652 return false;
3653
3654 // Be conservative about which kinds of constants we support.
3655 if (!ValidLookupTableConstant(ConstVal))
3656 return false;
3657
3658 Res.push_back(std::make_pair(PHI, ConstVal));
3659 }
3660
Hans Wennborgac114a32014-01-12 00:44:41 +00003661 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003662}
3663
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003664// Helper function used to add CaseVal to the list of cases that generate
3665// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003666static void MapCaseToResult(ConstantInt *CaseVal,
3667 SwitchCaseResultVectorTy &UniqueResults,
3668 Constant *Result) {
3669 for (auto &I : UniqueResults) {
3670 if (I.first == Result) {
3671 I.second.push_back(CaseVal);
3672 return;
3673 }
3674 }
3675 UniqueResults.push_back(std::make_pair(Result,
3676 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3677}
3678
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003679// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003680// results for the PHI node of the common destination block for a switch
3681// instruction. Returns false if multiple PHI nodes have been found or if
3682// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003683static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
3684 BasicBlock *&CommonDest,
3685 SwitchCaseResultVectorTy &UniqueResults,
3686 Constant *&DefaultResult,
3687 const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003688 for (auto &I : SI->cases()) {
3689 ConstantInt *CaseVal = I.getCaseValue();
3690
3691 // Resulting value at phi nodes for this case value.
3692 SwitchCaseResultsTy Results;
3693 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3694 DL))
3695 return false;
3696
3697 // Only one value per case is permitted
3698 if (Results.size() > 1)
3699 return false;
3700 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3701
3702 // Check the PHI consistency.
3703 if (!PHI)
3704 PHI = Results[0].first;
3705 else if (PHI != Results[0].first)
3706 return false;
3707 }
3708 // Find the default result value.
3709 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3710 BasicBlock *DefaultDest = SI->getDefaultDest();
3711 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3712 DL);
3713 // If the default value is not found abort unless the default destination
3714 // is unreachable.
3715 DefaultResult =
3716 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3717 if ((!DefaultResult &&
3718 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3719 return false;
3720
3721 return true;
3722}
3723
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003724// Helper function that checks if it is possible to transform a switch with only
3725// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003726// Example:
3727// switch (a) {
3728// case 10: %0 = icmp eq i32 %a, 10
3729// return 10; %1 = select i1 %0, i32 10, i32 4
3730// case 20: ----> %2 = icmp eq i32 %a, 20
3731// return 2; %3 = select i1 %2, i32 2, i32 %1
3732// default:
3733// return 4;
3734// }
3735static Value *
3736ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3737 Constant *DefaultResult, Value *Condition,
3738 IRBuilder<> &Builder) {
3739 assert(ResultVector.size() == 2 &&
3740 "We should have exactly two unique results at this point");
3741 // If we are selecting between only two cases transform into a simple
3742 // select or a two-way select if default is possible.
3743 if (ResultVector[0].second.size() == 1 &&
3744 ResultVector[1].second.size() == 1) {
3745 ConstantInt *const FirstCase = ResultVector[0].second[0];
3746 ConstantInt *const SecondCase = ResultVector[1].second[0];
3747
3748 bool DefaultCanTrigger = DefaultResult;
3749 Value *SelectValue = ResultVector[1].first;
3750 if (DefaultCanTrigger) {
3751 Value *const ValueCompare =
3752 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3753 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3754 DefaultResult, "switch.select");
3755 }
3756 Value *const ValueCompare =
3757 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3758 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3759 "switch.select");
3760 }
3761
3762 return nullptr;
3763}
3764
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003765// Helper function to cleanup a switch instruction that has been converted into
3766// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003767static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3768 Value *SelectValue,
3769 IRBuilder<> &Builder) {
3770 BasicBlock *SelectBB = SI->getParent();
3771 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3772 PHI->removeIncomingValue(SelectBB);
3773 PHI->addIncoming(SelectValue, SelectBB);
3774
3775 Builder.CreateBr(PHI->getParent());
3776
3777 // Remove the switch.
3778 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3779 BasicBlock *Succ = SI->getSuccessor(i);
3780
3781 if (Succ == PHI->getParent())
3782 continue;
3783 Succ->removePredecessor(SelectBB);
3784 }
3785 SI->eraseFromParent();
3786}
3787
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003788/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003789/// phi nodes in a common successor block with only two different
3790/// constant values, replace the switch with select.
3791static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003792 AssumptionCache *AC, const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003793 Value *const Cond = SI->getCondition();
3794 PHINode *PHI = nullptr;
3795 BasicBlock *CommonDest = nullptr;
3796 Constant *DefaultResult;
3797 SwitchCaseResultVectorTy UniqueResults;
3798 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003799 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
3800 DL))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003801 return false;
3802 // Selects choose between maximum two values.
3803 if (UniqueResults.size() != 2)
3804 return false;
3805 assert(PHI != nullptr && "PHI for value select not found");
3806
3807 Builder.SetInsertPoint(SI);
3808 Value *SelectValue = ConvertTwoCaseSwitch(
3809 UniqueResults,
3810 DefaultResult, Cond, Builder);
3811 if (SelectValue) {
3812 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3813 return true;
3814 }
3815 // The switch couldn't be converted into a select.
3816 return false;
3817}
3818
Hans Wennborg776d7122012-09-26 09:34:53 +00003819namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003820 /// This class represents a lookup table that can be used to replace a switch.
Hans Wennborg776d7122012-09-26 09:34:53 +00003821 class SwitchLookupTable {
3822 public:
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003823 /// Create a lookup table to use as a switch replacement with the contents
3824 /// of Values, using DefaultValue to fill any holes in the table.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003825 SwitchLookupTable(
3826 Module &M, uint64_t TableSize, ConstantInt *Offset,
3827 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
3828 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00003829
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003830 /// Build instructions with Builder to retrieve the value at
Hans Wennborg776d7122012-09-26 09:34:53 +00003831 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00003832 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00003833
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003834 /// Return true if a table with TableSize elements of
Hans Wennborg39583b82012-09-26 09:44:49 +00003835 /// type ElementType would fit in a target-legal register.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003836 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00003837 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003838
Hans Wennborg776d7122012-09-26 09:34:53 +00003839 private:
3840 // Depending on the contents of the table, it can be represented in
3841 // different ways.
3842 enum {
3843 // For tables where each element contains the same value, we just have to
3844 // store that single value and return it for each lookup.
3845 SingleValueKind,
3846
Erik Eckstein105374f2014-11-17 09:13:57 +00003847 // For tables where there is a linear relationship between table index
3848 // and values. We calculate the result with a simple multiplication
3849 // and addition instead of a table lookup.
3850 LinearMapKind,
3851
Hans Wennborg39583b82012-09-26 09:44:49 +00003852 // For small tables with integer elements, we can pack them into a bitmap
3853 // that fits into a target-legal register. Values are retrieved by
3854 // shift and mask operations.
3855 BitMapKind,
3856
Hans Wennborg776d7122012-09-26 09:34:53 +00003857 // The table is stored as an array of values. Values are retrieved by load
3858 // instructions from the table.
3859 ArrayKind
3860 } Kind;
3861
3862 // For SingleValueKind, this is the single value.
3863 Constant *SingleValue;
3864
Hans Wennborg39583b82012-09-26 09:44:49 +00003865 // For BitMapKind, this is the bitmap.
3866 ConstantInt *BitMap;
3867 IntegerType *BitMapElementTy;
3868
Erik Eckstein105374f2014-11-17 09:13:57 +00003869 // For LinearMapKind, these are the constants used to derive the value.
3870 ConstantInt *LinearOffset;
3871 ConstantInt *LinearMultiplier;
3872
Hans Wennborg776d7122012-09-26 09:34:53 +00003873 // For ArrayKind, this is the array.
3874 GlobalVariable *Array;
3875 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003876}
Hans Wennborg776d7122012-09-26 09:34:53 +00003877
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003878SwitchLookupTable::SwitchLookupTable(
3879 Module &M, uint64_t TableSize, ConstantInt *Offset,
3880 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
3881 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00003882 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00003883 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003884 assert(Values.size() && "Can't build lookup table without values!");
3885 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003886
3887 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00003888 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003889
Hans Wennborgac114a32014-01-12 00:44:41 +00003890 Type *ValueType = Values.begin()->second->getType();
3891
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003892 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00003893 SmallVector<Constant*, 64> TableContents(TableSize);
3894 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3895 ConstantInt *CaseVal = Values[I].first;
3896 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00003897 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003898
Hans Wennborg776d7122012-09-26 09:34:53 +00003899 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3900 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003901 TableContents[Idx] = CaseRes;
3902
Hans Wennborg776d7122012-09-26 09:34:53 +00003903 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003904 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003905 }
3906
3907 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00003908 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00003909 assert(DefaultValue &&
3910 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00003911 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00003912 for (uint64_t I = 0; I < TableSize; ++I) {
3913 if (!TableContents[I])
3914 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003915 }
3916
Hans Wennborg776d7122012-09-26 09:34:53 +00003917 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003918 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003919 }
3920
Hans Wennborg776d7122012-09-26 09:34:53 +00003921 // If each element in the table contains the same value, we only need to store
3922 // that single value.
3923 if (SingleValue) {
3924 Kind = SingleValueKind;
3925 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003926 }
3927
Erik Eckstein105374f2014-11-17 09:13:57 +00003928 // Check if we can derive the value with a linear transformation from the
3929 // table index.
3930 if (isa<IntegerType>(ValueType)) {
3931 bool LinearMappingPossible = true;
3932 APInt PrevVal;
3933 APInt DistToPrev;
3934 assert(TableSize >= 2 && "Should be a SingleValue table.");
3935 // Check if there is the same distance between two consecutive values.
3936 for (uint64_t I = 0; I < TableSize; ++I) {
3937 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3938 if (!ConstVal) {
3939 // This is an undef. We could deal with it, but undefs in lookup tables
3940 // are very seldom. It's probably not worth the additional complexity.
3941 LinearMappingPossible = false;
3942 break;
3943 }
3944 APInt Val = ConstVal->getValue();
3945 if (I != 0) {
3946 APInt Dist = Val - PrevVal;
3947 if (I == 1) {
3948 DistToPrev = Dist;
3949 } else if (Dist != DistToPrev) {
3950 LinearMappingPossible = false;
3951 break;
3952 }
3953 }
3954 PrevVal = Val;
3955 }
3956 if (LinearMappingPossible) {
3957 LinearOffset = cast<ConstantInt>(TableContents[0]);
3958 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3959 Kind = LinearMapKind;
3960 ++NumLinearMaps;
3961 return;
3962 }
3963 }
3964
Hans Wennborg39583b82012-09-26 09:44:49 +00003965 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003966 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00003967 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003968 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3969 for (uint64_t I = TableSize; I > 0; --I) {
3970 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00003971 // Insert values into the bitmap. Undef values are set to zero.
3972 if (!isa<UndefValue>(TableContents[I - 1])) {
3973 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3974 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3975 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003976 }
3977 BitMap = ConstantInt::get(M.getContext(), TableInt);
3978 BitMapElementTy = IT;
3979 Kind = BitMapKind;
3980 ++NumBitMaps;
3981 return;
3982 }
3983
Hans Wennborg776d7122012-09-26 09:34:53 +00003984 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00003985 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003986 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3987
Hans Wennborg776d7122012-09-26 09:34:53 +00003988 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3989 GlobalVariable::PrivateLinkage,
3990 Initializer,
3991 "switch.table");
3992 Array->setUnnamedAddr(true);
3993 Kind = ArrayKind;
3994}
3995
Manman Ren4d189fb2014-07-24 21:13:20 +00003996Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00003997 switch (Kind) {
3998 case SingleValueKind:
3999 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00004000 case LinearMapKind: {
4001 // Derive the result value from the input value.
4002 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4003 false, "switch.idx.cast");
4004 if (!LinearMultiplier->isOne())
4005 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4006 if (!LinearOffset->isZero())
4007 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4008 return Result;
4009 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004010 case BitMapKind: {
4011 // Type of the bitmap (e.g. i59).
4012 IntegerType *MapTy = BitMap->getType();
4013
4014 // Cast Index to the same type as the bitmap.
4015 // Note: The Index is <= the number of elements in the table, so
4016 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00004017 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004018
4019 // Multiply the shift amount by the element width.
4020 ShiftAmt = Builder.CreateMul(ShiftAmt,
4021 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4022 "switch.shiftamt");
4023
4024 // Shift down.
4025 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
4026 "switch.downshift");
4027 // Mask off.
4028 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
4029 "switch.masked");
4030 }
Hans Wennborg776d7122012-09-26 09:34:53 +00004031 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00004032 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00004033 IntegerType *IT = cast<IntegerType>(Index->getType());
4034 uint64_t TableSize = Array->getInitializer()->getType()
4035 ->getArrayNumElements();
4036 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4037 Index = Builder.CreateZExt(Index,
4038 IntegerType::get(IT->getContext(),
4039 IT->getBitWidth() + 1),
4040 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00004041
Hans Wennborg776d7122012-09-26 09:34:53 +00004042 Value *GEPIndices[] = { Builder.getInt32(0), Index };
David Blaikieaa41cd52015-04-03 21:33:42 +00004043 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4044 GEPIndices, "switch.gep");
Hans Wennborg776d7122012-09-26 09:34:53 +00004045 return Builder.CreateLoad(GEP, "switch.load");
4046 }
4047 }
4048 llvm_unreachable("Unknown lookup table kind!");
4049}
4050
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004051bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00004052 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004053 Type *ElementType) {
4054 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004055 if (!IT)
4056 return false;
4057 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4058 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004059
4060 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4061 if (TableSize >= UINT_MAX/IT->getBitWidth())
4062 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004063 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00004064}
4065
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004066/// Determine whether a lookup table should be built for this switch, based on
4067/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004068static bool
4069ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4070 const TargetTransformInfo &TTI, const DataLayout &DL,
4071 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004072 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4073 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00004074
Chandler Carruth77d433d2012-11-30 09:26:25 +00004075 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00004076 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00004077 for (const auto &I : ResultTypes) {
4078 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004079
4080 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004081 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004082
4083 // Saturate this flag to false.
4084 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004085 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004086
4087 // If both flags saturate, we're done. NOTE: This *only* works with
4088 // saturating flags, and all flags have to saturate first due to the
4089 // non-deterministic behavior of iterating over a dense map.
4090 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00004091 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00004092 }
Evan Cheng65df8082012-11-30 02:02:42 +00004093
Chandler Carruth77d433d2012-11-30 09:26:25 +00004094 // If each table would fit in a register, we should build it anyway.
4095 if (AllTablesFitInRegister)
4096 return true;
4097
4098 // Don't build a table that doesn't fit in-register if it has illegal types.
4099 if (HasIllegalType)
4100 return false;
4101
4102 // The table density should be at least 40%. This is the same criterion as for
4103 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4104 // FIXME: Find the best cut-off.
4105 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004106}
4107
Erik Eckstein0d86c762014-11-27 15:13:14 +00004108/// Try to reuse the switch table index compare. Following pattern:
4109/// \code
4110/// if (idx < tablesize)
4111/// r = table[idx]; // table does not contain default_value
4112/// else
4113/// r = default_value;
4114/// if (r != default_value)
4115/// ...
4116/// \endcode
4117/// Is optimized to:
4118/// \code
4119/// cond = idx < tablesize;
4120/// if (cond)
4121/// r = table[idx];
4122/// else
4123/// r = default_value;
4124/// if (cond)
4125/// ...
4126/// \endcode
4127/// Jump threading will then eliminate the second if(cond).
4128static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4129 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4130 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4131
4132 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4133 if (!CmpInst)
4134 return;
4135
4136 // We require that the compare is in the same block as the phi so that jump
4137 // threading can do its work afterwards.
4138 if (CmpInst->getParent() != PhiBlock)
4139 return;
4140
4141 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4142 if (!CmpOp1)
4143 return;
4144
4145 Value *RangeCmp = RangeCheckBranch->getCondition();
4146 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4147 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4148
4149 // Check if the compare with the default value is constant true or false.
4150 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4151 DefaultValue, CmpOp1, true);
4152 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4153 return;
4154
4155 // Check if the compare with the case values is distinct from the default
4156 // compare result.
4157 for (auto ValuePair : Values) {
4158 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4159 ValuePair.second, CmpOp1, true);
4160 if (!CaseConst || CaseConst == DefaultConst)
4161 return;
4162 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4163 "Expect true or false as compare result.");
4164 }
4165
4166 // Check if the branch instruction dominates the phi node. It's a simple
4167 // dominance check, but sufficient for our needs.
4168 // Although this check is invariant in the calling loops, it's better to do it
4169 // at this late stage. Practically we do it at most once for a switch.
4170 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4171 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4172 BasicBlock *Pred = *PI;
4173 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4174 return;
4175 }
4176
4177 if (DefaultConst == FalseConst) {
4178 // The compare yields the same result. We can replace it.
4179 CmpInst->replaceAllUsesWith(RangeCmp);
4180 ++NumTableCmpReuses;
4181 } else {
4182 // The compare yields the same result, just inverted. We can replace it.
4183 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4184 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4185 RangeCheckBranch);
4186 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4187 ++NumTableCmpReuses;
4188 }
4189}
4190
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004191/// If the switch is only used to initialize one or more phi nodes in a common
4192/// successor block with different constant values, replace the switch with
4193/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004194static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4195 const DataLayout &DL,
4196 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004197 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004198
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004199 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004200 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004201 return false;
4202
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004203 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4204 // split off a dense part and build a lookup table for that.
4205
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004206 // FIXME: This creates arrays of GEPs to constant strings, which means each
4207 // GEP needs a runtime relocation in PIC code. We should just build one big
4208 // string and lookup indices into that.
4209
Hans Wennborg4744ac12014-01-15 05:00:27 +00004210 // Ignore switches with less than three cases. Lookup tables will not make them
4211 // faster, so we don't analyze them.
4212 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004213 return false;
4214
4215 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00004216 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004217 assert(SI->case_begin() != SI->case_end());
4218 SwitchInst::CaseIt CI = SI->case_begin();
4219 ConstantInt *MinCaseVal = CI.getCaseValue();
4220 ConstantInt *MaxCaseVal = CI.getCaseValue();
4221
Craig Topperf40110f2014-04-25 05:29:35 +00004222 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004223 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004224 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4225 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4226 SmallDenseMap<PHINode*, Type*> ResultTypes;
4227 SmallVector<PHINode*, 4> PHIs;
4228
4229 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4230 ConstantInt *CaseVal = CI.getCaseValue();
4231 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4232 MinCaseVal = CaseVal;
4233 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4234 MaxCaseVal = CaseVal;
4235
4236 // Resulting value at phi nodes for this case value.
4237 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4238 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004239 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004240 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004241 return false;
4242
4243 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004244 for (const auto &I : Results) {
4245 PHINode *PHI = I.first;
4246 Constant *Value = I.second;
4247 if (!ResultLists.count(PHI))
4248 PHIs.push_back(PHI);
4249 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004250 }
4251 }
4252
Hans Wennborgac114a32014-01-12 00:44:41 +00004253 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004254 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004255 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4256 }
4257
4258 uint64_t NumResults = ResultLists[PHIs[0]].size();
4259 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4260 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4261 bool TableHasHoles = (NumResults < TableSize);
4262
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004263 // If the table has holes, we need a constant result for the default case
4264 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004265 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00004266 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004267 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00004268
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004269 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4270 if (NeedMask) {
4271 // As an extra penalty for the validity test we require more cases.
4272 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4273 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004274 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004275 return false;
4276 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004277
Hans Wennborga6a11a92014-11-18 02:37:11 +00004278 for (const auto &I : DefaultResultsList) {
4279 PHINode *PHI = I.first;
4280 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004281 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004282 }
4283
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004284 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004285 return false;
4286
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004287 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004288 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004289 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4290 "switch.lookup",
4291 CommonDest->getParent(),
4292 CommonDest);
4293
Michael Gottesmanc024f322013-10-20 07:04:37 +00004294 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004295 Builder.SetInsertPoint(SI);
4296 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4297 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004298
4299 // Compute the maximum table size representable by the integer type we are
4300 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004301 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004302 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004303 assert(MaxTableSize >= TableSize &&
4304 "It is impossible for a switch to have more entries than the max "
4305 "representable value of its input integer type's size.");
4306
Hans Wennborgb64cb272015-01-26 19:52:34 +00004307 // If the default destination is unreachable, or if the lookup table covers
4308 // all values of the conditional variable, branch directly to the lookup table
4309 // BB. Otherwise, check that the condition is within the case range.
4310 const bool DefaultIsReachable =
4311 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4312 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004313 BranchInst *RangeCheckBranch = nullptr;
4314
Hans Wennborgb64cb272015-01-26 19:52:34 +00004315 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00004316 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00004317 // Note: We call removeProdecessor later since we need to be able to get the
4318 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00004319 } else {
4320 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004321 MinCaseVal->getType(), TableSize));
Erik Eckstein0d86c762014-11-27 15:13:14 +00004322 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00004323 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004324
4325 // Populate the BB that does the lookups.
4326 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004327
4328 if (NeedMask) {
4329 // Before doing the lookup we do the hole check.
4330 // The LookupBB is therefore re-purposed to do the hole check
4331 // and we create a new LookupBB.
4332 BasicBlock *MaskBB = LookupBB;
4333 MaskBB->setName("switch.hole_check");
4334 LookupBB = BasicBlock::Create(Mod.getContext(),
4335 "switch.lookup",
4336 CommonDest->getParent(),
4337 CommonDest);
4338
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004339 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4340 // unnecessary illegal types.
4341 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4342 APInt MaskInt(TableSizePowOf2, 0);
4343 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004344 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004345 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4346 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4347 uint64_t Idx = (ResultList[I].first->getValue() -
4348 MinCaseVal->getValue()).getLimitedValue();
4349 MaskInt |= One << Idx;
4350 }
4351 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4352
4353 // Get the TableIndex'th bit of the bitmask.
4354 // If this bit is 0 (meaning hole) jump to the default destination,
4355 // else continue with table lookup.
4356 IntegerType *MapTy = TableMask->getType();
4357 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4358 "switch.maskindex");
4359 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4360 "switch.shifted");
4361 Value *LoBit = Builder.CreateTrunc(Shifted,
4362 Type::getInt1Ty(Mod.getContext()),
4363 "switch.lobit");
4364 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4365
4366 Builder.SetInsertPoint(LookupBB);
4367 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4368 }
4369
Hans Wennborg86ac6302015-04-24 20:57:56 +00004370 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4371 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4372 // do not delete PHINodes here.
4373 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4374 /*DontDeleteUselessPHIs=*/true);
4375 }
4376
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004377 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004378 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4379 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004380 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004381
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004382 // If using a bitmask, use any value to fill the lookup table holes.
4383 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004384 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004385
Manman Ren4d189fb2014-07-24 21:13:20 +00004386 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004387
Hans Wennborgf744fa92012-09-19 14:24:21 +00004388 // If the result is used to return immediately from the function, we want to
4389 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004390 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4391 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004392 Builder.CreateRet(Result);
4393 ReturnedEarly = true;
4394 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004395 }
4396
Erik Eckstein0d86c762014-11-27 15:13:14 +00004397 // Do a small peephole optimization: re-use the switch table compare if
4398 // possible.
4399 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4400 BasicBlock *PhiBlock = PHI->getParent();
4401 // Search for compare instructions which use the phi.
4402 for (auto *User : PHI->users()) {
4403 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4404 }
4405 }
4406
Hans Wennborgf744fa92012-09-19 14:24:21 +00004407 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004408 }
4409
4410 if (!ReturnedEarly)
4411 Builder.CreateBr(CommonDest);
4412
4413 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004414 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004415 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004416
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004417 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004418 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004419 Succ->removePredecessor(SI->getParent());
4420 }
4421 SI->eraseFromParent();
4422
4423 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004424 if (NeedMask)
4425 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004426 return true;
4427}
4428
Devang Patela7ec47d2011-05-18 20:35:38 +00004429bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004430 BasicBlock *BB = SI->getParent();
4431
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004432 if (isValueEqualityComparison(SI)) {
4433 // If we only have one predecessor, and if it is a branch on this value,
4434 // see if that predecessor totally determines the outcome of this switch.
4435 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4436 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004437 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004438
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004439 Value *Cond = SI->getCondition();
4440 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4441 if (SimplifySwitchOnSelect(SI, Select))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004442 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004443
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004444 // If the block only contains the switch, see if we can fold the block
4445 // away into any preds.
4446 BasicBlock::iterator BBI = BB->begin();
4447 // Ignore dbg intrinsics.
4448 while (isa<DbgInfoIntrinsic>(BBI))
4449 ++BBI;
4450 if (SI == &*BBI)
4451 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004452 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004453 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004454
4455 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004456 if (TurnSwitchRangeIntoICmp(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004457 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004458
4459 // Remove unreachable cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004460 if (EliminateDeadSwitchCases(SI, AC, DL))
4461 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004462
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004463 if (SwitchToSelect(SI, Builder, AC, DL))
4464 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004465
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004466 if (ForwardSwitchConditionToPHI(SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004467 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004468
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004469 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4470 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004471
Chris Lattner25c3af32010-12-13 06:25:44 +00004472 return false;
4473}
4474
4475bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4476 BasicBlock *BB = IBI->getParent();
4477 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004478
Chris Lattner25c3af32010-12-13 06:25:44 +00004479 // Eliminate redundant destinations.
4480 SmallPtrSet<Value *, 8> Succs;
4481 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4482 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004483 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004484 Dest->removePredecessor(BB);
4485 IBI->removeDestination(i);
4486 --i; --e;
4487 Changed = true;
4488 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004489 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004490
4491 if (IBI->getNumDestinations() == 0) {
4492 // If the indirectbr has no successors, change it to unreachable.
4493 new UnreachableInst(IBI->getContext(), IBI);
4494 EraseTerminatorInstAndDCECond(IBI);
4495 return true;
4496 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004497
Chris Lattner25c3af32010-12-13 06:25:44 +00004498 if (IBI->getNumDestinations() == 1) {
4499 // If the indirectbr has one successor, change it to a direct branch.
4500 BranchInst::Create(IBI->getDestination(0), IBI);
4501 EraseTerminatorInstAndDCECond(IBI);
4502 return true;
4503 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004504
Chris Lattner25c3af32010-12-13 06:25:44 +00004505 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4506 if (SimplifyIndirectBrOnSelect(IBI, SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004507 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004508 }
4509 return Changed;
4510}
4511
Philip Reames2b969d72015-03-24 22:28:45 +00004512/// Given an block with only a single landing pad and a unconditional branch
4513/// try to find another basic block which this one can be merged with. This
4514/// handles cases where we have multiple invokes with unique landing pads, but
4515/// a shared handler.
4516///
4517/// We specifically choose to not worry about merging non-empty blocks
4518/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4519/// practice, the optimizer produces empty landing pad blocks quite frequently
4520/// when dealing with exception dense code. (see: instcombine, gvn, if-else
4521/// sinking in this file)
4522///
4523/// This is primarily a code size optimization. We need to avoid performing
4524/// any transform which might inhibit optimization (such as our ability to
4525/// specialize a particular handler via tail commoning). We do this by not
4526/// merging any blocks which require us to introduce a phi. Since the same
4527/// values are flowing through both blocks, we don't loose any ability to
4528/// specialize. If anything, we make such specialization more likely.
4529///
4530/// TODO - This transformation could remove entries from a phi in the target
4531/// block when the inputs in the phi are the same for the two blocks being
4532/// merged. In some cases, this could result in removal of the PHI entirely.
4533static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
4534 BasicBlock *BB) {
4535 auto Succ = BB->getUniqueSuccessor();
4536 assert(Succ);
4537 // If there's a phi in the successor block, we'd likely have to introduce
4538 // a phi into the merged landing pad block.
4539 if (isa<PHINode>(*Succ->begin()))
4540 return false;
4541
4542 for (BasicBlock *OtherPred : predecessors(Succ)) {
4543 if (BB == OtherPred)
4544 continue;
4545 BasicBlock::iterator I = OtherPred->begin();
4546 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
4547 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
4548 continue;
4549 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4550 BranchInst *BI2 = dyn_cast<BranchInst>(I);
4551 if (!BI2 || !BI2->isIdenticalTo(BI))
4552 continue;
4553
4554 // We've found an identical block. Update our predeccessors to take that
4555 // path instead and make ourselves dead.
4556 SmallSet<BasicBlock *, 16> Preds;
4557 Preds.insert(pred_begin(BB), pred_end(BB));
4558 for (BasicBlock *Pred : Preds) {
4559 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
4560 assert(II->getNormalDest() != BB &&
4561 II->getUnwindDest() == BB && "unexpected successor");
4562 II->setUnwindDest(OtherPred);
4563 }
4564
4565 // The debug info in OtherPred doesn't cover the merged control flow that
4566 // used to go through BB. We need to delete it or update it.
4567 for (auto I = OtherPred->begin(), E = OtherPred->end();
4568 I != E;) {
4569 Instruction &Inst = *I; I++;
4570 if (isa<DbgInfoIntrinsic>(Inst))
4571 Inst.eraseFromParent();
4572 }
4573
4574 SmallSet<BasicBlock *, 16> Succs;
4575 Succs.insert(succ_begin(BB), succ_end(BB));
4576 for (BasicBlock *Succ : Succs) {
4577 Succ->removePredecessor(BB);
4578 }
4579
4580 IRBuilder<> Builder(BI);
4581 Builder.CreateUnreachable();
4582 BI->eraseFromParent();
4583 return true;
4584 }
4585 return false;
4586}
4587
Devang Patel767f6932011-05-18 18:28:48 +00004588bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00004589 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004590
Manman Ren93ab6492012-09-20 22:37:36 +00004591 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4592 return true;
4593
Chris Lattner25c3af32010-12-13 06:25:44 +00004594 // If the Terminator is the only non-phi instruction, simplify the block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004595 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00004596 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4597 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4598 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004599
Chris Lattner25c3af32010-12-13 06:25:44 +00004600 // If the only instruction in the block is a seteq/setne comparison
4601 // against a constant, try to simplify the block.
4602 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4603 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4604 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4605 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004606 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004607 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
4608 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00004609 return true;
4610 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004611
Philip Reames2b969d72015-03-24 22:28:45 +00004612 // See if we can merge an empty landing pad block with another which is
4613 // equivalent.
4614 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
4615 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4616 if (I->isTerminator() &&
4617 TryToMergeLandingPad(LPad, BI, BB))
4618 return true;
4619 }
4620
Manman Rend33f4ef2012-06-13 05:43:29 +00004621 // If this basic block is ONLY a compare and a branch, and if a predecessor
4622 // branches to us and our successor, fold the comparison into the
4623 // predecessor and use logical operations to update the incoming value
4624 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004625 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4626 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004627 return false;
4628}
4629
4630
Devang Patela7ec47d2011-05-18 20:35:38 +00004631bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004632 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004633
Chris Lattner25c3af32010-12-13 06:25:44 +00004634 // Conditional branch
4635 if (isValueEqualityComparison(BI)) {
4636 // If we only have one predecessor, and if it is a branch on this value,
4637 // see if that predecessor totally determines the outcome of this
4638 // switch.
4639 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00004640 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004641 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004642
Chris Lattner25c3af32010-12-13 06:25:44 +00004643 // This block must be empty, except for the setcond inst, if it exists.
4644 // Ignore dbg intrinsics.
4645 BasicBlock::iterator I = BB->begin();
4646 // Ignore dbg intrinsics.
4647 while (isa<DbgInfoIntrinsic>(I))
4648 ++I;
4649 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00004650 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004651 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004652 } else if (&*I == cast<Instruction>(BI->getCondition())){
4653 ++I;
4654 // Ignore dbg intrinsics.
4655 while (isa<DbgInfoIntrinsic>(I))
4656 ++I;
Devang Patel58380552011-05-18 20:53:17 +00004657 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004658 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004659 }
4660 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004661
Chris Lattner25c3af32010-12-13 06:25:44 +00004662 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004663 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00004664 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004665
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00004666 // If this basic block is ONLY a compare and a branch, and if a predecessor
4667 // branches to us and one of our successors, fold the comparison into the
4668 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004669 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4670 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004671
Chris Lattner25c3af32010-12-13 06:25:44 +00004672 // We have a conditional branch to two blocks that are only reachable
4673 // from BI. We know that the condbr dominates the two blocks, so see if
4674 // there is any identical code in the "then" and "else" blocks. If so, we
4675 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00004676 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4677 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004678 if (HoistThenElseCodeToIf(BI, TTI))
4679 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004680 } else {
4681 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004682 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00004683 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4684 if (Succ0TI->getNumSuccessors() == 1 &&
4685 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004686 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
4687 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004688 }
Craig Topperf40110f2014-04-25 05:29:35 +00004689 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004690 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004691 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00004692 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4693 if (Succ1TI->getNumSuccessors() == 1 &&
4694 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004695 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
4696 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004697 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004698
Chris Lattner25c3af32010-12-13 06:25:44 +00004699 // If this is a branch on a phi node in the current block, thread control
4700 // through this block if any PHI node entries are constants.
4701 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4702 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004703 if (FoldCondBranchOnPHI(BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004704 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004705
Chris Lattner25c3af32010-12-13 06:25:44 +00004706 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004707 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4708 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00004709 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00004710 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004711 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004712
4713 return false;
4714}
4715
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004716/// Check if passing a value to an instruction will cause undefined behavior.
4717static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4718 Constant *C = dyn_cast<Constant>(V);
4719 if (!C)
4720 return false;
4721
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004722 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004723 return false;
4724
4725 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004726 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00004727 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004728
4729 // Now make sure that there are no instructions in between that can alter
4730 // control flow (eg. calls)
4731 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00004732 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004733 return false;
4734
4735 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4736 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4737 if (GEP->getPointerOperand() == I)
4738 return passingValueIsAlwaysUndefined(V, GEP);
4739
4740 // Look through bitcasts.
4741 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4742 return passingValueIsAlwaysUndefined(V, BC);
4743
Benjamin Kramer0655b782011-08-26 02:25:55 +00004744 // Load from null is undefined.
4745 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004746 if (!LI->isVolatile())
4747 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004748
Benjamin Kramer0655b782011-08-26 02:25:55 +00004749 // Store to null is undefined.
4750 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004751 if (!SI->isVolatile())
4752 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004753 }
4754 return false;
4755}
4756
4757/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004758/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004759static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4760 for (BasicBlock::iterator i = BB->begin();
4761 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4762 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4763 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4764 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4765 IRBuilder<> Builder(T);
4766 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4767 BB->removePredecessor(PHI->getIncomingBlock(i));
4768 // Turn uncoditional branches into unreachables and remove the dead
4769 // destination from conditional branches.
4770 if (BI->isUnconditional())
4771 Builder.CreateUnreachable();
4772 else
4773 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4774 BI->getSuccessor(0));
4775 BI->eraseFromParent();
4776 return true;
4777 }
4778 // TODO: SwitchInst.
4779 }
4780
4781 return false;
4782}
4783
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004784bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00004785 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00004786
Chris Lattnerd7beca32010-12-14 06:17:25 +00004787 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00004788 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00004789
Dan Gohman4a63fad2010-08-14 00:29:42 +00004790 // Remove basic blocks that have no predecessors (except the entry block)...
4791 // or that just have themself as a predecessor. These are unreachable.
Ramkumar Ramachandra181233b2015-01-13 04:17:47 +00004792 if ((pred_empty(BB) &&
Chris Lattnerd7beca32010-12-14 06:17:25 +00004793 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00004794 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00004795 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00004796 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00004797 return true;
4798 }
4799
Chris Lattner031340a2003-08-17 19:41:53 +00004800 // Check to see if we can constant propagate this terminator instruction
4801 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00004802 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00004803
Dan Gohman1a951062009-10-30 22:39:04 +00004804 // Check for and eliminate duplicate PHI nodes in this block.
4805 Changed |= EliminateDuplicatePHINodes(BB);
4806
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004807 // Check for and remove branches that will always cause undefined behavior.
4808 Changed |= removeUndefIntroducingPredecessor(BB);
4809
Chris Lattner2e3832d2010-12-13 05:10:48 +00004810 // Merge basic blocks into their predecessor if there is only one distinct
4811 // pred, and if there is only one distinct successor of the predecessor, and
4812 // if there are no PHI nodes.
4813 //
4814 if (MergeBlockIntoPredecessor(BB))
4815 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004816
Devang Patel15ad6762011-05-18 18:01:27 +00004817 IRBuilder<> Builder(BB);
4818
Dan Gohman20af5a02008-03-11 21:53:06 +00004819 // If there is a trivial two-entry PHI node in this basic block, and we can
4820 // eliminate it, do so now.
4821 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4822 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004823 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00004824
Devang Patela7ec47d2011-05-18 20:35:38 +00004825 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00004826 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00004827 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00004828 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004829 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00004830 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004831 }
4832 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00004833 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00004834 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4835 if (SimplifyResume(RI, Builder)) return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00004836 } else if (CleanupReturnInst *RI =
4837 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
4838 if (SimplifyCleanupReturn(RI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004839 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00004840 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004841 } else if (UnreachableInst *UI =
4842 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4843 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004844 } else if (IndirectBrInst *IBI =
4845 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4846 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00004847 }
4848
Chris Lattner031340a2003-08-17 19:41:53 +00004849 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00004850}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004851
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004852/// This function is used to do simplification of a CFG.
4853/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004854/// eliminates unreachable basic blocks, and does other "peephole" optimization
4855/// of the CFG. It returns true if a modification was made.
4856///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004857bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004858 unsigned BonusInstThreshold, AssumptionCache *AC) {
4859 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
4860 BonusInstThreshold, AC).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004861}