blob: 02e17d388214d0047303f12cb6da0492be2c5365 [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
86 // case group is selected, and the second field is a vector containing the cases
87 // composing the case group.
88 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
91 // and the second field contains the value generated for a certain case in the switch
92 // for that PHI.
93 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);
Chris Lattner25c3af32010-12-13 06:25:44 +0000127 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000128 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000129 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000130 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000131 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000132
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000133public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000134 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
135 unsigned BonusInstThreshold, AssumptionCache *AC)
136 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000137 bool run(BasicBlock *BB);
138};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000139}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000140
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000141/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000142/// terminator instructions together.
Chris Lattner76dc2042005-08-03 00:19:45 +0000143static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
144 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000145
Chris Lattner76dc2042005-08-03 00:19:45 +0000146 // It is not safe to merge these two switch instructions if they have a common
147 // successor, and if that successor has a PHI node, and if *that* PHI node has
148 // conflicting incoming values from the two switch blocks.
149 BasicBlock *SI1BB = SI1->getParent();
150 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000151 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000152
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000153 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
154 if (SI1Succs.count(*I))
155 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000156 isa<PHINode>(BBI); ++BBI) {
157 PHINode *PN = cast<PHINode>(BBI);
158 if (PN->getIncomingValueForBlock(SI1BB) !=
159 PN->getIncomingValueForBlock(SI2BB))
160 return false;
161 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000162
Chris Lattner76dc2042005-08-03 00:19:45 +0000163 return true;
164}
165
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000166/// Return true if it is safe and profitable to merge these two terminator
167/// instructions together, where SI1 is an unconditional branch. PhiNodes will
168/// store all PHI nodes in common successors.
Manman Rend33f4ef2012-06-13 05:43:29 +0000169static bool isProfitableToFoldUnconditional(BranchInst *SI1,
170 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000171 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000172 SmallVectorImpl<PHINode*> &PhiNodes) {
173 if (SI1 == SI2) return false; // Can't merge with self!
174 assert(SI1->isUnconditional() && SI2->isConditional());
175
176 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000177 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000178 // 1> We have a constant incoming value for the conditional branch;
179 // 2> We have "Cond" as the incoming value for the unconditional branch;
180 // 3> SI2->getCondition() and Cond have same operands.
181 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
182 if (!Ci2) return false;
183 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
184 Cond->getOperand(1) == Ci2->getOperand(1)) &&
185 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
186 Cond->getOperand(1) == Ci2->getOperand(0)))
187 return false;
188
189 BasicBlock *SI1BB = SI1->getParent();
190 BasicBlock *SI2BB = SI2->getParent();
191 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000192 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
193 if (SI1Succs.count(*I))
194 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000195 isa<PHINode>(BBI); ++BBI) {
196 PHINode *PN = cast<PHINode>(BBI);
197 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000198 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000199 return false;
200 PhiNodes.push_back(PN);
201 }
202 return true;
203}
204
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000205/// Update PHI nodes in Succ to indicate that there will now be entries in it
206/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
207/// will be the same as those coming in from ExistPred, an existing predecessor
208/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000209static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
210 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000211 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000212
Chris Lattner80b03a12008-07-13 22:23:11 +0000213 PHINode *PN;
214 for (BasicBlock::iterator I = Succ->begin();
215 (PN = dyn_cast<PHINode>(I)); ++I)
216 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000217}
218
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000219/// Compute an abstract "cost" of speculating the given instruction,
220/// which is assumed to be safe to speculate. TCC_Free means cheap,
221/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000222/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000223static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000224 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000225 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000226 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000227 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000228}
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000229/// If we have a merge point of an "if condition" as accepted above,
230/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000231/// don't handle the true generality of domination here, just a special case
232/// which works well enough for us.
233///
234/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000235/// see if V (which must be an instruction) and its recursive operands
236/// that do not dominate BB have a combined cost lower than CostRemaining and
237/// are non-trapping. If both are true, the instruction is inserted into the
238/// set and true is returned.
239///
240/// The cost for most non-trapping instructions is defined as 1 except for
241/// Select whose cost is 2.
242///
243/// After this function returns, CostRemaining is decreased by the cost of
244/// V plus its non-dominating operands. If that cost is greater than
245/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000246static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000247 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000248 unsigned &CostRemaining,
James Molloy7c336572015-02-11 12:15:41 +0000249 const TargetTransformInfo &TTI) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000250 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000251 if (!I) {
252 // Non-instructions all dominate instructions, but not all constantexprs
253 // can be executed unconditionally.
254 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
255 if (C->canTrap())
256 return false;
257 return true;
258 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000259 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000260
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000261 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000262 // the bottom of this block.
263 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000264
Chris Lattner0aa56562004-04-09 22:50:22 +0000265 // If this instruction is defined in a block that contains an unconditional
266 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000267 // statement". If not, it definitely dominates the region.
268 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000269 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000270 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000271
Chris Lattner9ac168d2010-12-14 07:41:39 +0000272 // If we aren't allowing aggressive promotion anymore, then don't consider
273 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000274 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000275
Peter Collingbournee3511e12011-04-29 18:47:31 +0000276 // If we have seen this instruction before, don't count it again.
277 if (AggressiveInsts->count(I)) return true;
278
Chris Lattner9ac168d2010-12-14 07:41:39 +0000279 // Okay, it looks like the instruction IS in the "condition". Check to
280 // see if it's a cheap instruction to unconditionally compute, and if it
281 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000282 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000283 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000284
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000285 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000286
Peter Collingbournee3511e12011-04-29 18:47:31 +0000287 if (Cost > CostRemaining)
288 return false;
289
290 CostRemaining -= Cost;
291
292 // Okay, we can only really hoist these out if their operands do
293 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000294 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000295 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000296 return false;
297 // Okay, it's safe to do this! Remember this instruction.
298 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000299 return true;
300}
Chris Lattner466a0492002-05-21 20:50:24 +0000301
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000302/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000303/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000304static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000305 // Normal constant int.
306 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000307 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000308 return CI;
309
310 // This is some kind of pointer constant. Turn it into a pointer-sized
311 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000312 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000313
314 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
315 if (isa<ConstantPointerNull>(V))
316 return ConstantInt::get(PtrTy, 0);
317
318 // IntToPtr const int.
319 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
320 if (CE->getOpcode() == Instruction::IntToPtr)
321 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
322 // The constant is very likely to have the right type already.
323 if (CI->getType() == PtrTy)
324 return CI;
325 else
326 return cast<ConstantInt>
327 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
328 }
Craig Topperf40110f2014-04-25 05:29:35 +0000329 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000330}
331
Mehdi Aminiffd01002014-11-20 22:40:25 +0000332namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000333
Mehdi Aminiffd01002014-11-20 22:40:25 +0000334/// Given a chain of or (||) or and (&&) comparison of a value against a
335/// constant, this will try to recover the information required for a switch
336/// structure.
337/// It will depth-first traverse the chain of comparison, seeking for patterns
338/// like %a == 12 or %a < 4 and combine them to produce a set of integer
339/// representing the different cases for the switch.
340/// Note that if the chain is composed of '||' it will build the set of elements
341/// that matches the comparisons (i.e. any of this value validate the chain)
342/// while for a chain of '&&' it will build the set elements that make the test
343/// fail.
344struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000345 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000346 Value *CompValue; /// Value found for the switch comparison
347 Value *Extra; /// Extra clause to be checked before the switch
348 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
349 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000350
Mehdi Aminiffd01002014-11-20 22:40:25 +0000351 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000352 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
353 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
354 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000355 }
356
Mehdi Aminiffd01002014-11-20 22:40:25 +0000357 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000358 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000359 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000360 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000361
Mehdi Aminiffd01002014-11-20 22:40:25 +0000362private:
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000363
Mehdi Aminiffd01002014-11-20 22:40:25 +0000364 /// Try to set the current value used for the comparison, it succeeds only if
365 /// it wasn't set before or if the new value is the same as the old one
366 bool setValueOnce(Value *NewVal) {
367 if(CompValue && CompValue != NewVal) return false;
368 CompValue = NewVal;
369 return (CompValue != nullptr);
370 }
371
372 /// Try to match Instruction "I" as a comparison against a constant and
373 /// populates the array Vals with the set of values that match (or do not
374 /// match depending on isEQ).
375 /// Return false on failure. On success, the Value the comparison matched
376 /// against is placed in CompValue.
377 /// If CompValue is already set, the function is expected to fail if a match
378 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000379 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000380 // If this is an icmp against a constant, handle this as one of the cases.
381 ICmpInst *ICI;
382 ConstantInt *C;
383 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
384 (C = GetConstantInt(I->getOperand(1), DL)))) {
385 return false;
386 }
387
388 Value *RHSVal;
389 ConstantInt *RHSC;
390
391 // Pattern match a special case
392 // (x & ~2^x) == y --> x == y || x == y|2^x
393 // This undoes a transformation done by instcombine to fuse 2 compares.
394 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
395 if (match(ICI->getOperand(0),
396 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
397 APInt Not = ~RHSC->getValue();
398 if (Not.isPowerOf2()) {
399 // If we already have a value for the switch, it has to match!
400 if(!setValueOnce(RHSVal))
401 return false;
402
403 Vals.push_back(C);
404 Vals.push_back(ConstantInt::get(C->getContext(),
405 C->getValue() | Not));
406 UsedICmps++;
407 return true;
408 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000409 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000410
411 // If we already have a value for the switch, it has to match!
412 if(!setValueOnce(ICI->getOperand(0)))
413 return false;
414
415 UsedICmps++;
416 Vals.push_back(C);
417 return ICI->getOperand(0);
418 }
419
420 // 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 +0000421 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
422 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000423
424 // Shift the range if the compare is fed by an add. This is the range
425 // compare idiom as emitted by instcombine.
426 Value *CandidateVal = I->getOperand(0);
427 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
428 Span = Span.subtract(RHSC->getValue());
429 CandidateVal = RHSVal;
430 }
431
432 // If this is an and/!= check, then we are looking to build the set of
433 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
434 // x != 0 && x != 1.
435 if (!isEQ)
436 Span = Span.inverse();
437
438 // If there are a ton of values, we don't want to make a ginormous switch.
439 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
440 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000441 }
442
443 // If we already have a value for the switch, it has to match!
Mehdi Aminiffd01002014-11-20 22:40:25 +0000444 if(!setValueOnce(CandidateVal))
445 return false;
446
447 // Add all values from the range to the set
448 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
449 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000450
451 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000452 return true;
453
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000454 }
455
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000456 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000457 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
458 /// the value being compared, and stick the list constants into the Vals
459 /// vector.
460 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000461 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000462 Instruction *I = dyn_cast<Instruction>(V);
463 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000464
Mehdi Aminiffd01002014-11-20 22:40:25 +0000465 // Keep a stack (SmallVector for efficiency) for depth-first traversal
466 SmallVector<Value *, 8> DFT;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000467
Mehdi Aminiffd01002014-11-20 22:40:25 +0000468 // Initialize
469 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000470
Mehdi Aminiffd01002014-11-20 22:40:25 +0000471 while(!DFT.empty()) {
472 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000473
Mehdi Aminiffd01002014-11-20 22:40:25 +0000474 if (Instruction *I = dyn_cast<Instruction>(V)) {
475 // If it is a || (or && depending on isEQ), process the operands.
476 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
477 DFT.push_back(I->getOperand(1));
478 DFT.push_back(I->getOperand(0));
479 continue;
480 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000481
Mehdi Aminiffd01002014-11-20 22:40:25 +0000482 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000483 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000484 // Match succeed, continue the loop
485 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000486 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000487
Mehdi Aminiffd01002014-11-20 22:40:25 +0000488 // One element of the sequence of || (or &&) could not be match as a
489 // comparison against the same value as the others.
490 // We allow only one "Extra" case to be checked before the switch
491 if (!Extra) {
492 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000493 continue;
494 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000495 // Failed to parse a proper sequence, abort now
496 CompValue = nullptr;
497 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000498 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000499 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000500};
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000501
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000502}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000503
Eli Friedmancb61afb2008-12-16 20:54:32 +0000504static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000505 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000506 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
507 Cond = dyn_cast<Instruction>(SI->getCondition());
508 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
509 if (BI->isConditional())
510 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000511 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
512 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000513 }
514
515 TI->eraseFromParent();
516 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
517}
518
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000519/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000520/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000521Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000522 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000523 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
524 // Do not permit merging of large switch instructions into their
525 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000526 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
527 pred_end(SI->getParent())) <= 128)
528 CV = SI->getCondition();
529 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000530 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000531 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000532 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000533 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000534 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000535
536 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000537 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000538 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
539 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000540 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000541 CV = Ptr;
542 }
543 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000544 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000545}
546
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000547/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000548/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000549BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000550GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000551 std::vector<ValueEqualityComparisonCase>
552 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000553 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000554 Cases.reserve(SI->getNumCases());
555 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
556 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
557 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000558 return SI->getDefaultDest();
559 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000560
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000561 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000562 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000563 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
564 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000565 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000566 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000567 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000568}
569
Eric Christopherb65acc62012-07-02 23:22:21 +0000570
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000571/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000572/// in the list that match the specified block.
573static void EliminateBlockCases(BasicBlock *BB,
574 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000575 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000576}
577
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000578/// Return true if there are any keys in C1 that exist in C2 as well.
Eric Christopherb65acc62012-07-02 23:22:21 +0000579static bool
580ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
581 std::vector<ValueEqualityComparisonCase > &C2) {
582 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
583
584 // Make V1 be smaller than V2.
585 if (V1->size() > V2->size())
586 std::swap(V1, V2);
587
588 if (V1->size() == 0) return false;
589 if (V1->size() == 1) {
590 // Just scan V2.
591 ConstantInt *TheVal = (*V1)[0].Value;
592 for (unsigned i = 0, e = V2->size(); i != e; ++i)
593 if (TheVal == (*V2)[i].Value)
594 return true;
595 }
596
597 // Otherwise, just sort both lists and compare element by element.
598 array_pod_sort(V1->begin(), V1->end());
599 array_pod_sort(V2->begin(), V2->end());
600 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
601 while (i1 != e1 && i2 != e2) {
602 if ((*V1)[i1].Value == (*V2)[i2].Value)
603 return true;
604 if ((*V1)[i1].Value < (*V2)[i2].Value)
605 ++i1;
606 else
607 ++i2;
608 }
609 return false;
610}
611
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000612/// If TI is known to be a terminator instruction and its block is known to
613/// only have a single predecessor block, check to see if that predecessor is
614/// also a value comparison with the same value, and if that comparison
615/// determines the outcome of this comparison. If so, simplify TI. This does a
616/// very limited form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000617bool SimplifyCFGOpt::
618SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000619 BasicBlock *Pred,
620 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000621 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
622 if (!PredVal) return false; // Not a value comparison in predecessor.
623
624 Value *ThisVal = isValueEqualityComparison(TI);
625 assert(ThisVal && "This isn't a value comparison!!");
626 if (ThisVal != PredVal) return false; // Different predicates.
627
Andrew Trick3051aa12012-08-29 21:46:38 +0000628 // TODO: Preserve branch weight metadata, similarly to how
629 // FoldValueComparisonIntoPredecessors preserves it.
630
Chris Lattner1cca9592005-02-24 06:17:52 +0000631 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000632 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000633 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
634 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000635 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000636
Chris Lattner1cca9592005-02-24 06:17:52 +0000637 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000638 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000639 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000640 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000641
642 // If TI's block is the default block from Pred's comparison, potentially
643 // simplify TI based on this knowledge.
644 if (PredDef == TI->getParent()) {
645 // If we are here, we know that the value is none of those cases listed in
646 // PredCases. If there are any cases in ThisCases that are in PredCases, we
647 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000648 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000649 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000650
Chris Lattner4088e2b2010-12-13 01:47:07 +0000651 if (isa<BranchInst>(TI)) {
652 // Okay, one of the successors of this condbr is dead. Convert it to a
653 // uncond br.
654 assert(ThisCases.size() == 1 && "Branch can only have one case!");
655 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000656 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000657 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000658
Chris Lattner4088e2b2010-12-13 01:47:07 +0000659 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000660 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000661
Chris Lattner4088e2b2010-12-13 01:47:07 +0000662 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
663 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000664
Chris Lattner4088e2b2010-12-13 01:47:07 +0000665 EraseTerminatorInstAndDCECond(TI);
666 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000667 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000668
Chris Lattner4088e2b2010-12-13 01:47:07 +0000669 SwitchInst *SI = cast<SwitchInst>(TI);
670 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000671 SmallPtrSet<Constant*, 16> DeadCases;
672 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
673 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000674
David Greene725c7c32010-01-05 01:26:52 +0000675 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000676 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000677
Manman Ren8691e522012-09-14 21:53:06 +0000678 // Collect branch weights into a vector.
679 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000680 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000681 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
682 if (HasWeight)
683 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
684 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000685 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000686 Weights.push_back(CI->getValue().getZExtValue());
687 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000688 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
689 --i;
690 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000691 if (HasWeight) {
692 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
693 Weights.pop_back();
694 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000695 i.getCaseSuccessor()->removePredecessor(TI->getParent());
696 SI->removeCase(i);
697 }
698 }
Manman Ren97c18762012-10-11 22:28:34 +0000699 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000700 SI->setMetadata(LLVMContext::MD_prof,
701 MDBuilder(SI->getParent()->getContext()).
702 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000703
704 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000705 return true;
706 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000707
Chris Lattner4088e2b2010-12-13 01:47:07 +0000708 // Otherwise, TI's block must correspond to some matched value. Find out
709 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000710 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000711 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000712 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
713 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000714 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000715 return false; // Cannot handle multiple values coming to this block.
716 TIV = PredCases[i].Value;
717 }
718 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000719
720 // Okay, we found the one constant that our value can be if we get into TI's
721 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000722 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000723 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
724 if (ThisCases[i].Value == TIV) {
725 TheRealDest = ThisCases[i].Dest;
726 break;
727 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000728
729 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000730 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000731
732 // Remove PHI node entries for dead edges.
733 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000734 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
735 if (*SI != CheckEdge)
736 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000737 else
Craig Topperf40110f2014-04-25 05:29:35 +0000738 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000739
740 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000741 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000742 (void) NI;
743
744 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
745 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
746
747 EraseTerminatorInstAndDCECond(TI);
748 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000749}
750
Dale Johannesen7f99d222009-03-12 21:01:11 +0000751namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000752 /// This class implements a stable ordering of constant
Dale Johannesen7f99d222009-03-12 21:01:11 +0000753 /// integers that does not depend on their address. This is important for
754 /// applications that sort ConstantInt's to ensure uniqueness.
755 struct ConstantIntOrdering {
756 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
757 return LHS->getValue().ult(RHS->getValue());
758 }
759 };
760}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000761
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000762static int ConstantIntSortPredicate(ConstantInt *const *P1,
763 ConstantInt *const *P2) {
764 const ConstantInt *LHS = *P1;
765 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000766 if (LHS->getValue().ult(RHS->getValue()))
767 return 1;
768 if (LHS->getValue() == RHS->getValue())
769 return 0;
770 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000771}
772
Andrew Trick3051aa12012-08-29 21:46:38 +0000773static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000774 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000775 if (ProfMD && ProfMD->getOperand(0))
776 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
777 return MDS->getString().equals("branch_weights");
778
779 return false;
780}
781
Manman Ren571d9e42012-09-11 17:43:35 +0000782/// Get Weights of a given TerminatorInst, the default weight is at the front
783/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
784/// metadata.
785static void GetBranchWeights(TerminatorInst *TI,
786 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000787 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000788 assert(MD);
789 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000790 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000791 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000792 }
793
Manman Ren571d9e42012-09-11 17:43:35 +0000794 // If TI is a conditional eq, the default case is the false case,
795 // and the corresponding branch-weight data is at index 2. We swap the
796 // default weight to be the first entry.
797 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
798 assert(Weights.size() == 2);
799 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
800 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
801 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000802 }
803}
804
Manman Renf1cb16e2014-01-27 23:39:03 +0000805/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000806static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000807 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
808 if (Max > UINT_MAX) {
809 unsigned Offset = 32 - countLeadingZeros(Max);
810 for (uint64_t &I : Weights)
811 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000812 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000813}
814
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000815/// The specified terminator is a value equality comparison instruction
816/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000817/// See if any of the predecessors of the terminator block are value comparisons
818/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000819bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
820 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000821 BasicBlock *BB = TI->getParent();
822 Value *CV = isValueEqualityComparison(TI); // CondVal
823 assert(CV && "Not a comparison?");
824 bool Changed = false;
825
Chris Lattner6b39cb92008-02-18 07:42:56 +0000826 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000827 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000828 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000829
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000830 // See if the predecessor is a comparison with the same value.
831 TerminatorInst *PTI = Pred->getTerminator();
832 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
833
834 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
835 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000836 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000837 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
838
Eric Christopherb65acc62012-07-02 23:22:21 +0000839 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000840 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
841
842 // Based on whether the default edge from PTI goes to BB or not, fill in
843 // PredCases and PredDefault with the new switch cases we would like to
844 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000845 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000846
Andrew Trick3051aa12012-08-29 21:46:38 +0000847 // Update the branch weight metadata along the way
848 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000849 bool PredHasWeights = HasBranchWeights(PTI);
850 bool SuccHasWeights = HasBranchWeights(TI);
851
Manman Ren5e5049d2012-09-14 19:05:19 +0000852 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000853 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000854 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000855 if (Weights.size() != 1 + PredCases.size())
856 PredHasWeights = SuccHasWeights = false;
857 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000858 // If there are no predecessor weights but there are successor weights,
859 // populate Weights with 1, which will later be scaled to the sum of
860 // successor's weights
861 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000862
Manman Ren571d9e42012-09-11 17:43:35 +0000863 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000864 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000865 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000866 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000867 if (SuccWeights.size() != 1 + BBCases.size())
868 PredHasWeights = SuccHasWeights = false;
869 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000870 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000871
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000872 if (PredDefault == BB) {
873 // If this is the default destination from PTI, only the edges in TI
874 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000875 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
876 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
877 if (PredCases[i].Dest != BB)
878 PTIHandled.insert(PredCases[i].Value);
879 else {
880 // The default destination is BB, we don't need explicit targets.
881 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000882
Manman Ren571d9e42012-09-11 17:43:35 +0000883 if (PredHasWeights || SuccHasWeights) {
884 // Increase weight for the default case.
885 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000886 std::swap(Weights[i+1], Weights.back());
887 Weights.pop_back();
888 }
889
Eric Christopherb65acc62012-07-02 23:22:21 +0000890 PredCases.pop_back();
891 --i; --e;
892 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000893
Eric Christopherb65acc62012-07-02 23:22:21 +0000894 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000895 if (PredDefault != BBDefault) {
896 PredDefault->removePredecessor(Pred);
897 PredDefault = BBDefault;
898 NewSuccessors.push_back(BBDefault);
899 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000900
Manman Ren571d9e42012-09-11 17:43:35 +0000901 unsigned CasesFromPred = Weights.size();
902 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000903 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
904 if (!PTIHandled.count(BBCases[i].Value) &&
905 BBCases[i].Dest != BBDefault) {
906 PredCases.push_back(BBCases[i]);
907 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000908 if (SuccHasWeights || PredHasWeights) {
909 // The default weight is at index 0, so weight for the ith case
910 // should be at index i+1. Scale the cases from successor by
911 // PredDefaultWeight (Weights[0]).
912 Weights.push_back(Weights[0] * SuccWeights[i+1]);
913 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000914 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000915 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000916
Manman Ren571d9e42012-09-11 17:43:35 +0000917 if (SuccHasWeights || PredHasWeights) {
918 ValidTotalSuccWeight += SuccWeights[0];
919 // Scale the cases from predecessor by ValidTotalSuccWeight.
920 for (unsigned i = 1; i < CasesFromPred; ++i)
921 Weights[i] *= ValidTotalSuccWeight;
922 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
923 Weights[0] *= SuccWeights[0];
924 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000925 } else {
926 // If this is not the default destination from PSI, only the edges
927 // in SI that occur in PSI with a destination of BB will be
928 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000929 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000930 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000931 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
932 if (PredCases[i].Dest == BB) {
933 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000934
935 if (PredHasWeights || SuccHasWeights) {
936 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
937 std::swap(Weights[i+1], Weights.back());
938 Weights.pop_back();
939 }
940
Eric Christopherb65acc62012-07-02 23:22:21 +0000941 std::swap(PredCases[i], PredCases.back());
942 PredCases.pop_back();
943 --i; --e;
944 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000945
946 // Okay, now we know which constants were sent to BB from the
947 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000948 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
949 if (PTIHandled.count(BBCases[i].Value)) {
950 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000951 if (PredHasWeights || SuccHasWeights)
952 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000953 PredCases.push_back(BBCases[i]);
954 NewSuccessors.push_back(BBCases[i].Dest);
955 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
956 }
957
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000958 // If there are any constants vectored to BB that TI doesn't handle,
959 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000960 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000961 PTIHandled.begin(),
962 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000963 if (PredHasWeights || SuccHasWeights)
964 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000965 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000966 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000967 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000968 }
969
970 // Okay, at this point, we know which new successor Pred will get. Make
971 // sure we update the number of entries in the PHI nodes for these
972 // successors.
973 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
974 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
975
Devang Patel58380552011-05-18 20:53:17 +0000976 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000977 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +0000978 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000979 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +0000980 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000981 }
982
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000983 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +0000984 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
985 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +0000986 NewSI->setDebugLoc(PTI->getDebugLoc());
Eric Christopherb65acc62012-07-02 23:22:21 +0000987 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
988 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +0000989
Andrew Trick3051aa12012-08-29 21:46:38 +0000990 if (PredHasWeights || SuccHasWeights) {
991 // Halve the weights if any of them cannot fit in an uint32_t
992 FitWeights(Weights);
993
994 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
995
996 NewSI->setMetadata(LLVMContext::MD_prof,
997 MDBuilder(BB->getContext()).
998 createBranchWeights(MDWeights));
999 }
1000
Eli Friedmancb61afb2008-12-16 20:54:32 +00001001 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001002
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001003 // Okay, last check. If BB is still a successor of PSI, then we must
1004 // have an infinite loop case. If so, add an infinitely looping block
1005 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001006 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001007 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1008 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001009 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001010 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001011 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001012 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1013 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001014 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001015 }
1016 NewSI->setSuccessor(i, InfLoopBlock);
1017 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001018
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001019 Changed = true;
1020 }
1021 }
1022 return Changed;
1023}
1024
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001025// If we would need to insert a select that uses the value of this invoke
1026// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1027// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001028static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1029 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001030 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001031 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001032 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001033 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1034 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1035 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1036 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1037 return false;
1038 }
1039 }
1040 }
1041 return true;
1042}
1043
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001044static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1045
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001046/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1047/// in the two blocks up into the branch block. The caller of this function
1048/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001049static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001050 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001051 // This does very trivial matching, with limited scanning, to find identical
1052 // instructions in the two blocks. In particular, we don't want to get into
1053 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1054 // such, we currently just scan for obviously identical instructions in an
1055 // identical order.
1056 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1057 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1058
Devang Patelf10e2872009-02-04 00:03:08 +00001059 BasicBlock::iterator BB1_Itr = BB1->begin();
1060 BasicBlock::iterator BB2_Itr = BB2->begin();
1061
1062 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001063 // Skip debug info if it is not identical.
1064 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1065 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1066 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1067 while (isa<DbgInfoIntrinsic>(I1))
1068 I1 = BB1_Itr++;
1069 while (isa<DbgInfoIntrinsic>(I2))
1070 I2 = BB2_Itr++;
1071 }
Devang Patele48ddf82011-04-07 00:30:15 +00001072 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001073 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001074 return false;
1075
Chris Lattner389cfac2004-11-30 00:29:14 +00001076 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001077
David Majnemerc82f27a2013-06-03 20:43:12 +00001078 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001079 do {
1080 // If we are hoisting the terminator instruction, don't move one (making a
1081 // broken BB), instead clone it, and remove BI.
1082 if (isa<TerminatorInst>(I1))
1083 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001084
Chad Rosier54390052015-02-23 19:15:16 +00001085 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1086 return Changed;
1087
Chris Lattner389cfac2004-11-30 00:29:14 +00001088 // For a normal instruction, we just move one to right before the branch,
1089 // then replace all uses of the other with the first. Finally, we remove
1090 // the now redundant second instruction.
1091 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1092 if (!I2->use_empty())
1093 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001094 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001095 unsigned KnownIDs[] = {
Adrian Prantlbaf90fc2015-08-20 18:24:02 +00001096 LLVMContext::MD_dbg,
Rafael Espindolaea46c322014-08-15 15:46:38 +00001097 LLVMContext::MD_tbaa,
1098 LLVMContext::MD_range,
1099 LLVMContext::MD_fpmath,
Philip Reamesd92c2a72014-10-22 16:37:13 +00001100 LLVMContext::MD_invariant_load,
1101 LLVMContext::MD_nonnull
Rafael Espindolaea46c322014-08-15 15:46:38 +00001102 };
1103 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001104 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001105 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001106
Devang Patelf10e2872009-02-04 00:03:08 +00001107 I1 = BB1_Itr++;
Devang Patelf10e2872009-02-04 00:03:08 +00001108 I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001109 // Skip debug info if it is not identical.
1110 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1111 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1112 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1113 while (isa<DbgInfoIntrinsic>(I1))
1114 I1 = BB1_Itr++;
1115 while (isa<DbgInfoIntrinsic>(I2))
1116 I2 = BB2_Itr++;
1117 }
Devang Patele48ddf82011-04-07 00:30:15 +00001118 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001119
1120 return true;
1121
1122HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001123 // It may not be possible to hoist an invoke.
1124 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001125 return Changed;
1126
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001127 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001128 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001129 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001130 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1131 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1132 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1133 if (BB1V == BB2V)
1134 continue;
1135
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001136 // Check for passingValueIsAlwaysUndefined here because we would rather
1137 // eliminate undefined control flow then converting it to a select.
1138 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1139 passingValueIsAlwaysUndefined(BB2V, PN))
1140 return Changed;
1141
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001142 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001143 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001144 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001145 return Changed;
1146 }
1147 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001148
Chris Lattner389cfac2004-11-30 00:29:14 +00001149 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001150 Instruction *NT = I1->clone();
Chris Lattner389cfac2004-11-30 00:29:14 +00001151 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001152 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001153 I1->replaceAllUsesWith(NT);
1154 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001155 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001156 }
1157
Devang Patel1407fb42011-05-19 20:52:46 +00001158 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001159 // Hoisting one of the terminators from our successor is a great thing.
1160 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1161 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1162 // nodes, so we insert select instruction to compute the final result.
1163 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001164 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001165 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001166 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001167 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001168 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1169 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001170 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001171
Chris Lattner4088e2b2010-12-13 01:47:07 +00001172 // These values do not agree. Insert a select instruction before NT
1173 // that determines the right value.
1174 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001175 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001176 SI = cast<SelectInst>
1177 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1178 BB1V->getName()+"."+BB2V->getName()));
1179
Chris Lattner4088e2b2010-12-13 01:47:07 +00001180 // Make the PHI node use the select for all incoming values for BB1/BB2
1181 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1182 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1183 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001184 }
1185 }
1186
1187 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001188 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1189 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001190
Eli Friedmancb61afb2008-12-16 20:54:32 +00001191 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001192 return true;
1193}
1194
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001195/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001196/// check whether BBEnd has only two predecessors and the other predecessor
1197/// ends with an unconditional branch. If it is true, sink any common code
1198/// in the two predecessors to BBEnd.
1199static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1200 assert(BI1->isUnconditional());
1201 BasicBlock *BB1 = BI1->getParent();
1202 BasicBlock *BBEnd = BI1->getSuccessor(0);
1203
1204 // Check that BBEnd has two predecessors and the other predecessor ends with
1205 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001206 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1207 BasicBlock *Pred0 = *PI++;
1208 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001209 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001210 BasicBlock *Pred1 = *PI++;
1211 if (PI != PE) // More than two predecessors.
1212 return false;
1213 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001214 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1215 if (!BI2 || !BI2->isUnconditional())
1216 return false;
1217
1218 // Gather the PHI nodes in BBEnd.
Michael Liao5313da32014-12-23 08:26:55 +00001219 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
Craig Topperf40110f2014-04-25 05:29:35 +00001220 Instruction *FirstNonPhiInBBEnd = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001221 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
Manman Ren93ab6492012-09-20 22:37:36 +00001222 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1223 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001224 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Michael Liao5313da32014-12-23 08:26:55 +00001225 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
Manman Ren93ab6492012-09-20 22:37:36 +00001226 } else {
1227 FirstNonPhiInBBEnd = &*I;
1228 break;
1229 }
1230 }
1231 if (!FirstNonPhiInBBEnd)
1232 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001233
Manman Ren93ab6492012-09-20 22:37:36 +00001234 // This does very trivial matching, with limited scanning, to find identical
1235 // instructions in the two blocks. We scan backward for obviously identical
1236 // instructions in an identical order.
1237 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
Michael Liao5313da32014-12-23 08:26:55 +00001238 RE1 = BB1->getInstList().rend(),
1239 RI2 = BB2->getInstList().rbegin(),
1240 RE2 = BB2->getInstList().rend();
Manman Ren93ab6492012-09-20 22:37:36 +00001241 // Skip debug info.
1242 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1243 if (RI1 == RE1)
1244 return false;
1245 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1246 if (RI2 == RE2)
1247 return false;
1248 // Skip the unconditional branches.
1249 ++RI1;
1250 ++RI2;
1251
1252 bool Changed = false;
1253 while (RI1 != RE1 && RI2 != RE2) {
1254 // Skip debug info.
1255 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1256 if (RI1 == RE1)
1257 return Changed;
1258 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1259 if (RI2 == RE2)
1260 return Changed;
1261
1262 Instruction *I1 = &*RI1, *I2 = &*RI2;
Michael Liao5313da32014-12-23 08:26:55 +00001263 auto InstPair = std::make_pair(I1, I2);
Manman Ren93ab6492012-09-20 22:37:36 +00001264 // I1 and I2 should have a single use in the same PHI node, and they
1265 // perform the same operation.
1266 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1267 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1268 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
David Majnemerba275f92015-08-19 19:54:02 +00001269 I1->isEHPad() || I2->isEHPad() ||
Manman Ren93ab6492012-09-20 22:37:36 +00001270 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1271 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1272 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1273 !I1->hasOneUse() || !I2->hasOneUse() ||
Michael Liao5313da32014-12-23 08:26:55 +00001274 !JointValueMap.count(InstPair))
Manman Ren93ab6492012-09-20 22:37:36 +00001275 return Changed;
1276
1277 // Check whether we should swap the operands of ICmpInst.
Michael Liao5313da32014-12-23 08:26:55 +00001278 // TODO: Add support of communativity.
Manman Ren93ab6492012-09-20 22:37:36 +00001279 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1280 bool SwapOpnds = false;
1281 if (ICmp1 && ICmp2 &&
1282 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1283 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1284 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1285 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1286 ICmp2->swapOperands();
1287 SwapOpnds = true;
1288 }
1289 if (!I1->isSameOperationAs(I2)) {
1290 if (SwapOpnds)
1291 ICmp2->swapOperands();
1292 return Changed;
1293 }
1294
1295 // The operands should be either the same or they need to be generated
1296 // with a PHI node after sinking. We only handle the case where there is
1297 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001298 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001299 unsigned Op1Idx = ~0U;
Manman Ren93ab6492012-09-20 22:37:36 +00001300 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1301 if (I1->getOperand(I) == I2->getOperand(I))
1302 continue;
Michael Liao5313da32014-12-23 08:26:55 +00001303 // Early exit if we have more-than one pair of different operands or if
1304 // we need a PHI node to replace a constant.
1305 if (Op1Idx != ~0U ||
Manman Ren93ab6492012-09-20 22:37:36 +00001306 isa<Constant>(I1->getOperand(I)) ||
1307 isa<Constant>(I2->getOperand(I))) {
1308 // If we can't sink the instructions, undo the swapping.
1309 if (SwapOpnds)
1310 ICmp2->swapOperands();
1311 return Changed;
1312 }
1313 DifferentOp1 = I1->getOperand(I);
1314 Op1Idx = I;
1315 DifferentOp2 = I2->getOperand(I);
1316 }
1317
Michael Liao5313da32014-12-23 08:26:55 +00001318 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1319 DEBUG(dbgs() << " " << *I2 << "\n");
1320
1321 // We insert the pair of different operands to JointValueMap and
1322 // remove (I1, I2) from JointValueMap.
1323 if (Op1Idx != ~0U) {
1324 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1325 if (!NewPN) {
1326 NewPN =
1327 PHINode::Create(DifferentOp1->getType(), 2,
1328 DifferentOp1->getName() + ".sink", BBEnd->begin());
1329 NewPN->addIncoming(DifferentOp1, BB1);
1330 NewPN->addIncoming(DifferentOp2, BB2);
1331 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1332 }
Manman Ren93ab6492012-09-20 22:37:36 +00001333 // I1 should use NewPN instead of DifferentOp1.
1334 I1->setOperand(Op1Idx, NewPN);
Manman Ren93ab6492012-09-20 22:37:36 +00001335 }
Michael Liao5313da32014-12-23 08:26:55 +00001336 PHINode *OldPN = JointValueMap[InstPair];
1337 JointValueMap.erase(InstPair);
Manman Ren93ab6492012-09-20 22:37:36 +00001338
Manman Ren93ab6492012-09-20 22:37:36 +00001339 // We need to update RE1 and RE2 if we are going to sink the first
1340 // instruction in the basic block down.
1341 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1342 // Sink the instruction.
1343 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1344 if (!OldPN->use_empty())
1345 OldPN->replaceAllUsesWith(I1);
1346 OldPN->eraseFromParent();
1347
1348 if (!I2->use_empty())
1349 I2->replaceAllUsesWith(I1);
1350 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001351 // TODO: Use combineMetadata here to preserve what metadata we can
1352 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001353 I2->eraseFromParent();
1354
1355 if (UpdateRE1)
1356 RE1 = BB1->getInstList().rend();
1357 if (UpdateRE2)
1358 RE2 = BB2->getInstList().rend();
1359 FirstNonPhiInBBEnd = I1;
1360 NumSinkCommons++;
1361 Changed = true;
1362 }
1363 return Changed;
1364}
1365
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001366/// \brief Determine if we can hoist sink a sole store instruction out of a
1367/// conditional block.
1368///
1369/// We are looking for code like the following:
1370/// BrBB:
1371/// store i32 %add, i32* %arrayidx2
1372/// ... // No other stores or function calls (we could be calling a memory
1373/// ... // function).
1374/// %cmp = icmp ult %x, %y
1375/// br i1 %cmp, label %EndBB, label %ThenBB
1376/// ThenBB:
1377/// store i32 %add5, i32* %arrayidx2
1378/// br label EndBB
1379/// EndBB:
1380/// ...
1381/// We are going to transform this into:
1382/// BrBB:
1383/// store i32 %add, i32* %arrayidx2
1384/// ... //
1385/// %cmp = icmp ult %x, %y
1386/// %add.add5 = select i1 %cmp, i32 %add, %add5
1387/// store i32 %add.add5, i32* %arrayidx2
1388/// ...
1389///
1390/// \return The pointer to the value of the previous store if the store can be
1391/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001392static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1393 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001394 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1395 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001396 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001397
1398 // Volatile or atomic.
1399 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001400 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001401
1402 Value *StorePtr = StoreToHoist->getPointerOperand();
1403
1404 // Look for a store to the same pointer in BrBB.
1405 unsigned MaxNumInstToLookAt = 10;
1406 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1407 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1408 Instruction *CurI = &*RI;
1409
1410 // Could be calling an instruction that effects memory like free().
1411 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001412 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001413
1414 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1415 // Found the previous store make sure it stores to the same location.
1416 if (SI && SI->getPointerOperand() == StorePtr)
1417 // Found the previous store, return its value operand.
1418 return SI->getValueOperand();
1419 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001420 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001421 }
1422
Craig Topperf40110f2014-04-25 05:29:35 +00001423 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001424}
1425
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001426/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001427///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001428/// Note that this is a very risky transform currently. Speculating
1429/// instructions like this is most often not desirable. Instead, there is an MI
1430/// pass which can do it with full awareness of the resource constraints.
1431/// However, some cases are "obvious" and we should do directly. An example of
1432/// this is speculating a single, reasonably cheap instruction.
1433///
1434/// There is only one distinct advantage to flattening the CFG at the IR level:
1435/// it makes very common but simplistic optimizations such as are common in
1436/// instcombine and the DAG combiner more powerful by removing CFG edges and
1437/// modeling their effects with easier to reason about SSA value graphs.
1438///
1439///
1440/// An illustration of this transform is turning this IR:
1441/// \code
1442/// BB:
1443/// %cmp = icmp ult %x, %y
1444/// br i1 %cmp, label %EndBB, label %ThenBB
1445/// ThenBB:
1446/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001447/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001448/// EndBB:
1449/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1450/// ...
1451/// \endcode
1452///
1453/// Into this IR:
1454/// \code
1455/// BB:
1456/// %cmp = icmp ult %x, %y
1457/// %sub = sub %x, %y
1458/// %cond = select i1 %cmp, 0, %sub
1459/// ...
1460/// \endcode
1461///
1462/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001463static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001464 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001465 // Be conservative for now. FP select instruction can often be expensive.
1466 Value *BrCond = BI->getCondition();
1467 if (isa<FCmpInst>(BrCond))
1468 return false;
1469
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001470 BasicBlock *BB = BI->getParent();
1471 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1472
1473 // If ThenBB is actually on the false edge of the conditional branch, remember
1474 // to swap the select operands later.
1475 bool Invert = false;
1476 if (ThenBB != BI->getSuccessor(0)) {
1477 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1478 Invert = true;
1479 }
1480 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1481
Chandler Carruthceff2222013-01-25 05:40:09 +00001482 // Keep a count of how many times instructions are used within CondBB when
1483 // they are candidates for sinking into CondBB. Specifically:
1484 // - They are defined in BB, and
1485 // - They have no side effects, and
1486 // - All of their uses are in CondBB.
1487 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1488
Chandler Carruth7481ca82013-01-24 11:52:58 +00001489 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001490 Value *SpeculatedStoreValue = nullptr;
1491 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001492 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001493 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001494 BBI != BBE; ++BBI) {
1495 Instruction *I = BBI;
1496 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001497 if (isa<DbgInfoIntrinsic>(I))
1498 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001499
Mark Lacey274f48b2015-04-12 18:18:51 +00001500 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001501 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001502 ++SpeculationCost;
1503 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001504 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001505
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001506 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001507 if (!isSafeToSpeculativelyExecute(I) &&
1508 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1509 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001510 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001511 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001512 ComputeSpeculationCost(I, TTI) >
1513 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001514 return false;
1515
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001516 // Store the store speculation candidate.
1517 if (SpeculatedStoreValue)
1518 SpeculatedStore = cast<StoreInst>(I);
1519
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001520 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001521 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001522 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001523 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001524 i != e; ++i) {
1525 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001526 if (!OpI || OpI->getParent() != BB ||
1527 OpI->mayHaveSideEffects())
1528 continue; // Not a candidate for sinking.
1529
1530 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001531 }
1532 }
Evan Cheng89200c92008-06-07 08:52:29 +00001533
Chandler Carruthceff2222013-01-25 05:40:09 +00001534 // Consider any sink candidates which are only used in CondBB as costs for
1535 // speculation. Note, while we iterate over a DenseMap here, we are summing
1536 // and so iteration order isn't significant.
1537 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1538 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1539 I != E; ++I)
1540 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001541 ++SpeculationCost;
1542 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001543 return false;
1544 }
1545
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001546 // Check that the PHI nodes can be converted to selects.
1547 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001548 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001549 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001550 Value *OrigV = PN->getIncomingValueForBlock(BB);
1551 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001552
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001553 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001554 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001555 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001556 continue;
1557
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001558 // Don't convert to selects if we could remove undefined behavior instead.
1559 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1560 passingValueIsAlwaysUndefined(ThenV, PN))
1561 return false;
1562
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001563 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001564 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1565 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1566 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001567 continue; // Known safe and cheap.
1568
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001569 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1570 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001571 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001572 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1573 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
James Molloy7c336572015-02-11 12:15:41 +00001574 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1575 TargetTransformInfo::TCC_Basic;
1576 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00001577 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001578
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001579 // Account for the cost of an unfolded ConstantExpr which could end up
1580 // getting expanded into Instructions.
1581 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001582 // constant expression.
1583 ++SpeculationCost;
1584 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001585 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001586 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001587
1588 // If there are no PHIs to process, bail early. This helps ensure idempotence
1589 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001590 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001591 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001592
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001593 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001594 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001595
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001596 // Insert a select of the value of the speculated store.
1597 if (SpeculatedStoreValue) {
1598 IRBuilder<true, NoFolder> Builder(BI);
1599 Value *TrueV = SpeculatedStore->getValueOperand();
1600 Value *FalseV = SpeculatedStoreValue;
1601 if (Invert)
1602 std::swap(TrueV, FalseV);
1603 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1604 "." + FalseV->getName());
1605 SpeculatedStore->setOperand(0, S);
1606 }
1607
Chandler Carruth7481ca82013-01-24 11:52:58 +00001608 // Hoist the instructions.
1609 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001610 std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001611
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001612 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001613 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001614 for (BasicBlock::iterator I = EndBB->begin();
1615 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1616 unsigned OrigI = PN->getBasicBlockIndex(BB);
1617 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1618 Value *OrigV = PN->getIncomingValue(OrigI);
1619 Value *ThenV = PN->getIncomingValue(ThenI);
1620
1621 // Skip PHIs which are trivial.
1622 if (OrigV == ThenV)
1623 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001624
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001625 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001626 // false value is the preexisting value. Swap them if the branch
1627 // destinations were inverted.
1628 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001629 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001630 std::swap(TrueV, FalseV);
1631 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1632 TrueV->getName() + "." + FalseV->getName());
1633 PN->setIncomingValue(OrigI, V);
1634 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001635 }
1636
Evan Cheng89553cc2008-06-12 21:15:59 +00001637 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001638 return true;
1639}
1640
Tom Stellarde1631dd2013-10-21 20:07:30 +00001641/// \returns True if this block contains a CallInst with the NoDuplicate
1642/// attribute.
1643static bool HasNoDuplicateCall(const BasicBlock *BB) {
1644 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1645 const CallInst *CI = dyn_cast<CallInst>(I);
1646 if (!CI)
1647 continue;
1648 if (CI->cannotDuplicate())
1649 return true;
1650 }
1651 return false;
1652}
1653
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001654/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001655static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1656 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001657 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001658
Devang Patel84fceff2009-03-10 18:00:05 +00001659 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001660 if (isa<DbgInfoIntrinsic>(BBI))
1661 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001662 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001663 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001664
Dale Johannesened6f5a82009-03-12 23:18:09 +00001665 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001666 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001667 for (User *U : BBI->users()) {
1668 Instruction *UI = cast<Instruction>(U);
1669 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001670 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001671
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001672 // Looks ok, continue checking.
1673 }
Chris Lattner6c701062005-09-20 01:48:40 +00001674
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001675 return true;
1676}
1677
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001678/// If we have a conditional branch on a PHI node value that is defined in the
1679/// same block as the branch and if any PHI entries are constants, thread edges
1680/// corresponding to that entry to be branches to their ultimate destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001681static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001682 BasicBlock *BB = BI->getParent();
1683 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001684 // NOTE: we currently cannot transform this case if the PHI node is used
1685 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001686 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1687 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001688
Chris Lattner748f9032005-09-19 23:49:37 +00001689 // Degenerate case of a single entry PHI.
1690 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001691 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001692 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001693 }
1694
1695 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001696 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001697
Tom Stellarde1631dd2013-10-21 20:07:30 +00001698 if (HasNoDuplicateCall(BB)) return false;
1699
Chris Lattner748f9032005-09-19 23:49:37 +00001700 // Okay, this is a simple enough basic block. See if any phi values are
1701 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001702 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001703 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001704 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001705
Chris Lattner4088e2b2010-12-13 01:47:07 +00001706 // Okay, we now know that all edges from PredBB should be revectored to
1707 // branch to RealDest.
1708 BasicBlock *PredBB = PN->getIncomingBlock(i);
1709 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001710
Chris Lattner4088e2b2010-12-13 01:47:07 +00001711 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001712 // Skip if the predecessor's terminator is an indirect branch.
1713 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001714
Chris Lattner4088e2b2010-12-13 01:47:07 +00001715 // The dest block might have PHI nodes, other predecessors and other
1716 // difficult cases. Instead of being smart about this, just insert a new
1717 // block that jumps to the destination block, effectively splitting
1718 // the edge we are about to create.
1719 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1720 RealDest->getName()+".critedge",
1721 RealDest->getParent(), RealDest);
1722 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001723
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001724 // Update PHI nodes.
1725 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001726
1727 // BB may have instructions that are being threaded over. Clone these
1728 // instructions into EdgeBB. We know that there will be no uses of the
1729 // cloned instructions outside of EdgeBB.
1730 BasicBlock::iterator InsertPt = EdgeBB->begin();
1731 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1732 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1733 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1734 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1735 continue;
1736 }
1737 // Clone the instruction.
1738 Instruction *N = BBI->clone();
1739 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001740
Chris Lattner4088e2b2010-12-13 01:47:07 +00001741 // Update operands due to translation.
1742 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1743 i != e; ++i) {
1744 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1745 if (PI != TranslateMap.end())
1746 *i = PI->second;
1747 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001748
Chris Lattner4088e2b2010-12-13 01:47:07 +00001749 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001750 if (Value *V = SimplifyInstruction(N, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00001751 TranslateMap[BBI] = V;
1752 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001753 } else {
1754 // Insert the new instruction into its new home.
1755 EdgeBB->getInstList().insert(InsertPt, N);
1756 if (!BBI->use_empty())
1757 TranslateMap[BBI] = N;
1758 }
1759 }
1760
1761 // Loop over all of the edges from PredBB to BB, changing them to branch
1762 // to EdgeBB instead.
1763 TerminatorInst *PredBBTI = PredBB->getTerminator();
1764 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1765 if (PredBBTI->getSuccessor(i) == BB) {
1766 BB->removePredecessor(PredBB);
1767 PredBBTI->setSuccessor(i, EdgeBB);
1768 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001769
Chris Lattner4088e2b2010-12-13 01:47:07 +00001770 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001771 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001772 }
Chris Lattner748f9032005-09-19 23:49:37 +00001773
1774 return false;
1775}
1776
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001777/// Given a BB that starts with the specified two-entry PHI node,
1778/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001779static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1780 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001781 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1782 // statement", which has a very simple dominance structure. Basically, we
1783 // are trying to find the condition that is being branched on, which
1784 // subsequently causes this merge to happen. We really want control
1785 // dependence information for this check, but simplifycfg can't keep it up
1786 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001787 BasicBlock *BB = PN->getParent();
1788 BasicBlock *IfTrue, *IfFalse;
1789 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001790 if (!IfCond ||
1791 // Don't bother if the branch will be constant folded trivially.
1792 isa<ConstantInt>(IfCond))
1793 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001794
Chris Lattner95adf8f12006-11-18 19:19:36 +00001795 // Okay, we found that we can merge this two-entry phi node into a select.
1796 // Doing so would require us to fold *all* two entry phi nodes in this block.
1797 // At some point this becomes non-profitable (particularly if the target
1798 // doesn't support cmov's). Only do this transformation if there are two or
1799 // fewer PHI nodes in this block.
1800 unsigned NumPhis = 0;
1801 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1802 if (NumPhis > 2)
1803 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001804
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001805 // Loop over the PHI's seeing if we can promote them all to select
1806 // instructions. While we are at it, keep track of the instructions
1807 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001808 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001809 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1810 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00001811 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1812 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001813
Chris Lattner7499b452010-12-14 08:46:09 +00001814 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1815 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001816 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001817 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001818 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001819 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001820 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001821
Peter Collingbournee3511e12011-04-29 18:47:31 +00001822 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001823 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001824 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001825 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001826 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001827 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001828
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001829 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001830 // we ran out of PHIs then we simplified them all.
1831 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001832 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001833
Chris Lattner7499b452010-12-14 08:46:09 +00001834 // Don't fold i1 branches on PHIs which contain binary operators. These can
1835 // often be turned into switches and other things.
1836 if (PN->getType()->isIntegerTy(1) &&
1837 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1838 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1839 isa<BinaryOperator>(IfCond)))
1840 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001841
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001842 // If we all PHI nodes are promotable, check to make sure that all
1843 // instructions in the predecessor blocks can be promoted as well. If
1844 // not, we won't be able to get rid of the control flow, so it's not
1845 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001846 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001847 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1848 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1849 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001850 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001851 } else {
1852 DomBlock = *pred_begin(IfBlock1);
1853 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001854 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001855 // This is not an aggressive instruction that we can promote.
1856 // Because of this, we won't be able to get rid of the control
1857 // flow, so the xform is not worth it.
1858 return false;
1859 }
1860 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001861
Chris Lattner9ac168d2010-12-14 07:41:39 +00001862 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001863 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001864 } else {
1865 DomBlock = *pred_begin(IfBlock2);
1866 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001867 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001868 // This is not an aggressive instruction that we can promote.
1869 // Because of this, we won't be able to get rid of the control
1870 // flow, so the xform is not worth it.
1871 return false;
1872 }
1873 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001874
Chris Lattner9fd838d2010-12-14 07:23:10 +00001875 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001876 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001877
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001878 // If we can still promote the PHI nodes after this gauntlet of tests,
1879 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001880 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001881 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001882
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001883 // Move all 'aggressive' instructions, which are defined in the
1884 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001885 if (IfBlock1)
Chris Lattner7499b452010-12-14 08:46:09 +00001886 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001887 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001888 IfBlock1->getTerminator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001889 if (IfBlock2)
Chris Lattner7499b452010-12-14 08:46:09 +00001890 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001891 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001892 IfBlock2->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001893
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001894 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1895 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001896 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1897 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001898
1899 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001900 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001901 PN->replaceAllUsesWith(NV);
1902 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001903 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001904 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001905
Chris Lattner335f0e42010-12-14 08:01:53 +00001906 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1907 // has been flattened. Change DomBlock to jump directly to our new block to
1908 // avoid other simplifycfg's kicking in on the diamond.
1909 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001910 Builder.SetInsertPoint(OldTI);
1911 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001912 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001913 return true;
1914}
Chris Lattner748f9032005-09-19 23:49:37 +00001915
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001916/// If we found a conditional branch that goes to two returning blocks,
1917/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00001918/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001919static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001920 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001921 assert(BI->isConditional() && "Must be a conditional branch");
1922 BasicBlock *TrueSucc = BI->getSuccessor(0);
1923 BasicBlock *FalseSucc = BI->getSuccessor(1);
1924 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1925 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001926
Chris Lattner86bbf332008-04-24 00:01:19 +00001927 // Check to ensure both blocks are empty (just a return) or optionally empty
1928 // with PHI nodes. If there are other instructions, merging would cause extra
1929 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001930 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001931 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001932 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001933 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001934
Devang Pateldd14e0f2011-05-18 21:33:11 +00001935 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001936 // Okay, we found a branch that is going to two return nodes. If
1937 // there is no return value for this function, just change the
1938 // branch into a return.
1939 if (FalseRet->getNumOperands() == 0) {
1940 TrueSucc->removePredecessor(BI->getParent());
1941 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001942 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001943 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001944 return true;
1945 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001946
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001947 // Otherwise, figure out what the true and false return values are
1948 // so we can insert a new select instruction.
1949 Value *TrueValue = TrueRet->getReturnValue();
1950 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001951
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001952 // Unwrap any PHI nodes in the return blocks.
1953 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1954 if (TVPN->getParent() == TrueSucc)
1955 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1956 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1957 if (FVPN->getParent() == FalseSucc)
1958 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001959
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001960 // In order for this transformation to be safe, we must be able to
1961 // unconditionally execute both operands to the return. This is
1962 // normally the case, but we could have a potentially-trapping
1963 // constant expression that prevents this transformation from being
1964 // safe.
1965 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1966 if (TCV->canTrap())
1967 return false;
1968 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1969 if (FCV->canTrap())
1970 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001971
Chris Lattner86bbf332008-04-24 00:01:19 +00001972 // Okay, we collected all the mapped values and checked them for sanity, and
1973 // defined to really do this transformation. First, update the CFG.
1974 TrueSucc->removePredecessor(BI->getParent());
1975 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001976
Chris Lattner86bbf332008-04-24 00:01:19 +00001977 // Insert select instructions where needed.
1978 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001979 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001980 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001981 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1982 } else if (isa<UndefValue>(TrueValue)) {
1983 TrueValue = FalseValue;
1984 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00001985 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1986 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00001987 }
Chris Lattner86bbf332008-04-24 00:01:19 +00001988 }
1989
Andrew Trickf3cf1932012-08-29 21:46:36 +00001990 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00001991 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1992
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00001993 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001994
David Greene725c7c32010-01-05 01:26:52 +00001995 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00001996 << "\n " << *BI << "NewRet = " << *RI
1997 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001998
Eli Friedmancb61afb2008-12-16 20:54:32 +00001999 EraseTerminatorInstAndDCECond(BI);
2000
Chris Lattner86bbf332008-04-24 00:01:19 +00002001 return true;
2002}
2003
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002004/// Given a conditional BranchInstruction, retrieve the probabilities of the
2005/// branch taking each edge. Fills in the two APInt parameters and returns true,
2006/// or returns false if no or invalid metadata was found.
Juergen Ributzka194350a2014-12-09 17:32:12 +00002007static bool ExtractBranchMetadata(BranchInst *BI,
2008 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2009 assert(BI->isConditional() &&
2010 "Looking for probabilities on unconditional branch?");
2011 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2012 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002013 ConstantInt *CITrue =
2014 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2015 ConstantInt *CIFalse =
2016 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00002017 if (!CITrue || !CIFalse) return false;
2018 ProbTrue = CITrue->getValue().getZExtValue();
2019 ProbFalse = CIFalse->getValue().getZExtValue();
2020 return true;
2021}
2022
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002023/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002024/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002025static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002026 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2027 return false;
2028 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2029 Instruction *PBI = &*I;
2030 // Check whether Inst and PBI generate the same value.
2031 if (Inst->isIdenticalTo(PBI)) {
2032 Inst->replaceAllUsesWith(PBI);
2033 Inst->eraseFromParent();
2034 return true;
2035 }
2036 }
2037 return false;
2038}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002039
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002040/// If this basic block is simple enough, and if a predecessor branches to us
2041/// and one of our successors, fold the block into the predecessor and use
2042/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002043bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002044 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002045
Craig Topperf40110f2014-04-25 05:29:35 +00002046 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002047 if (BI->isConditional())
2048 Cond = dyn_cast<Instruction>(BI->getCondition());
2049 else {
2050 // For unconditional branch, check for a simple CFG pattern, where
2051 // BB has a single predecessor and BB's successor is also its predecessor's
2052 // successor. If such pattern exisits, check for CSE between BB and its
2053 // predecessor.
2054 if (BasicBlock *PB = BB->getSinglePredecessor())
2055 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2056 if (PBI->isConditional() &&
2057 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2058 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2059 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2060 I != E; ) {
2061 Instruction *Curr = I++;
2062 if (isa<CmpInst>(Curr)) {
2063 Cond = Curr;
2064 break;
2065 }
2066 // Quit if we can't remove this instruction.
2067 if (!checkCSEInPredecessor(Curr, PB))
2068 return false;
2069 }
2070 }
2071
Craig Topperf40110f2014-04-25 05:29:35 +00002072 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002073 return false;
2074 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002075
Craig Topperf40110f2014-04-25 05:29:35 +00002076 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2077 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002078 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002079
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002080 // Make sure the instruction after the condition is the cond branch.
2081 BasicBlock::iterator CondIt = Cond; ++CondIt;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002082
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002083 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002084 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002085
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002086 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002087 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002088
Jingyue Wufc029672014-09-30 22:23:38 +00002089 // Only allow this transformation if computing the condition doesn't involve
2090 // too many instructions and these involved instructions can be executed
2091 // unconditionally. We denote all involved instructions except the condition
2092 // as "bonus instructions", and only allow this transformation when the
2093 // number of the bonus instructions does not exceed a certain threshold.
2094 unsigned NumBonusInsts = 0;
2095 for (auto I = BB->begin(); Cond != I; ++I) {
2096 // Ignore dbg intrinsics.
2097 if (isa<DbgInfoIntrinsic>(I))
2098 continue;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002099 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I))
Jingyue Wufc029672014-09-30 22:23:38 +00002100 return false;
2101 // I has only one use and can be executed unconditionally.
2102 Instruction *User = dyn_cast<Instruction>(I->user_back());
2103 if (User == nullptr || User->getParent() != BB)
2104 return false;
2105 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2106 // to use any other instruction, User must be an instruction between next(I)
2107 // and Cond.
2108 ++NumBonusInsts;
2109 // Early exits once we reach the limit.
2110 if (NumBonusInsts > BonusInstThreshold)
2111 return false;
2112 }
2113
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002114 // Cond is known to be a compare or binary operator. Check to make sure that
2115 // neither operand is a potentially-trapping constant expression.
2116 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2117 if (CE->canTrap())
2118 return false;
2119 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2120 if (CE->canTrap())
2121 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002122
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002123 // Finally, don't infinitely unroll conditional loops.
2124 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002125 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002126 if (TrueDest == BB || FalseDest == BB)
2127 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002128
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002129 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2130 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002131 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002132
Chris Lattner80b03a12008-07-13 22:23:11 +00002133 // Check that we have two conditional branches. If there is a PHI node in
2134 // the common successor, verify that the same value flows in from both
2135 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002136 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002137 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002138 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002139 !SafeToMergeTerminators(BI, PBI)) ||
2140 (!BI->isConditional() &&
2141 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002142 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002143
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002144 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002145 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002146 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002147
Manman Rend33f4ef2012-06-13 05:43:29 +00002148 if (BI->isConditional()) {
2149 if (PBI->getSuccessor(0) == TrueDest)
2150 Opc = Instruction::Or;
2151 else if (PBI->getSuccessor(1) == FalseDest)
2152 Opc = Instruction::And;
2153 else if (PBI->getSuccessor(0) == FalseDest)
2154 Opc = Instruction::And, InvertPredCond = true;
2155 else if (PBI->getSuccessor(1) == TrueDest)
2156 Opc = Instruction::Or, InvertPredCond = true;
2157 else
2158 continue;
2159 } else {
2160 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2161 continue;
2162 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002163
David Greene725c7c32010-01-05 01:26:52 +00002164 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002165 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002166
Chris Lattner55eaae12008-07-13 21:20:19 +00002167 // If we need to invert the condition in the pred block to match, do so now.
2168 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002169 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002170
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002171 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2172 CmpInst *CI = cast<CmpInst>(NewCond);
2173 CI->setPredicate(CI->getInversePredicate());
2174 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002175 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002176 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002177 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002178
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002179 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002180 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002181 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002182
Jingyue Wufc029672014-09-30 22:23:38 +00002183 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002184 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002185 // bonus instructions to a predecessor block.
2186 ValueToValueMapTy VMap; // maps original values to cloned values
2187 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002188 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002189 // instructions.
2190 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2191 if (isa<DbgInfoIntrinsic>(BonusInst))
2192 continue;
2193 Instruction *NewBonusInst = BonusInst->clone();
2194 RemapInstruction(NewBonusInst, VMap,
2195 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2196 VMap[BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002197
2198 // If we moved a load, we cannot any longer claim any knowledge about
2199 // its potential value. The previous information might have been valid
2200 // only given the branch precondition.
2201 // For an analogous reason, we must also drop all the metadata whose
2202 // semantics we don't understand.
Jingyue Wufc029672014-09-30 22:23:38 +00002203 NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
Rafael Espindolaab73c492014-01-28 16:56:46 +00002204
Jingyue Wufc029672014-09-30 22:23:38 +00002205 PredBlock->getInstList().insert(PBI, NewBonusInst);
2206 NewBonusInst->takeName(BonusInst);
2207 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002208 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002209
Chris Lattner55eaae12008-07-13 21:20:19 +00002210 // Clone Cond into the predecessor basic block, and or/and the
2211 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002212 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002213 RemapInstruction(New, VMap,
2214 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Chris Lattner55eaae12008-07-13 21:20:19 +00002215 PredBlock->getInstList().insert(PBI, New);
2216 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002217 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002218
Manman Rend33f4ef2012-06-13 05:43:29 +00002219 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002220 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002221 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002222 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002223 PBI->setCondition(NewCond);
2224
Manman Renbfb9d432012-09-15 00:39:57 +00002225 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002226 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2227 PredFalseWeight);
2228 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2229 SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002230 SmallVector<uint64_t, 8> NewWeights;
2231
Manman Rend33f4ef2012-06-13 05:43:29 +00002232 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002233 if (PredHasWeights && SuccHasWeights) {
2234 // PBI: br i1 %x, BB, FalseDest
2235 // BI: br i1 %y, TrueDest, FalseDest
2236 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2237 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2238 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2239 // TrueWeight for PBI * FalseWeight for BI.
2240 // We assume that total weights of a BranchInst can fit into 32 bits.
2241 // Therefore, we will not have overflow using 64-bit arithmetic.
2242 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2243 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2244 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002245 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2246 PBI->setSuccessor(0, TrueDest);
2247 }
2248 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002249 if (PredHasWeights && SuccHasWeights) {
2250 // PBI: br i1 %x, TrueDest, BB
2251 // BI: br i1 %y, TrueDest, FalseDest
2252 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2253 // FalseWeight for PBI * TrueWeight for BI.
2254 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2255 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2256 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2257 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2258 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002259 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2260 PBI->setSuccessor(1, FalseDest);
2261 }
Manman Renbfb9d432012-09-15 00:39:57 +00002262 if (NewWeights.size() == 2) {
2263 // Halve the weights if any of them cannot fit in an uint32_t
2264 FitWeights(NewWeights);
2265
2266 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2267 PBI->setMetadata(LLVMContext::MD_prof,
2268 MDBuilder(BI->getContext()).
2269 createBranchWeights(MDWeights));
2270 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002271 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002272 } else {
2273 // Update PHI nodes in the common successors.
2274 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002275 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002276 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2277 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002278 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002279 if (PBI->getSuccessor(0) == TrueDest) {
2280 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2281 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2282 // is false: !PBI_Cond and BI_Value
2283 Instruction *NotCond =
2284 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2285 "not.cond"));
2286 MergedCond =
2287 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2288 NotCond, New,
2289 "and.cond"));
2290 if (PBI_C->isOne())
2291 MergedCond =
2292 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2293 PBI->getCondition(), MergedCond,
2294 "or.cond"));
2295 } else {
2296 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2297 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2298 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002299 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002300 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2301 PBI->getCondition(), New,
2302 "and.cond"));
2303 if (PBI_C->isOne()) {
2304 Instruction *NotCond =
2305 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2306 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002307 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002308 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2309 NotCond, MergedCond,
2310 "or.cond"));
2311 }
2312 }
2313 // Update PHI Node.
2314 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2315 MergedCond);
2316 }
2317 // Change PBI from Conditional to Unconditional.
2318 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2319 EraseTerminatorInstAndDCECond(PBI);
2320 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002321 }
Devang Pateld715ec82011-04-06 22:37:20 +00002322
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002323 // TODO: If BB is reachable from all paths through PredBlock, then we
2324 // could replace PBI's branch probabilities with BI's.
2325
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002326 // Copy any debug value intrinsics into the end of PredBlock.
2327 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2328 if (isa<DbgInfoIntrinsic>(*I))
2329 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002330
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002331 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002332 }
2333 return false;
2334}
2335
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002336/// If we have a conditional branch as a predecessor of another block,
2337/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00002338/// that PBI and BI are both conditional branches, and BI is in one of the
2339/// successor blocks of PBI - PBI branches to BI.
2340static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2341 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);
Owen Anderson55f1c092009-08-13 21:58:54 +00002364 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Jay Foad52131342011-03-30 11:28:46 +00002365 std::distance(PB, PE),
Chris Lattner9aada1d2008-07-13 21:53:26 +00002366 BI->getCondition()->getName() + ".pr",
2367 BB->begin());
Chris Lattner5eed3722008-07-13 21:55:46 +00002368 // Okay, we're going to insert the PHI node. Since PBI is not the only
2369 // predecessor, compute the PHI'd conditional value for all of the preds.
2370 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002371 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002372 BasicBlock *P = *PI;
2373 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002374 PBI != BI && PBI->isConditional() &&
2375 PBI->getCondition() == BI->getCondition() &&
2376 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2377 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002378 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002379 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002380 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002381 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002382 }
Gabor Greif8629f122010-07-12 10:59:23 +00002383 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002384
Chris Lattner9aada1d2008-07-13 21:53:26 +00002385 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002386 return true;
2387 }
2388 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002389
Chris Lattner9aada1d2008-07-13 21:53:26 +00002390 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002391 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002392 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002393 BasicBlock::iterator BBI = BB->begin();
2394 // Ignore dbg intrinsics.
2395 while (isa<DbgInfoIntrinsic>(BBI))
2396 ++BBI;
2397 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002398 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002399
Andrew Trickf3cf1932012-08-29 21:46:36 +00002400
Chris Lattnerc59945b2009-01-20 01:15:41 +00002401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2402 if (CE->canTrap())
2403 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002404
Chris Lattner834ab4e2008-07-13 22:04:41 +00002405 int PBIOp, BIOp;
2406 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2407 PBIOp = BIOp = 0;
2408 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2409 PBIOp = 0, BIOp = 1;
2410 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2411 PBIOp = 1, BIOp = 0;
2412 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2413 PBIOp = BIOp = 1;
2414 else
2415 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002416
Chris Lattner834ab4e2008-07-13 22:04:41 +00002417 // Check to make sure that the other destination of this branch
2418 // isn't BB itself. If so, this is an infinite loop that will
2419 // keep getting unwound.
2420 if (PBI->getSuccessor(PBIOp) == BB)
2421 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002422
2423 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002424 // insertion of a large number of select instructions. For targets
2425 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002426
Sanjay Patela932da82014-07-07 21:19:00 +00002427 // Also do not perform this transformation if any phi node in the common
2428 // destination block can trap when reached by BB or PBB (PR17073). In that
2429 // case, it would be unsafe to hoist the operation into a select instruction.
2430
2431 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002432 unsigned NumPhis = 0;
2433 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002434 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002435 if (NumPhis > 2) // Disable this xform.
2436 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002437
Sanjay Patela932da82014-07-07 21:19:00 +00002438 PHINode *PN = cast<PHINode>(II);
2439 Value *BIV = PN->getIncomingValueForBlock(BB);
2440 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2441 if (CE->canTrap())
2442 return false;
2443
2444 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2445 Value *PBIV = PN->getIncomingValue(PBBIdx);
2446 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2447 if (CE->canTrap())
2448 return false;
2449 }
2450
Chris Lattner834ab4e2008-07-13 22:04:41 +00002451 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002452 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002453
David Greene725c7c32010-01-05 01:26:52 +00002454 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002455 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002456
2457
Chris Lattner80b03a12008-07-13 22:23:11 +00002458 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2459 // branch in it, where one edge (OtherDest) goes back to itself but the other
2460 // exits. We don't *know* that the program avoids the infinite loop
2461 // (even though that seems likely). If we do this xform naively, we'll end up
2462 // recursively unpeeling the loop. Since we know that (after the xform is
2463 // done) that the block *is* infinite if reached, we just make it an obviously
2464 // infinite loop with no cond branch.
2465 if (OtherDest == BB) {
2466 // Insert it at the end of the function, because it's either code,
2467 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002468 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2469 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002470 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2471 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002472 }
2473
David Greene725c7c32010-01-05 01:26:52 +00002474 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002475
Chris Lattner834ab4e2008-07-13 22:04:41 +00002476 // BI may have other predecessors. Because of this, we leave
2477 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002478
Chris Lattner834ab4e2008-07-13 22:04:41 +00002479 // Make sure we get to CommonDest on True&True directions.
2480 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002481 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002482 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002483 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2484
Chris Lattner834ab4e2008-07-13 22:04:41 +00002485 Value *BICond = BI->getCondition();
2486 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002487 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2488
Chris Lattner834ab4e2008-07-13 22:04:41 +00002489 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002490 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002491
Chris Lattner834ab4e2008-07-13 22:04:41 +00002492 // Modify PBI to branch on the new condition to the new dests.
2493 PBI->setCondition(Cond);
2494 PBI->setSuccessor(0, CommonDest);
2495 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002496
Manman Ren2d4c10f2012-09-17 21:30:40 +00002497 // Update branch weight for PBI.
2498 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002499 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2500 PredFalseWeight);
2501 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2502 SuccFalseWeight);
Manman Ren2d4c10f2012-09-17 21:30:40 +00002503 if (PredHasWeights && SuccHasWeights) {
2504 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2505 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2506 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2507 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2508 // The weight to CommonDest should be PredCommon * SuccTotal +
2509 // PredOther * SuccCommon.
2510 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00002511 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2512 PredOther * SuccCommon,
2513 PredOther * SuccOther};
Manman Ren2d4c10f2012-09-17 21:30:40 +00002514 // Halve the weights if any of them cannot fit in an uint32_t
2515 FitWeights(NewWeights);
2516
Manman Ren2d4c10f2012-09-17 21:30:40 +00002517 PBI->setMetadata(LLVMContext::MD_prof,
Benjamin Kramerea68a942015-02-19 15:26:17 +00002518 MDBuilder(BI->getContext())
2519 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00002520 }
2521
Chris Lattner834ab4e2008-07-13 22:04:41 +00002522 // OtherDest may have phi nodes. If so, add an entry from PBI's
2523 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002524 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002525
Chris Lattner834ab4e2008-07-13 22:04:41 +00002526 // We know that the CommonDest already had an edge from PBI to
2527 // it. If it has PHIs though, the PHIs may have different
2528 // entries for BB and PBI's BB. If so, insert a select to make
2529 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002530 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002531 for (BasicBlock::iterator II = CommonDest->begin();
2532 (PN = dyn_cast<PHINode>(II)); ++II) {
2533 Value *BIV = PN->getIncomingValueForBlock(BB);
2534 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2535 Value *PBIV = PN->getIncomingValue(PBBIdx);
2536 if (BIV != PBIV) {
2537 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002538 Value *NV = cast<SelectInst>
2539 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002540 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002541 }
2542 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002543
David Greene725c7c32010-01-05 01:26:52 +00002544 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2545 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002546
Chris Lattner834ab4e2008-07-13 22:04:41 +00002547 // This basic block is probably dead. We know it has at least
2548 // one fewer predecessor.
2549 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002550}
2551
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002552// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2553// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00002554// Takes care of updating the successors and removing the old terminator.
2555// Also makes sure not to introduce new successors by assuming that edges to
2556// non-successor TrueBBs and FalseBBs aren't reachable.
2557static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002558 BasicBlock *TrueBB, BasicBlock *FalseBB,
2559 uint32_t TrueWeight,
2560 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002561 // Remove any superfluous successor edges from the CFG.
2562 // First, figure out which successors to preserve.
2563 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2564 // successor.
2565 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002566 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002567
2568 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00002569 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002570 // Make sure only to keep exactly one copy of each edge.
2571 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002572 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002573 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002574 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002575 else
2576 Succ->removePredecessor(OldTerm->getParent());
2577 }
2578
Devang Patel2c2ea222011-05-18 18:43:31 +00002579 IRBuilder<> Builder(OldTerm);
2580 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2581
Frits van Bommel8e158492011-01-11 12:52:11 +00002582 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002583 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002584 if (TrueBB == FalseBB)
2585 // We were only looking for one successor, and it was present.
2586 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002587 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002588 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002589 // We found both of the successors we were looking for.
2590 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002591 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2592 if (TrueWeight != FalseWeight)
2593 NewBI->setMetadata(LLVMContext::MD_prof,
2594 MDBuilder(OldTerm->getContext()).
2595 createBranchWeights(TrueWeight, FalseWeight));
2596 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002597 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2598 // Neither of the selected blocks were successors, so this
2599 // terminator must be unreachable.
2600 new UnreachableInst(OldTerm->getContext(), OldTerm);
2601 } else {
2602 // One of the selected values was a successor, but the other wasn't.
2603 // Insert an unconditional branch to the one that was found;
2604 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002605 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002606 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002607 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002608 else
2609 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002610 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002611 }
2612
2613 EraseTerminatorInstAndDCECond(OldTerm);
2614 return true;
2615}
2616
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002617// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00002618// (switch (select cond, X, Y)) on constant X, Y
2619// with a branch - conditional if X and Y lead to distinct BBs,
2620// unconditional otherwise.
2621static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2622 // Check for constant integer values in the select.
2623 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2624 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2625 if (!TrueVal || !FalseVal)
2626 return false;
2627
2628 // Find the relevant condition and destinations.
2629 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002630 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2631 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002632
Manman Ren774246a2012-09-17 22:28:55 +00002633 // Get weight for TrueBB and FalseBB.
2634 uint32_t TrueWeight = 0, FalseWeight = 0;
2635 SmallVector<uint64_t, 8> Weights;
2636 bool HasWeights = HasBranchWeights(SI);
2637 if (HasWeights) {
2638 GetBranchWeights(SI, Weights);
2639 if (Weights.size() == 1 + SI->getNumCases()) {
2640 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2641 getSuccessorIndex()];
2642 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2643 getSuccessorIndex()];
2644 }
2645 }
2646
Frits van Bommel8ae07992011-02-28 09:44:07 +00002647 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002648 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2649 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002650}
2651
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002652// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002653// (indirectbr (select cond, blockaddress(@fn, BlockA),
2654// blockaddress(@fn, BlockB)))
2655// with
2656// (br cond, BlockA, BlockB).
2657static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2658 // Check that both operands of the select are block addresses.
2659 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2660 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2661 if (!TBA || !FBA)
2662 return false;
2663
2664 // Extract the actual blocks.
2665 BasicBlock *TrueBB = TBA->getBasicBlock();
2666 BasicBlock *FalseBB = FBA->getBasicBlock();
2667
Frits van Bommel8e158492011-01-11 12:52:11 +00002668 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002669 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2670 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002671}
2672
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002673/// This is called when we find an icmp instruction
2674/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002675/// block that ends with an uncond branch. We are looking for a very specific
2676/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2677/// this case, we merge the first two "or's of icmp" into a switch, but then the
2678/// default value goes to an uncond block with a seteq in it, we get something
2679/// like:
2680///
2681/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2682/// DEFAULT:
2683/// %tmp = icmp eq i8 %A, 92
2684/// br label %end
2685/// end:
2686/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00002687///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002688/// We prefer to split the edge to 'end' so that there is a true/false entry to
2689/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00002690static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002691 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
2692 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
2693 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002694 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00002695
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002696 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2697 // complex.
2698 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2699
2700 Value *V = ICI->getOperand(0);
2701 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002702
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002703 // The pattern we're looking for is where our only predecessor is a switch on
2704 // 'V' and this block is the default case for the switch. In this case we can
2705 // fold the compared value into the switch to simplify things.
2706 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00002707 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002708
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002709 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2710 if (SI->getCondition() != V)
2711 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002712
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002713 // If BB is reachable on a non-default case, then we simply know the value of
2714 // V in this block. Substitute it and constant fold the icmp instruction
2715 // away.
2716 if (SI->getDefaultDest() != BB) {
2717 ConstantInt *VVal = SI->findCaseDest(BB);
2718 assert(VVal && "Should have a unique destination value");
2719 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002720
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002721 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00002722 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002723 ICI->eraseFromParent();
2724 }
2725 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002726 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002727 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002728
Chris Lattner62cc76e2010-12-13 03:43:57 +00002729 // Ok, the block is reachable from the default dest. If the constant we're
2730 // comparing exists in one of the other edges, then we can constant fold ICI
2731 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002732 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00002733 Value *V;
2734 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2735 V = ConstantInt::getFalse(BB->getContext());
2736 else
2737 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002738
Chris Lattner62cc76e2010-12-13 03:43:57 +00002739 ICI->replaceAllUsesWith(V);
2740 ICI->eraseFromParent();
2741 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002742 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00002743 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002744
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002745 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2746 // the block.
2747 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00002748 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00002749 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002750 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2751 return false;
2752
2753 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2754 // true in the PHI.
2755 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2756 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2757
2758 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2759 std::swap(DefaultCst, NewCst);
2760
2761 // Replace ICI (which is used by the PHI for the default value) with true or
2762 // false depending on if it is EQ or NE.
2763 ICI->replaceAllUsesWith(DefaultCst);
2764 ICI->eraseFromParent();
2765
2766 // Okay, the switch goes to this block on a default value. Add an edge from
2767 // the switch to the merge point on the compared value.
2768 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2769 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00002770 SmallVector<uint64_t, 8> Weights;
2771 bool HasWeights = HasBranchWeights(SI);
2772 if (HasWeights) {
2773 GetBranchWeights(SI, Weights);
2774 if (Weights.size() == 1 + SI->getNumCases()) {
2775 // Split weight for default case to case for "Cst".
2776 Weights[0] = (Weights[0]+1) >> 1;
2777 Weights.push_back(Weights[0]);
2778
2779 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2780 SI->setMetadata(LLVMContext::MD_prof,
2781 MDBuilder(SI->getContext()).
2782 createBranchWeights(MDWeights));
2783 }
2784 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002785 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002786
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002787 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00002788 Builder.SetInsertPoint(NewBB);
2789 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2790 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002791 PHIUse->addIncoming(NewCst, NewBB);
2792 return true;
2793}
2794
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002795/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00002796/// Check to see if it is branching on an or/and chain of icmp instructions, and
2797/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002798static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
2799 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00002800 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00002801 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002802
Chris Lattnera69c4432010-12-13 05:03:41 +00002803 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2804 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2805 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002806
Mehdi Amini9a25cb82014-11-19 20:09:11 +00002807 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00002808 ConstantComparesGatherer ConstantCompare(Cond, DL);
2809 // Unpack the result
2810 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
2811 Value *CompVal = ConstantCompare.CompValue;
2812 unsigned UsedICmps = ConstantCompare.UsedICmps;
2813 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002814
Chris Lattnera69c4432010-12-13 05:03:41 +00002815 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00002816 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00002817
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002818 // Avoid turning single icmps into a switch.
2819 if (UsedICmps <= 1)
2820 return false;
2821
Mehdi Aminiffd01002014-11-20 22:40:25 +00002822 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
2823
Chris Lattnera69c4432010-12-13 05:03:41 +00002824 // There might be duplicate constants in the list, which the switch
2825 // instruction can't handle, remove them now.
2826 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2827 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002828
Chris Lattnera69c4432010-12-13 05:03:41 +00002829 // If Extra was used, we require at least two switch values to do the
2830 // transformation. A switch with one value is just an cond branch.
2831 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002832
Andrew Trick3051aa12012-08-29 21:46:38 +00002833 // TODO: Preserve branch weight metadata, similarly to how
2834 // FoldValueComparisonIntoPredecessors preserves it.
2835
Chris Lattnera69c4432010-12-13 05:03:41 +00002836 // Figure out which block is which destination.
2837 BasicBlock *DefaultBB = BI->getSuccessor(1);
2838 BasicBlock *EdgeBB = BI->getSuccessor(0);
2839 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002840
Chris Lattnera69c4432010-12-13 05:03:41 +00002841 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002842
Chris Lattnerd7beca32010-12-14 06:17:25 +00002843 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002844 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002845
Chris Lattnera69c4432010-12-13 05:03:41 +00002846 // If there are any extra values that couldn't be folded into the switch
2847 // then we evaluate them with an explicit branch first. Split the block
2848 // right before the condbr to handle it.
2849 if (ExtraCase) {
2850 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2851 // 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());
2908 if (RI->getValue() != LPInst)
2909 // Not a landing pad, or the resume is not unwinding the exception that
2910 // caused control to branch here.
2911 return false;
2912
2913 // Check that there are no other instructions except for debug intrinsics.
2914 BasicBlock::iterator I = LPInst, E = RI;
2915 while (++I != E)
2916 if (!isa<DbgInfoIntrinsic>(I))
2917 return false;
2918
2919 // Turn all invokes that unwind here into calls and delete the basic block.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002920 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2921 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
Duncan Sands29192d02011-09-05 12:57:57 +00002922 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
2923 // Insert a call instruction before the invoke.
2924 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2925 Call->takeName(II);
2926 Call->setCallingConv(II->getCallingConv());
2927 Call->setAttributes(II->getAttributes());
2928 Call->setDebugLoc(II->getDebugLoc());
2929
2930 // Anything that used the value produced by the invoke instruction now uses
2931 // the value produced by the call instruction. Note that we do this even
2932 // for void functions and calls with no uses so that the callgraph edge is
2933 // updated.
2934 II->replaceAllUsesWith(Call);
2935 BB->removePredecessor(II->getParent());
2936
2937 // Insert a branch to the normal destination right before the invoke.
2938 BranchInst::Create(II->getNormalDest(), II);
2939
2940 // Finally, delete the invoke instruction!
2941 II->eraseFromParent();
2942 }
2943
Reid Klecknerf12b3342015-01-22 19:29:46 +00002944 // The landingpad is now unreachable. Zap it.
2945 BB->eraseFromParent();
2946 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00002947}
2948
Devang Pateldd14e0f2011-05-18 21:33:11 +00002949bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002950 BasicBlock *BB = RI->getParent();
2951 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002952
Chris Lattner25c3af32010-12-13 06:25:44 +00002953 // Find predecessors that end with branches.
2954 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2955 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002956 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2957 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00002958 TerminatorInst *PTI = P->getTerminator();
2959 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2960 if (BI->isUnconditional())
2961 UncondBranchPreds.push_back(P);
2962 else
2963 CondBranchPreds.push_back(BI);
2964 }
2965 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002966
Chris Lattner25c3af32010-12-13 06:25:44 +00002967 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00002968 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002969 while (!UncondBranchPreds.empty()) {
2970 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2971 DEBUG(dbgs() << "FOLDING: " << *BB
2972 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00002973 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00002974 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002975
Chris Lattner25c3af32010-12-13 06:25:44 +00002976 // If we eliminated all predecessors of the block, delete the block now.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00002977 if (pred_empty(BB))
Chris Lattner25c3af32010-12-13 06:25:44 +00002978 // We know there are no successors, so just nuke the block.
2979 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002980
Chris Lattner25c3af32010-12-13 06:25:44 +00002981 return true;
2982 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002983
Chris Lattner25c3af32010-12-13 06:25:44 +00002984 // Check out all of the conditional branches going to this return
2985 // instruction. If any of them just select between returns, change the
2986 // branch itself into a select/return pair.
2987 while (!CondBranchPreds.empty()) {
2988 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002989
Chris Lattner25c3af32010-12-13 06:25:44 +00002990 // Check to see if the non-BB successor is also a return block.
2991 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2992 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00002993 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00002994 return true;
2995 }
2996 return false;
2997}
2998
Chris Lattner25c3af32010-12-13 06:25:44 +00002999bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3000 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003001
Chris Lattner25c3af32010-12-13 06:25:44 +00003002 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003003
Chris Lattner25c3af32010-12-13 06:25:44 +00003004 // If there are any instructions immediately before the unreachable that can
3005 // be removed, do so.
3006 while (UI != BB->begin()) {
3007 BasicBlock::iterator BBI = UI;
3008 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003009 // Do not delete instructions that can have side effects which might cause
3010 // the unreachable to not be reachable; specifically, calls and volatile
3011 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003012 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003013
3014 if (BBI->mayHaveSideEffects()) {
3015 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3016 if (SI->isVolatile())
3017 break;
3018 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3019 if (LI->isVolatile())
3020 break;
3021 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3022 if (RMWI->isVolatile())
3023 break;
3024 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3025 if (CXI->isVolatile())
3026 break;
3027 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3028 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003029 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003030 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003031 // Note that deleting LandingPad's here is in fact okay, although it
3032 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3033 // all the predecessors of this block will be the unwind edges of Invokes,
3034 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003035 }
3036
Eli Friedmanaac35b32011-03-09 00:48:33 +00003037 // Delete this instruction (any uses are guaranteed to be dead)
3038 if (!BBI->use_empty())
3039 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003040 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003041 Changed = true;
3042 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003043
Chris Lattner25c3af32010-12-13 06:25:44 +00003044 // If the unreachable instruction is the first in the block, take a gander
3045 // at all of the predecessors of this instruction, and simplify them.
3046 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003047
Chris Lattner25c3af32010-12-13 06:25:44 +00003048 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3049 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3050 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003051 IRBuilder<> Builder(TI);
Chris Lattner25c3af32010-12-13 06:25:44 +00003052 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3053 if (BI->isUnconditional()) {
3054 if (BI->getSuccessor(0) == BB) {
3055 new UnreachableInst(TI->getContext(), TI);
3056 TI->eraseFromParent();
3057 Changed = true;
3058 }
3059 } else {
3060 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003061 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003062 EraseTerminatorInstAndDCECond(BI);
3063 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003064 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003065 EraseTerminatorInstAndDCECond(BI);
3066 Changed = true;
3067 }
3068 }
3069 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003070 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003071 i != e; ++i)
3072 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003073 BB->removePredecessor(SI->getParent());
3074 SI->removeCase(i);
3075 --i; --e;
3076 Changed = true;
3077 }
Chris Lattner25c3af32010-12-13 06:25:44 +00003078 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3079 if (II->getUnwindDest() == BB) {
3080 // Convert the invoke to a call instruction. This would be a good
3081 // place to note that the call does not throw though.
Devang Patel31458a02011-05-19 00:09:21 +00003082 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
Chris Lattner25c3af32010-12-13 06:25:44 +00003083 II->removeFromParent(); // Take out of symbol table
Andrew Trickf3cf1932012-08-29 21:46:36 +00003084
Chris Lattner25c3af32010-12-13 06:25:44 +00003085 // Insert the call now...
3086 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Devang Patel31458a02011-05-19 00:09:21 +00003087 Builder.SetInsertPoint(BI);
3088 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Jay Foad5bd375a2011-07-15 08:37:34 +00003089 Args, II->getName());
Chris Lattner25c3af32010-12-13 06:25:44 +00003090 CI->setCallingConv(II->getCallingConv());
3091 CI->setAttributes(II->getAttributes());
3092 // If the invoke produced a value, the call does now instead.
3093 II->replaceAllUsesWith(CI);
3094 delete II;
3095 Changed = true;
3096 }
3097 }
3098 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003099
Chris Lattner25c3af32010-12-13 06:25:44 +00003100 // If this block is now dead, remove it.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003101 if (pred_empty(BB) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00003102 BB != &BB->getParent()->getEntryBlock()) {
3103 // We know there are no successors, so just nuke the block.
3104 BB->eraseFromParent();
3105 return true;
3106 }
3107
3108 return Changed;
3109}
3110
Hans Wennborg68000082015-01-26 19:52:32 +00003111static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3112 assert(Cases.size() >= 1);
3113
3114 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3115 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3116 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3117 return false;
3118 }
3119 return true;
3120}
3121
3122/// Turn a switch with two reachable destinations into an integer range
3123/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003124static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003125 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003126
Hans Wennborg68000082015-01-26 19:52:32 +00003127 bool HasDefault =
3128 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003129
Hans Wennborg68000082015-01-26 19:52:32 +00003130 // Partition the cases into two sets with different destinations.
3131 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3132 BasicBlock *DestB = nullptr;
3133 SmallVector <ConstantInt *, 16> CasesA;
3134 SmallVector <ConstantInt *, 16> CasesB;
3135
3136 for (SwitchInst::CaseIt I : SI->cases()) {
3137 BasicBlock *Dest = I.getCaseSuccessor();
3138 if (!DestA) DestA = Dest;
3139 if (Dest == DestA) {
3140 CasesA.push_back(I.getCaseValue());
3141 continue;
3142 }
3143 if (!DestB) DestB = Dest;
3144 if (Dest == DestB) {
3145 CasesB.push_back(I.getCaseValue());
3146 continue;
3147 }
3148 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003149 }
3150
Hans Wennborg68000082015-01-26 19:52:32 +00003151 assert(DestA && DestB && "Single-destination switch should have been folded.");
3152 assert(DestA != DestB);
3153 assert(DestB != SI->getDefaultDest());
3154 assert(!CasesB.empty() && "There must be non-default cases.");
3155 assert(!CasesA.empty() || HasDefault);
3156
3157 // Figure out if one of the sets of cases form a contiguous range.
3158 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3159 BasicBlock *ContiguousDest = nullptr;
3160 BasicBlock *OtherDest = nullptr;
3161 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3162 ContiguousCases = &CasesA;
3163 ContiguousDest = DestA;
3164 OtherDest = DestB;
3165 } else if (CasesAreContiguous(CasesB)) {
3166 ContiguousCases = &CasesB;
3167 ContiguousDest = DestB;
3168 OtherDest = DestA;
3169 } else
3170 return false;
3171
3172 // Start building the compare and branch.
3173
3174 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3175 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003176
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003177 Value *Sub = SI->getCondition();
3178 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00003179 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3180
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003181 Value *Cmp;
3182 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00003183 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003184 Cmp = ConstantInt::getTrue(SI->getContext());
3185 else
3186 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00003187 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003188
Manman Ren56575552012-09-18 00:47:33 +00003189 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00003190 if (HasBranchWeights(SI)) {
3191 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00003192 GetBranchWeights(SI, Weights);
3193 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00003194 uint64_t TrueWeight = 0;
3195 uint64_t FalseWeight = 0;
3196 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3197 if (SI->getSuccessor(I) == ContiguousDest)
3198 TrueWeight += Weights[I];
3199 else
3200 FalseWeight += Weights[I];
3201 }
3202 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3203 TrueWeight /= 2;
3204 FalseWeight /= 2;
3205 }
Manman Ren56575552012-09-18 00:47:33 +00003206 NewBI->setMetadata(LLVMContext::MD_prof,
Hans Wennborg68000082015-01-26 19:52:32 +00003207 MDBuilder(SI->getContext()).createBranchWeights(
3208 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00003209 }
3210 }
3211
Hans Wennborg68000082015-01-26 19:52:32 +00003212 // Prune obsolete incoming values off the successors' PHI nodes.
3213 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3214 unsigned PreviousEdges = ContiguousCases->size();
3215 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3216 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003217 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3218 }
Hans Wennborg68000082015-01-26 19:52:32 +00003219 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3220 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3221 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3222 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3223 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3224 }
3225
3226 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003227 SI->eraseFromParent();
3228
3229 return true;
3230}
Chris Lattner25c3af32010-12-13 06:25:44 +00003231
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003232/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003233/// and use it to remove dead cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003234static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3235 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003236 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003237 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003238 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003239 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003240
3241 // Gather dead cases.
3242 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003243 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003244 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3245 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3246 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003247 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003248 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003249 }
3250 }
3251
Manman Ren56575552012-09-18 00:47:33 +00003252 SmallVector<uint64_t, 8> Weights;
3253 bool HasWeight = HasBranchWeights(SI);
3254 if (HasWeight) {
3255 GetBranchWeights(SI, Weights);
3256 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3257 }
3258
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003259 // Remove dead cases from the switch.
3260 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003261 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003262 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003263 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003264 if (HasWeight) {
3265 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3266 Weights.pop_back();
3267 }
3268
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003269 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003270 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003271 SI->removeCase(Case);
3272 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003273 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003274 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3275 SI->setMetadata(LLVMContext::MD_prof,
3276 MDBuilder(SI->getParent()->getContext()).
3277 createBranchWeights(MDWeights));
3278 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003279
3280 return !DeadCases.empty();
3281}
3282
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003283/// If BB would be eligible for simplification by
3284/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003285/// by an unconditional branch), look at the phi node for BB in the successor
3286/// block and see if the incoming value is equal to CaseValue. If so, return
3287/// the phi node, and set PhiIndex to BB's index in the phi node.
3288static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3289 BasicBlock *BB,
3290 int *PhiIndex) {
3291 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003292 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003293 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003294 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003295
3296 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3297 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003298 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003299
3300 BasicBlock *Succ = Branch->getSuccessor(0);
3301
3302 BasicBlock::iterator I = Succ->begin();
3303 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3304 int Idx = PHI->getBasicBlockIndex(BB);
3305 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3306
3307 Value *InValue = PHI->getIncomingValue(Idx);
3308 if (InValue != CaseValue) continue;
3309
3310 *PhiIndex = Idx;
3311 return PHI;
3312 }
3313
Craig Topperf40110f2014-04-25 05:29:35 +00003314 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003315}
3316
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003317/// Try to forward the condition of a switch instruction to a phi node
3318/// dominated by the switch, if that would mean that some of the destination
3319/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003320/// Returns true if a change is made.
3321static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3322 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3323 ForwardingNodesMap ForwardingNodes;
3324
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003325 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003326 ConstantInt *CaseValue = I.getCaseValue();
3327 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003328
3329 int PhiIndex;
3330 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3331 &PhiIndex);
3332 if (!PHI) continue;
3333
3334 ForwardingNodes[PHI].push_back(PhiIndex);
3335 }
3336
3337 bool Changed = false;
3338
3339 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3340 E = ForwardingNodes.end(); I != E; ++I) {
3341 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003342 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003343
3344 if (Indexes.size() < 2) continue;
3345
3346 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3347 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3348 Changed = true;
3349 }
3350
3351 return Changed;
3352}
3353
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003354/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003355/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003356static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003357 if (C->isThreadDependent())
3358 return false;
3359 if (C->isDLLImportDependent())
3360 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003361
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003362 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3363 return CE->isGEPWithNoNotionalOverIndexing();
3364
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003365 return isa<ConstantFP>(C) ||
3366 isa<ConstantInt>(C) ||
3367 isa<ConstantPointerNull>(C) ||
3368 isa<GlobalValue>(C) ||
3369 isa<UndefValue>(C);
3370}
3371
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003372/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003373/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003374static Constant *LookupConstant(Value *V,
3375 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3376 if (Constant *C = dyn_cast<Constant>(V))
3377 return C;
3378 return ConstantPool.lookup(V);
3379}
3380
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003381/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003382/// simple instructions such as binary operations where both operands are
3383/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003384/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003385static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003386ConstantFold(Instruction *I, const DataLayout &DL,
3387 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003388 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003389 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3390 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003391 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003392 if (A->isAllOnesValue())
3393 return LookupConstant(Select->getTrueValue(), ConstantPool);
3394 if (A->isNullValue())
3395 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003396 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003397 }
3398
Benjamin Kramer7c302602013-11-12 12:24:36 +00003399 SmallVector<Constant *, 4> COps;
3400 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3401 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3402 COps.push_back(A);
3403 else
Craig Topperf40110f2014-04-25 05:29:35 +00003404 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003405 }
3406
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003407 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00003408 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3409 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003410 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00003411
3412 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003413}
3414
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003415/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003416/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003417/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003418/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003419static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003420GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00003421 BasicBlock **CommonDest,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003422 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
3423 const DataLayout &DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003424 // The block from which we enter the common destination.
3425 BasicBlock *Pred = SI->getParent();
3426
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003427 // If CaseDest is empty except for some side-effect free instructions through
3428 // which we can constant-propagate the CaseVal, continue to its successor.
3429 SmallDenseMap<Value*, Constant*> ConstantPool;
3430 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3431 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3432 ++I) {
3433 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3434 // If the terminator is a simple branch, continue to the next block.
3435 if (T->getNumSuccessors() != 1)
3436 return false;
3437 Pred = CaseDest;
3438 CaseDest = T->getSuccessor(0);
3439 } else if (isa<DbgInfoIntrinsic>(I)) {
3440 // Skip debug intrinsic.
3441 continue;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003442 } else if (Constant *C = ConstantFold(I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003443 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00003444
3445 // If the instruction has uses outside this block or a phi node slot for
3446 // the block, it is not safe to bypass the instruction since it would then
3447 // no longer dominate all its uses.
3448 for (auto &Use : I->uses()) {
3449 User *User = Use.getUser();
3450 if (Instruction *I = dyn_cast<Instruction>(User))
3451 if (I->getParent() == CaseDest)
3452 continue;
3453 if (PHINode *Phi = dyn_cast<PHINode>(User))
3454 if (Phi->getIncomingBlock(Use) == CaseDest)
3455 continue;
3456 return false;
3457 }
3458
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003459 ConstantPool.insert(std::make_pair(I, C));
3460 } else {
3461 break;
3462 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003463 }
3464
3465 // If we did not have a CommonDest before, use the current one.
3466 if (!*CommonDest)
3467 *CommonDest = CaseDest;
3468 // If the destination isn't the common one, abort.
3469 if (CaseDest != *CommonDest)
3470 return false;
3471
3472 // Get the values for this case from phi nodes in the destination block.
3473 BasicBlock::iterator I = (*CommonDest)->begin();
3474 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3475 int Idx = PHI->getBasicBlockIndex(Pred);
3476 if (Idx == -1)
3477 continue;
3478
Hans Wennborg09acdb92012-10-31 15:14:39 +00003479 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3480 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003481 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003482 return false;
3483
3484 // Be conservative about which kinds of constants we support.
3485 if (!ValidLookupTableConstant(ConstVal))
3486 return false;
3487
3488 Res.push_back(std::make_pair(PHI, ConstVal));
3489 }
3490
Hans Wennborgac114a32014-01-12 00:44:41 +00003491 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003492}
3493
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003494// Helper function used to add CaseVal to the list of cases that generate
3495// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003496static void MapCaseToResult(ConstantInt *CaseVal,
3497 SwitchCaseResultVectorTy &UniqueResults,
3498 Constant *Result) {
3499 for (auto &I : UniqueResults) {
3500 if (I.first == Result) {
3501 I.second.push_back(CaseVal);
3502 return;
3503 }
3504 }
3505 UniqueResults.push_back(std::make_pair(Result,
3506 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3507}
3508
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003509// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003510// results for the PHI node of the common destination block for a switch
3511// instruction. Returns false if multiple PHI nodes have been found or if
3512// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003513static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
3514 BasicBlock *&CommonDest,
3515 SwitchCaseResultVectorTy &UniqueResults,
3516 Constant *&DefaultResult,
3517 const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003518 for (auto &I : SI->cases()) {
3519 ConstantInt *CaseVal = I.getCaseValue();
3520
3521 // Resulting value at phi nodes for this case value.
3522 SwitchCaseResultsTy Results;
3523 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3524 DL))
3525 return false;
3526
3527 // Only one value per case is permitted
3528 if (Results.size() > 1)
3529 return false;
3530 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3531
3532 // Check the PHI consistency.
3533 if (!PHI)
3534 PHI = Results[0].first;
3535 else if (PHI != Results[0].first)
3536 return false;
3537 }
3538 // Find the default result value.
3539 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3540 BasicBlock *DefaultDest = SI->getDefaultDest();
3541 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3542 DL);
3543 // If the default value is not found abort unless the default destination
3544 // is unreachable.
3545 DefaultResult =
3546 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3547 if ((!DefaultResult &&
3548 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3549 return false;
3550
3551 return true;
3552}
3553
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003554// Helper function that checks if it is possible to transform a switch with only
3555// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003556// Example:
3557// switch (a) {
3558// case 10: %0 = icmp eq i32 %a, 10
3559// return 10; %1 = select i1 %0, i32 10, i32 4
3560// case 20: ----> %2 = icmp eq i32 %a, 20
3561// return 2; %3 = select i1 %2, i32 2, i32 %1
3562// default:
3563// return 4;
3564// }
3565static Value *
3566ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3567 Constant *DefaultResult, Value *Condition,
3568 IRBuilder<> &Builder) {
3569 assert(ResultVector.size() == 2 &&
3570 "We should have exactly two unique results at this point");
3571 // If we are selecting between only two cases transform into a simple
3572 // select or a two-way select if default is possible.
3573 if (ResultVector[0].second.size() == 1 &&
3574 ResultVector[1].second.size() == 1) {
3575 ConstantInt *const FirstCase = ResultVector[0].second[0];
3576 ConstantInt *const SecondCase = ResultVector[1].second[0];
3577
3578 bool DefaultCanTrigger = DefaultResult;
3579 Value *SelectValue = ResultVector[1].first;
3580 if (DefaultCanTrigger) {
3581 Value *const ValueCompare =
3582 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3583 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3584 DefaultResult, "switch.select");
3585 }
3586 Value *const ValueCompare =
3587 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3588 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3589 "switch.select");
3590 }
3591
3592 return nullptr;
3593}
3594
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003595// Helper function to cleanup a switch instruction that has been converted into
3596// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003597static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3598 Value *SelectValue,
3599 IRBuilder<> &Builder) {
3600 BasicBlock *SelectBB = SI->getParent();
3601 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3602 PHI->removeIncomingValue(SelectBB);
3603 PHI->addIncoming(SelectValue, SelectBB);
3604
3605 Builder.CreateBr(PHI->getParent());
3606
3607 // Remove the switch.
3608 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3609 BasicBlock *Succ = SI->getSuccessor(i);
3610
3611 if (Succ == PHI->getParent())
3612 continue;
3613 Succ->removePredecessor(SelectBB);
3614 }
3615 SI->eraseFromParent();
3616}
3617
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003618/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003619/// phi nodes in a common successor block with only two different
3620/// constant values, replace the switch with select.
3621static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003622 AssumptionCache *AC, const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003623 Value *const Cond = SI->getCondition();
3624 PHINode *PHI = nullptr;
3625 BasicBlock *CommonDest = nullptr;
3626 Constant *DefaultResult;
3627 SwitchCaseResultVectorTy UniqueResults;
3628 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003629 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
3630 DL))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003631 return false;
3632 // Selects choose between maximum two values.
3633 if (UniqueResults.size() != 2)
3634 return false;
3635 assert(PHI != nullptr && "PHI for value select not found");
3636
3637 Builder.SetInsertPoint(SI);
3638 Value *SelectValue = ConvertTwoCaseSwitch(
3639 UniqueResults,
3640 DefaultResult, Cond, Builder);
3641 if (SelectValue) {
3642 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3643 return true;
3644 }
3645 // The switch couldn't be converted into a select.
3646 return false;
3647}
3648
Hans Wennborg776d7122012-09-26 09:34:53 +00003649namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003650 /// This class represents a lookup table that can be used to replace a switch.
Hans Wennborg776d7122012-09-26 09:34:53 +00003651 class SwitchLookupTable {
3652 public:
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003653 /// Create a lookup table to use as a switch replacement with the contents
3654 /// of Values, using DefaultValue to fill any holes in the table.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003655 SwitchLookupTable(
3656 Module &M, uint64_t TableSize, ConstantInt *Offset,
3657 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
3658 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00003659
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003660 /// Build instructions with Builder to retrieve the value at
Hans Wennborg776d7122012-09-26 09:34:53 +00003661 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00003662 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00003663
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003664 /// Return true if a table with TableSize elements of
Hans Wennborg39583b82012-09-26 09:44:49 +00003665 /// type ElementType would fit in a target-legal register.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003666 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00003667 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003668
Hans Wennborg776d7122012-09-26 09:34:53 +00003669 private:
3670 // Depending on the contents of the table, it can be represented in
3671 // different ways.
3672 enum {
3673 // For tables where each element contains the same value, we just have to
3674 // store that single value and return it for each lookup.
3675 SingleValueKind,
3676
Erik Eckstein105374f2014-11-17 09:13:57 +00003677 // For tables where there is a linear relationship between table index
3678 // and values. We calculate the result with a simple multiplication
3679 // and addition instead of a table lookup.
3680 LinearMapKind,
3681
Hans Wennborg39583b82012-09-26 09:44:49 +00003682 // For small tables with integer elements, we can pack them into a bitmap
3683 // that fits into a target-legal register. Values are retrieved by
3684 // shift and mask operations.
3685 BitMapKind,
3686
Hans Wennborg776d7122012-09-26 09:34:53 +00003687 // The table is stored as an array of values. Values are retrieved by load
3688 // instructions from the table.
3689 ArrayKind
3690 } Kind;
3691
3692 // For SingleValueKind, this is the single value.
3693 Constant *SingleValue;
3694
Hans Wennborg39583b82012-09-26 09:44:49 +00003695 // For BitMapKind, this is the bitmap.
3696 ConstantInt *BitMap;
3697 IntegerType *BitMapElementTy;
3698
Erik Eckstein105374f2014-11-17 09:13:57 +00003699 // For LinearMapKind, these are the constants used to derive the value.
3700 ConstantInt *LinearOffset;
3701 ConstantInt *LinearMultiplier;
3702
Hans Wennborg776d7122012-09-26 09:34:53 +00003703 // For ArrayKind, this is the array.
3704 GlobalVariable *Array;
3705 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003706}
Hans Wennborg776d7122012-09-26 09:34:53 +00003707
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003708SwitchLookupTable::SwitchLookupTable(
3709 Module &M, uint64_t TableSize, ConstantInt *Offset,
3710 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
3711 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00003712 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00003713 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003714 assert(Values.size() && "Can't build lookup table without values!");
3715 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003716
3717 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00003718 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003719
Hans Wennborgac114a32014-01-12 00:44:41 +00003720 Type *ValueType = Values.begin()->second->getType();
3721
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003722 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00003723 SmallVector<Constant*, 64> TableContents(TableSize);
3724 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3725 ConstantInt *CaseVal = Values[I].first;
3726 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00003727 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003728
Hans Wennborg776d7122012-09-26 09:34:53 +00003729 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3730 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003731 TableContents[Idx] = CaseRes;
3732
Hans Wennborg776d7122012-09-26 09:34:53 +00003733 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003734 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003735 }
3736
3737 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00003738 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00003739 assert(DefaultValue &&
3740 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00003741 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00003742 for (uint64_t I = 0; I < TableSize; ++I) {
3743 if (!TableContents[I])
3744 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003745 }
3746
Hans Wennborg776d7122012-09-26 09:34:53 +00003747 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003748 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003749 }
3750
Hans Wennborg776d7122012-09-26 09:34:53 +00003751 // If each element in the table contains the same value, we only need to store
3752 // that single value.
3753 if (SingleValue) {
3754 Kind = SingleValueKind;
3755 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003756 }
3757
Erik Eckstein105374f2014-11-17 09:13:57 +00003758 // Check if we can derive the value with a linear transformation from the
3759 // table index.
3760 if (isa<IntegerType>(ValueType)) {
3761 bool LinearMappingPossible = true;
3762 APInt PrevVal;
3763 APInt DistToPrev;
3764 assert(TableSize >= 2 && "Should be a SingleValue table.");
3765 // Check if there is the same distance between two consecutive values.
3766 for (uint64_t I = 0; I < TableSize; ++I) {
3767 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3768 if (!ConstVal) {
3769 // This is an undef. We could deal with it, but undefs in lookup tables
3770 // are very seldom. It's probably not worth the additional complexity.
3771 LinearMappingPossible = false;
3772 break;
3773 }
3774 APInt Val = ConstVal->getValue();
3775 if (I != 0) {
3776 APInt Dist = Val - PrevVal;
3777 if (I == 1) {
3778 DistToPrev = Dist;
3779 } else if (Dist != DistToPrev) {
3780 LinearMappingPossible = false;
3781 break;
3782 }
3783 }
3784 PrevVal = Val;
3785 }
3786 if (LinearMappingPossible) {
3787 LinearOffset = cast<ConstantInt>(TableContents[0]);
3788 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3789 Kind = LinearMapKind;
3790 ++NumLinearMaps;
3791 return;
3792 }
3793 }
3794
Hans Wennborg39583b82012-09-26 09:44:49 +00003795 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003796 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00003797 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003798 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3799 for (uint64_t I = TableSize; I > 0; --I) {
3800 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00003801 // Insert values into the bitmap. Undef values are set to zero.
3802 if (!isa<UndefValue>(TableContents[I - 1])) {
3803 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3804 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3805 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003806 }
3807 BitMap = ConstantInt::get(M.getContext(), TableInt);
3808 BitMapElementTy = IT;
3809 Kind = BitMapKind;
3810 ++NumBitMaps;
3811 return;
3812 }
3813
Hans Wennborg776d7122012-09-26 09:34:53 +00003814 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00003815 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003816 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3817
Hans Wennborg776d7122012-09-26 09:34:53 +00003818 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3819 GlobalVariable::PrivateLinkage,
3820 Initializer,
3821 "switch.table");
3822 Array->setUnnamedAddr(true);
3823 Kind = ArrayKind;
3824}
3825
Manman Ren4d189fb2014-07-24 21:13:20 +00003826Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00003827 switch (Kind) {
3828 case SingleValueKind:
3829 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00003830 case LinearMapKind: {
3831 // Derive the result value from the input value.
3832 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
3833 false, "switch.idx.cast");
3834 if (!LinearMultiplier->isOne())
3835 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
3836 if (!LinearOffset->isZero())
3837 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
3838 return Result;
3839 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003840 case BitMapKind: {
3841 // Type of the bitmap (e.g. i59).
3842 IntegerType *MapTy = BitMap->getType();
3843
3844 // Cast Index to the same type as the bitmap.
3845 // Note: The Index is <= the number of elements in the table, so
3846 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00003847 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00003848
3849 // Multiply the shift amount by the element width.
3850 ShiftAmt = Builder.CreateMul(ShiftAmt,
3851 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3852 "switch.shiftamt");
3853
3854 // Shift down.
3855 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3856 "switch.downshift");
3857 // Mask off.
3858 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3859 "switch.masked");
3860 }
Hans Wennborg776d7122012-09-26 09:34:53 +00003861 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00003862 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00003863 IntegerType *IT = cast<IntegerType>(Index->getType());
3864 uint64_t TableSize = Array->getInitializer()->getType()
3865 ->getArrayNumElements();
3866 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3867 Index = Builder.CreateZExt(Index,
3868 IntegerType::get(IT->getContext(),
3869 IT->getBitWidth() + 1),
3870 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00003871
Hans Wennborg776d7122012-09-26 09:34:53 +00003872 Value *GEPIndices[] = { Builder.getInt32(0), Index };
David Blaikieaa41cd52015-04-03 21:33:42 +00003873 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
3874 GEPIndices, "switch.gep");
Hans Wennborg776d7122012-09-26 09:34:53 +00003875 return Builder.CreateLoad(GEP, "switch.load");
3876 }
3877 }
3878 llvm_unreachable("Unknown lookup table kind!");
3879}
3880
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003881bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003882 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00003883 Type *ElementType) {
3884 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003885 if (!IT)
3886 return false;
3887 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3888 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00003889
3890 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3891 if (TableSize >= UINT_MAX/IT->getBitWidth())
3892 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003893 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00003894}
3895
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003896/// Determine whether a lookup table should be built for this switch, based on
3897/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003898static bool
3899ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
3900 const TargetTransformInfo &TTI, const DataLayout &DL,
3901 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003902 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3903 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00003904
Chandler Carruth77d433d2012-11-30 09:26:25 +00003905 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00003906 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00003907 for (const auto &I : ResultTypes) {
3908 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003909
3910 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003911 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003912
3913 // Saturate this flag to false.
3914 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003915 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003916
3917 // If both flags saturate, we're done. NOTE: This *only* works with
3918 // saturating flags, and all flags have to saturate first due to the
3919 // non-deterministic behavior of iterating over a dense map.
3920 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00003921 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00003922 }
Evan Cheng65df8082012-11-30 02:02:42 +00003923
Chandler Carruth77d433d2012-11-30 09:26:25 +00003924 // If each table would fit in a register, we should build it anyway.
3925 if (AllTablesFitInRegister)
3926 return true;
3927
3928 // Don't build a table that doesn't fit in-register if it has illegal types.
3929 if (HasIllegalType)
3930 return false;
3931
3932 // The table density should be at least 40%. This is the same criterion as for
3933 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3934 // FIXME: Find the best cut-off.
3935 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003936}
3937
Erik Eckstein0d86c762014-11-27 15:13:14 +00003938/// Try to reuse the switch table index compare. Following pattern:
3939/// \code
3940/// if (idx < tablesize)
3941/// r = table[idx]; // table does not contain default_value
3942/// else
3943/// r = default_value;
3944/// if (r != default_value)
3945/// ...
3946/// \endcode
3947/// Is optimized to:
3948/// \code
3949/// cond = idx < tablesize;
3950/// if (cond)
3951/// r = table[idx];
3952/// else
3953/// r = default_value;
3954/// if (cond)
3955/// ...
3956/// \endcode
3957/// Jump threading will then eliminate the second if(cond).
3958static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
3959 BranchInst *RangeCheckBranch, Constant *DefaultValue,
3960 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
3961
3962 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
3963 if (!CmpInst)
3964 return;
3965
3966 // We require that the compare is in the same block as the phi so that jump
3967 // threading can do its work afterwards.
3968 if (CmpInst->getParent() != PhiBlock)
3969 return;
3970
3971 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
3972 if (!CmpOp1)
3973 return;
3974
3975 Value *RangeCmp = RangeCheckBranch->getCondition();
3976 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
3977 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
3978
3979 // Check if the compare with the default value is constant true or false.
3980 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
3981 DefaultValue, CmpOp1, true);
3982 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
3983 return;
3984
3985 // Check if the compare with the case values is distinct from the default
3986 // compare result.
3987 for (auto ValuePair : Values) {
3988 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
3989 ValuePair.second, CmpOp1, true);
3990 if (!CaseConst || CaseConst == DefaultConst)
3991 return;
3992 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
3993 "Expect true or false as compare result.");
3994 }
3995
3996 // Check if the branch instruction dominates the phi node. It's a simple
3997 // dominance check, but sufficient for our needs.
3998 // Although this check is invariant in the calling loops, it's better to do it
3999 // at this late stage. Practically we do it at most once for a switch.
4000 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4001 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4002 BasicBlock *Pred = *PI;
4003 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4004 return;
4005 }
4006
4007 if (DefaultConst == FalseConst) {
4008 // The compare yields the same result. We can replace it.
4009 CmpInst->replaceAllUsesWith(RangeCmp);
4010 ++NumTableCmpReuses;
4011 } else {
4012 // The compare yields the same result, just inverted. We can replace it.
4013 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4014 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4015 RangeCheckBranch);
4016 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4017 ++NumTableCmpReuses;
4018 }
4019}
4020
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004021/// If the switch is only used to initialize one or more phi nodes in a common
4022/// successor block with different constant values, replace the switch with
4023/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004024static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4025 const DataLayout &DL,
4026 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004027 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004028
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004029 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004030 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004031 return false;
4032
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004033 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4034 // split off a dense part and build a lookup table for that.
4035
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004036 // FIXME: This creates arrays of GEPs to constant strings, which means each
4037 // GEP needs a runtime relocation in PIC code. We should just build one big
4038 // string and lookup indices into that.
4039
Hans Wennborg4744ac12014-01-15 05:00:27 +00004040 // Ignore switches with less than three cases. Lookup tables will not make them
4041 // faster, so we don't analyze them.
4042 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004043 return false;
4044
4045 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00004046 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004047 assert(SI->case_begin() != SI->case_end());
4048 SwitchInst::CaseIt CI = SI->case_begin();
4049 ConstantInt *MinCaseVal = CI.getCaseValue();
4050 ConstantInt *MaxCaseVal = CI.getCaseValue();
4051
Craig Topperf40110f2014-04-25 05:29:35 +00004052 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004053 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004054 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4055 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4056 SmallDenseMap<PHINode*, Type*> ResultTypes;
4057 SmallVector<PHINode*, 4> PHIs;
4058
4059 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4060 ConstantInt *CaseVal = CI.getCaseValue();
4061 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4062 MinCaseVal = CaseVal;
4063 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4064 MaxCaseVal = CaseVal;
4065
4066 // Resulting value at phi nodes for this case value.
4067 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4068 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004069 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004070 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004071 return false;
4072
4073 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004074 for (const auto &I : Results) {
4075 PHINode *PHI = I.first;
4076 Constant *Value = I.second;
4077 if (!ResultLists.count(PHI))
4078 PHIs.push_back(PHI);
4079 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004080 }
4081 }
4082
Hans Wennborgac114a32014-01-12 00:44:41 +00004083 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004084 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004085 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4086 }
4087
4088 uint64_t NumResults = ResultLists[PHIs[0]].size();
4089 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4090 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4091 bool TableHasHoles = (NumResults < TableSize);
4092
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004093 // If the table has holes, we need a constant result for the default case
4094 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004095 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00004096 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004097 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00004098
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004099 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4100 if (NeedMask) {
4101 // As an extra penalty for the validity test we require more cases.
4102 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4103 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004104 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004105 return false;
4106 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004107
Hans Wennborga6a11a92014-11-18 02:37:11 +00004108 for (const auto &I : DefaultResultsList) {
4109 PHINode *PHI = I.first;
4110 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004111 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004112 }
4113
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004114 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004115 return false;
4116
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004117 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004118 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004119 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4120 "switch.lookup",
4121 CommonDest->getParent(),
4122 CommonDest);
4123
Michael Gottesmanc024f322013-10-20 07:04:37 +00004124 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004125 Builder.SetInsertPoint(SI);
4126 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4127 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004128
4129 // Compute the maximum table size representable by the integer type we are
4130 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004131 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004132 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004133 assert(MaxTableSize >= TableSize &&
4134 "It is impossible for a switch to have more entries than the max "
4135 "representable value of its input integer type's size.");
4136
Hans Wennborgb64cb272015-01-26 19:52:34 +00004137 // If the default destination is unreachable, or if the lookup table covers
4138 // all values of the conditional variable, branch directly to the lookup table
4139 // BB. Otherwise, check that the condition is within the case range.
4140 const bool DefaultIsReachable =
4141 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4142 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004143 BranchInst *RangeCheckBranch = nullptr;
4144
Hans Wennborgb64cb272015-01-26 19:52:34 +00004145 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00004146 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00004147 // Note: We call removeProdecessor later since we need to be able to get the
4148 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00004149 } else {
4150 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004151 MinCaseVal->getType(), TableSize));
Erik Eckstein0d86c762014-11-27 15:13:14 +00004152 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00004153 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004154
4155 // Populate the BB that does the lookups.
4156 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004157
4158 if (NeedMask) {
4159 // Before doing the lookup we do the hole check.
4160 // The LookupBB is therefore re-purposed to do the hole check
4161 // and we create a new LookupBB.
4162 BasicBlock *MaskBB = LookupBB;
4163 MaskBB->setName("switch.hole_check");
4164 LookupBB = BasicBlock::Create(Mod.getContext(),
4165 "switch.lookup",
4166 CommonDest->getParent(),
4167 CommonDest);
4168
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004169 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4170 // unnecessary illegal types.
4171 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4172 APInt MaskInt(TableSizePowOf2, 0);
4173 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004174 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004175 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4176 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4177 uint64_t Idx = (ResultList[I].first->getValue() -
4178 MinCaseVal->getValue()).getLimitedValue();
4179 MaskInt |= One << Idx;
4180 }
4181 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4182
4183 // Get the TableIndex'th bit of the bitmask.
4184 // If this bit is 0 (meaning hole) jump to the default destination,
4185 // else continue with table lookup.
4186 IntegerType *MapTy = TableMask->getType();
4187 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4188 "switch.maskindex");
4189 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4190 "switch.shifted");
4191 Value *LoBit = Builder.CreateTrunc(Shifted,
4192 Type::getInt1Ty(Mod.getContext()),
4193 "switch.lobit");
4194 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4195
4196 Builder.SetInsertPoint(LookupBB);
4197 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4198 }
4199
Hans Wennborg86ac6302015-04-24 20:57:56 +00004200 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4201 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4202 // do not delete PHINodes here.
4203 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4204 /*DontDeleteUselessPHIs=*/true);
4205 }
4206
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004207 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004208 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4209 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004210 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004211
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004212 // If using a bitmask, use any value to fill the lookup table holes.
4213 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004214 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004215
Manman Ren4d189fb2014-07-24 21:13:20 +00004216 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004217
Hans Wennborgf744fa92012-09-19 14:24:21 +00004218 // If the result is used to return immediately from the function, we want to
4219 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004220 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4221 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004222 Builder.CreateRet(Result);
4223 ReturnedEarly = true;
4224 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004225 }
4226
Erik Eckstein0d86c762014-11-27 15:13:14 +00004227 // Do a small peephole optimization: re-use the switch table compare if
4228 // possible.
4229 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4230 BasicBlock *PhiBlock = PHI->getParent();
4231 // Search for compare instructions which use the phi.
4232 for (auto *User : PHI->users()) {
4233 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4234 }
4235 }
4236
Hans Wennborgf744fa92012-09-19 14:24:21 +00004237 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004238 }
4239
4240 if (!ReturnedEarly)
4241 Builder.CreateBr(CommonDest);
4242
4243 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004244 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004245 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004246
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004247 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004248 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004249 Succ->removePredecessor(SI->getParent());
4250 }
4251 SI->eraseFromParent();
4252
4253 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004254 if (NeedMask)
4255 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004256 return true;
4257}
4258
Devang Patela7ec47d2011-05-18 20:35:38 +00004259bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004260 BasicBlock *BB = SI->getParent();
4261
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004262 if (isValueEqualityComparison(SI)) {
4263 // If we only have one predecessor, and if it is a branch on this value,
4264 // see if that predecessor totally determines the outcome of this switch.
4265 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4266 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004267 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004268
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004269 Value *Cond = SI->getCondition();
4270 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4271 if (SimplifySwitchOnSelect(SI, Select))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004272 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004273
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004274 // If the block only contains the switch, see if we can fold the block
4275 // away into any preds.
4276 BasicBlock::iterator BBI = BB->begin();
4277 // Ignore dbg intrinsics.
4278 while (isa<DbgInfoIntrinsic>(BBI))
4279 ++BBI;
4280 if (SI == &*BBI)
4281 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004282 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004283 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004284
4285 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004286 if (TurnSwitchRangeIntoICmp(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004287 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004288
4289 // Remove unreachable cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004290 if (EliminateDeadSwitchCases(SI, AC, DL))
4291 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004292
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004293 if (SwitchToSelect(SI, Builder, AC, DL))
4294 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004295
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004296 if (ForwardSwitchConditionToPHI(SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004297 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004298
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004299 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4300 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004301
Chris Lattner25c3af32010-12-13 06:25:44 +00004302 return false;
4303}
4304
4305bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4306 BasicBlock *BB = IBI->getParent();
4307 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004308
Chris Lattner25c3af32010-12-13 06:25:44 +00004309 // Eliminate redundant destinations.
4310 SmallPtrSet<Value *, 8> Succs;
4311 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4312 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004313 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004314 Dest->removePredecessor(BB);
4315 IBI->removeDestination(i);
4316 --i; --e;
4317 Changed = true;
4318 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004319 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004320
4321 if (IBI->getNumDestinations() == 0) {
4322 // If the indirectbr has no successors, change it to unreachable.
4323 new UnreachableInst(IBI->getContext(), IBI);
4324 EraseTerminatorInstAndDCECond(IBI);
4325 return true;
4326 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004327
Chris Lattner25c3af32010-12-13 06:25:44 +00004328 if (IBI->getNumDestinations() == 1) {
4329 // If the indirectbr has one successor, change it to a direct branch.
4330 BranchInst::Create(IBI->getDestination(0), IBI);
4331 EraseTerminatorInstAndDCECond(IBI);
4332 return true;
4333 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004334
Chris Lattner25c3af32010-12-13 06:25:44 +00004335 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4336 if (SimplifyIndirectBrOnSelect(IBI, SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004337 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004338 }
4339 return Changed;
4340}
4341
Philip Reames2b969d72015-03-24 22:28:45 +00004342/// Given an block with only a single landing pad and a unconditional branch
4343/// try to find another basic block which this one can be merged with. This
4344/// handles cases where we have multiple invokes with unique landing pads, but
4345/// a shared handler.
4346///
4347/// We specifically choose to not worry about merging non-empty blocks
4348/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4349/// practice, the optimizer produces empty landing pad blocks quite frequently
4350/// when dealing with exception dense code. (see: instcombine, gvn, if-else
4351/// sinking in this file)
4352///
4353/// This is primarily a code size optimization. We need to avoid performing
4354/// any transform which might inhibit optimization (such as our ability to
4355/// specialize a particular handler via tail commoning). We do this by not
4356/// merging any blocks which require us to introduce a phi. Since the same
4357/// values are flowing through both blocks, we don't loose any ability to
4358/// specialize. If anything, we make such specialization more likely.
4359///
4360/// TODO - This transformation could remove entries from a phi in the target
4361/// block when the inputs in the phi are the same for the two blocks being
4362/// merged. In some cases, this could result in removal of the PHI entirely.
4363static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
4364 BasicBlock *BB) {
4365 auto Succ = BB->getUniqueSuccessor();
4366 assert(Succ);
4367 // If there's a phi in the successor block, we'd likely have to introduce
4368 // a phi into the merged landing pad block.
4369 if (isa<PHINode>(*Succ->begin()))
4370 return false;
4371
4372 for (BasicBlock *OtherPred : predecessors(Succ)) {
4373 if (BB == OtherPred)
4374 continue;
4375 BasicBlock::iterator I = OtherPred->begin();
4376 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
4377 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
4378 continue;
4379 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4380 BranchInst *BI2 = dyn_cast<BranchInst>(I);
4381 if (!BI2 || !BI2->isIdenticalTo(BI))
4382 continue;
4383
4384 // We've found an identical block. Update our predeccessors to take that
4385 // path instead and make ourselves dead.
4386 SmallSet<BasicBlock *, 16> Preds;
4387 Preds.insert(pred_begin(BB), pred_end(BB));
4388 for (BasicBlock *Pred : Preds) {
4389 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
4390 assert(II->getNormalDest() != BB &&
4391 II->getUnwindDest() == BB && "unexpected successor");
4392 II->setUnwindDest(OtherPred);
4393 }
4394
4395 // The debug info in OtherPred doesn't cover the merged control flow that
4396 // used to go through BB. We need to delete it or update it.
4397 for (auto I = OtherPred->begin(), E = OtherPred->end();
4398 I != E;) {
4399 Instruction &Inst = *I; I++;
4400 if (isa<DbgInfoIntrinsic>(Inst))
4401 Inst.eraseFromParent();
4402 }
4403
4404 SmallSet<BasicBlock *, 16> Succs;
4405 Succs.insert(succ_begin(BB), succ_end(BB));
4406 for (BasicBlock *Succ : Succs) {
4407 Succ->removePredecessor(BB);
4408 }
4409
4410 IRBuilder<> Builder(BI);
4411 Builder.CreateUnreachable();
4412 BI->eraseFromParent();
4413 return true;
4414 }
4415 return false;
4416}
4417
Devang Patel767f6932011-05-18 18:28:48 +00004418bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00004419 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004420
Manman Ren93ab6492012-09-20 22:37:36 +00004421 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4422 return true;
4423
Chris Lattner25c3af32010-12-13 06:25:44 +00004424 // If the Terminator is the only non-phi instruction, simplify the block.
Rafael Espindolad07cf402014-07-30 21:04:00 +00004425 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
Chris Lattner25c3af32010-12-13 06:25:44 +00004426 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4427 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4428 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004429
Chris Lattner25c3af32010-12-13 06:25:44 +00004430 // If the only instruction in the block is a seteq/setne comparison
4431 // against a constant, try to simplify the block.
4432 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4433 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4434 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4435 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004436 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004437 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
4438 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00004439 return true;
4440 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004441
Philip Reames2b969d72015-03-24 22:28:45 +00004442 // See if we can merge an empty landing pad block with another which is
4443 // equivalent.
4444 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
4445 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4446 if (I->isTerminator() &&
4447 TryToMergeLandingPad(LPad, BI, BB))
4448 return true;
4449 }
4450
Manman Rend33f4ef2012-06-13 05:43:29 +00004451 // If this basic block is ONLY a compare and a branch, and if a predecessor
4452 // branches to us and our successor, fold the comparison into the
4453 // predecessor and use logical operations to update the incoming value
4454 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004455 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4456 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004457 return false;
4458}
4459
4460
Devang Patela7ec47d2011-05-18 20:35:38 +00004461bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004462 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004463
Chris Lattner25c3af32010-12-13 06:25:44 +00004464 // Conditional branch
4465 if (isValueEqualityComparison(BI)) {
4466 // If we only have one predecessor, and if it is a branch on this value,
4467 // see if that predecessor totally determines the outcome of this
4468 // switch.
4469 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00004470 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004471 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004472
Chris Lattner25c3af32010-12-13 06:25:44 +00004473 // This block must be empty, except for the setcond inst, if it exists.
4474 // Ignore dbg intrinsics.
4475 BasicBlock::iterator I = BB->begin();
4476 // Ignore dbg intrinsics.
4477 while (isa<DbgInfoIntrinsic>(I))
4478 ++I;
4479 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00004480 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004481 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004482 } else if (&*I == cast<Instruction>(BI->getCondition())){
4483 ++I;
4484 // Ignore dbg intrinsics.
4485 while (isa<DbgInfoIntrinsic>(I))
4486 ++I;
Devang Patel58380552011-05-18 20:53:17 +00004487 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004488 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004489 }
4490 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004491
Chris Lattner25c3af32010-12-13 06:25:44 +00004492 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004493 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00004494 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004495
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00004496 // If this basic block is ONLY a compare and a branch, and if a predecessor
4497 // branches to us and one of our successors, fold the comparison into the
4498 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004499 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4500 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004501
Chris Lattner25c3af32010-12-13 06:25:44 +00004502 // We have a conditional branch to two blocks that are only reachable
4503 // from BI. We know that the condbr dominates the two blocks, so see if
4504 // there is any identical code in the "then" and "else" blocks. If so, we
4505 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00004506 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4507 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004508 if (HoistThenElseCodeToIf(BI, TTI))
4509 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004510 } else {
4511 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004512 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00004513 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4514 if (Succ0TI->getNumSuccessors() == 1 &&
4515 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004516 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
4517 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004518 }
Craig Topperf40110f2014-04-25 05:29:35 +00004519 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004520 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004521 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00004522 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4523 if (Succ1TI->getNumSuccessors() == 1 &&
4524 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004525 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
4526 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004527 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004528
Chris Lattner25c3af32010-12-13 06:25:44 +00004529 // If this is a branch on a phi node in the current block, thread control
4530 // through this block if any PHI node entries are constants.
4531 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4532 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004533 if (FoldCondBranchOnPHI(BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004534 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004535
Chris Lattner25c3af32010-12-13 06:25:44 +00004536 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004537 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4538 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00004539 if (PBI != BI && PBI->isConditional())
4540 if (SimplifyCondBranchToCondBranch(PBI, BI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004541 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004542
4543 return false;
4544}
4545
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004546/// Check if passing a value to an instruction will cause undefined behavior.
4547static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4548 Constant *C = dyn_cast<Constant>(V);
4549 if (!C)
4550 return false;
4551
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004552 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004553 return false;
4554
4555 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004556 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00004557 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004558
4559 // Now make sure that there are no instructions in between that can alter
4560 // control flow (eg. calls)
4561 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00004562 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004563 return false;
4564
4565 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4566 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4567 if (GEP->getPointerOperand() == I)
4568 return passingValueIsAlwaysUndefined(V, GEP);
4569
4570 // Look through bitcasts.
4571 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4572 return passingValueIsAlwaysUndefined(V, BC);
4573
Benjamin Kramer0655b782011-08-26 02:25:55 +00004574 // Load from null is undefined.
4575 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004576 if (!LI->isVolatile())
4577 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004578
Benjamin Kramer0655b782011-08-26 02:25:55 +00004579 // Store to null is undefined.
4580 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004581 if (!SI->isVolatile())
4582 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004583 }
4584 return false;
4585}
4586
4587/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004588/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004589static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4590 for (BasicBlock::iterator i = BB->begin();
4591 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4592 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4593 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4594 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4595 IRBuilder<> Builder(T);
4596 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4597 BB->removePredecessor(PHI->getIncomingBlock(i));
4598 // Turn uncoditional branches into unreachables and remove the dead
4599 // destination from conditional branches.
4600 if (BI->isUnconditional())
4601 Builder.CreateUnreachable();
4602 else
4603 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4604 BI->getSuccessor(0));
4605 BI->eraseFromParent();
4606 return true;
4607 }
4608 // TODO: SwitchInst.
4609 }
4610
4611 return false;
4612}
4613
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004614bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00004615 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00004616
Chris Lattnerd7beca32010-12-14 06:17:25 +00004617 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00004618 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00004619
Dan Gohman4a63fad2010-08-14 00:29:42 +00004620 // Remove basic blocks that have no predecessors (except the entry block)...
4621 // or that just have themself as a predecessor. These are unreachable.
Ramkumar Ramachandra181233b2015-01-13 04:17:47 +00004622 if ((pred_empty(BB) &&
Chris Lattnerd7beca32010-12-14 06:17:25 +00004623 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00004624 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00004625 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00004626 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00004627 return true;
4628 }
4629
Chris Lattner031340a2003-08-17 19:41:53 +00004630 // Check to see if we can constant propagate this terminator instruction
4631 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00004632 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00004633
Dan Gohman1a951062009-10-30 22:39:04 +00004634 // Check for and eliminate duplicate PHI nodes in this block.
4635 Changed |= EliminateDuplicatePHINodes(BB);
4636
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004637 // Check for and remove branches that will always cause undefined behavior.
4638 Changed |= removeUndefIntroducingPredecessor(BB);
4639
Chris Lattner2e3832d2010-12-13 05:10:48 +00004640 // Merge basic blocks into their predecessor if there is only one distinct
4641 // pred, and if there is only one distinct successor of the predecessor, and
4642 // if there are no PHI nodes.
4643 //
4644 if (MergeBlockIntoPredecessor(BB))
4645 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004646
Devang Patel15ad6762011-05-18 18:01:27 +00004647 IRBuilder<> Builder(BB);
4648
Dan Gohman20af5a02008-03-11 21:53:06 +00004649 // If there is a trivial two-entry PHI node in this basic block, and we can
4650 // eliminate it, do so now.
4651 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4652 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004653 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00004654
Devang Patela7ec47d2011-05-18 20:35:38 +00004655 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00004656 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00004657 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00004658 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004659 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00004660 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004661 }
4662 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00004663 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00004664 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4665 if (SimplifyResume(RI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004666 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00004667 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004668 } else if (UnreachableInst *UI =
4669 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4670 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004671 } else if (IndirectBrInst *IBI =
4672 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4673 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00004674 }
4675
Chris Lattner031340a2003-08-17 19:41:53 +00004676 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00004677}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004678
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004679/// This function is used to do simplification of a CFG.
4680/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004681/// eliminates unreachable basic blocks, and does other "peephole" optimization
4682/// of the CFG. It returns true if a modification was made.
4683///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004684bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004685 unsigned BonusInstThreshold, AssumptionCache *AC) {
4686 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
4687 BonusInstThreshold, AC).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004688}