blob: e0c598f92e2b6d043cb5a75bd9d52c2f727704ca [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"
James Molloy4de84dd2015-11-04 15:28:04 +000017#include "llvm/ADT/SetOperations.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000022#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000024#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000026#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000027#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/MDBuilder.h"
37#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000039#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000041#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/Type.h"
Evan Chengd983eba2011-01-29 04:46:23 +000043#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000044#include "llvm/Support/Debug.h"
45#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Rafael Espindolaea46c322014-08-15 15:46:38 +000047#include "llvm/Transforms/Utils/Local.h"
Jingyue Wufc029672014-09-30 22:23:38 +000048#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000049#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000050#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000051#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000052using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000053using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000054
Chandler Carruth964daaa2014-04-22 02:55:47 +000055#define DEBUG_TYPE "simplifycfg"
56
James Molloy1b6207e2015-02-13 10:48:30 +000057// Chosen as 2 so as to be cheap, but still to have enough power to fold
58// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
59// To catch this, we need to fold a compare and a select, hence '2' being the
60// minimum reasonable default.
Peter Collingbourne616044a2011-04-29 18:47:38 +000061static cl::opt<unsigned>
James Molloy1b6207e2015-02-13 10:48:30 +000062PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
63 cl::desc("Control the amount of phi node folding to perform (default = 2)"));
Peter Collingbourne616044a2011-04-29 18:47:38 +000064
Evan Chengd983eba2011-01-29 04:46:23 +000065static cl::opt<bool>
66DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
67 cl::desc("Duplicate return instructions into unconditional branches"));
68
Manman Ren93ab6492012-09-20 22:37:36 +000069static cl::opt<bool>
70SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
71 cl::desc("Sink common instructions down to the end block"));
72
Alp Tokercb402912014-01-24 17:20:08 +000073static cl::opt<bool> HoistCondStores(
74 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
75 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000076
James Molloy4de84dd2015-11-04 15:28:04 +000077static cl::opt<bool> MergeCondStores(
78 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
79 cl::desc("Hoist conditional stores even if an unconditional store does not "
80 "precede - hoist multiple conditional stores into a single "
81 "predicated store"));
82
83static cl::opt<bool> MergeCondStoresAggressively(
84 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
85 cl::desc("When merging conditional stores, do so even if the resultant "
86 "basic blocks are unlikely to be if-converted as a result"));
87
Hans Wennborg39583b82012-09-26 09:44:49 +000088STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000089STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000090STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +000091STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +000092STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Manman Ren93ab6492012-09-20 22:37:36 +000093STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000094STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +000095
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000096namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +000097 // The first field contains the value that the switch produces when a certain
Sanjay Patel9361d352015-09-10 16:31:19 +000098 // case group is selected, and the second field is a vector containing the
99 // cases composing the case group.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000100 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
101 SwitchCaseResultVectorTy;
102 // The first field contains the phi node that generates a result of the switch
Sanjay Patel9361d352015-09-10 16:31:19 +0000103 // and the second field contains the value generated for a certain case in the
104 // switch for that PHI.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000105 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
106
Eric Christopherb65acc62012-07-02 23:22:21 +0000107 /// ValueEqualityComparisonCase - Represents a case of a switch.
108 struct ValueEqualityComparisonCase {
109 ConstantInt *Value;
110 BasicBlock *Dest;
111
112 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
113 : Value(Value), Dest(Dest) {}
114
115 bool operator<(ValueEqualityComparisonCase RHS) const {
116 // Comparing pointers is ok as we only rely on the order for uniquing.
117 return Value < RHS.Value;
118 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000119
120 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000121 };
122
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000123class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000124 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000125 const DataLayout &DL;
Jingyue Wufc029672014-09-30 22:23:38 +0000126 unsigned BonusInstThreshold;
Chandler Carruth66b31302015-01-04 12:03:27 +0000127 AssumptionCache *AC;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000128 Value *isValueEqualityComparison(TerminatorInst *TI);
129 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000130 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000131 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000132 BasicBlock *Pred,
133 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000134 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
135 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000136
Devang Pateldd14e0f2011-05-18 21:33:11 +0000137 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000138 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000139 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000140 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000141 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000142 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000143 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000144 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000145
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000146public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000147 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
148 unsigned BonusInstThreshold, AssumptionCache *AC)
149 : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000150 bool run(BasicBlock *BB);
151};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000152}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000153
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000154/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000155/// terminator instructions together.
Chris Lattner76dc2042005-08-03 00:19:45 +0000156static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
157 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000158
Chris Lattner76dc2042005-08-03 00:19:45 +0000159 // It is not safe to merge these two switch instructions if they have a common
160 // successor, and if that successor has a PHI node, and if *that* PHI node has
161 // conflicting incoming values from the two switch blocks.
162 BasicBlock *SI1BB = SI1->getParent();
163 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000164 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000165
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000166 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
167 if (SI1Succs.count(*I))
168 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000169 isa<PHINode>(BBI); ++BBI) {
170 PHINode *PN = cast<PHINode>(BBI);
171 if (PN->getIncomingValueForBlock(SI1BB) !=
172 PN->getIncomingValueForBlock(SI2BB))
173 return false;
174 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000175
Chris Lattner76dc2042005-08-03 00:19:45 +0000176 return true;
177}
178
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000179/// Return true if it is safe and profitable to merge these two terminator
180/// instructions together, where SI1 is an unconditional branch. PhiNodes will
181/// store all PHI nodes in common successors.
Manman Rend33f4ef2012-06-13 05:43:29 +0000182static bool isProfitableToFoldUnconditional(BranchInst *SI1,
183 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000184 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000185 SmallVectorImpl<PHINode*> &PhiNodes) {
186 if (SI1 == SI2) return false; // Can't merge with self!
187 assert(SI1->isUnconditional() && SI2->isConditional());
188
189 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000190 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000191 // 1> We have a constant incoming value for the conditional branch;
192 // 2> We have "Cond" as the incoming value for the unconditional branch;
193 // 3> SI2->getCondition() and Cond have same operands.
194 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
195 if (!Ci2) return false;
196 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
197 Cond->getOperand(1) == Ci2->getOperand(1)) &&
198 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
199 Cond->getOperand(1) == Ci2->getOperand(0)))
200 return false;
201
202 BasicBlock *SI1BB = SI1->getParent();
203 BasicBlock *SI2BB = SI2->getParent();
204 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000205 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
206 if (SI1Succs.count(*I))
207 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000208 isa<PHINode>(BBI); ++BBI) {
209 PHINode *PN = cast<PHINode>(BBI);
210 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000211 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000212 return false;
213 PhiNodes.push_back(PN);
214 }
215 return true;
216}
217
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000218/// Update PHI nodes in Succ to indicate that there will now be entries in it
219/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
220/// will be the same as those coming in from ExistPred, an existing predecessor
221/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000222static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
223 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000224 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000225
Chris Lattner80b03a12008-07-13 22:23:11 +0000226 PHINode *PN;
227 for (BasicBlock::iterator I = Succ->begin();
228 (PN = dyn_cast<PHINode>(I)); ++I)
229 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000230}
231
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000232/// Compute an abstract "cost" of speculating the given instruction,
233/// which is assumed to be safe to speculate. TCC_Free means cheap,
234/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000235/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000236static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000237 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000238 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000239 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000240 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000241}
Sanjay Patelf9b77632015-09-15 15:24:42 +0000242
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000243/// If we have a merge point of an "if condition" as accepted above,
244/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000245/// don't handle the true generality of domination here, just a special case
246/// which works well enough for us.
247///
248/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000249/// see if V (which must be an instruction) and its recursive operands
250/// that do not dominate BB have a combined cost lower than CostRemaining and
251/// are non-trapping. If both are true, the instruction is inserted into the
252/// set and true is returned.
253///
254/// The cost for most non-trapping instructions is defined as 1 except for
255/// Select whose cost is 2.
256///
257/// After this function returns, CostRemaining is decreased by the cost of
258/// V plus its non-dominating operands. If that cost is greater than
259/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000260static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000261 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000262 unsigned &CostRemaining,
James Molloy7c336572015-02-11 12:15:41 +0000263 const TargetTransformInfo &TTI) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000264 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000265 if (!I) {
266 // Non-instructions all dominate instructions, but not all constantexprs
267 // can be executed unconditionally.
268 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
269 if (C->canTrap())
270 return false;
271 return true;
272 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000273 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000274
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000275 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000276 // the bottom of this block.
277 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000278
Chris Lattner0aa56562004-04-09 22:50:22 +0000279 // If this instruction is defined in a block that contains an unconditional
280 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000281 // statement". If not, it definitely dominates the region.
282 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000283 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000284 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000285
Chris Lattner9ac168d2010-12-14 07:41:39 +0000286 // If we aren't allowing aggressive promotion anymore, then don't consider
287 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000288 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000289
Peter Collingbournee3511e12011-04-29 18:47:31 +0000290 // If we have seen this instruction before, don't count it again.
291 if (AggressiveInsts->count(I)) return true;
292
Chris Lattner9ac168d2010-12-14 07:41:39 +0000293 // Okay, it looks like the instruction IS in the "condition". Check to
294 // see if it's a cheap instruction to unconditionally compute, and if it
295 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000296 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000297 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000298
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000299 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000300
Peter Collingbournee3511e12011-04-29 18:47:31 +0000301 if (Cost > CostRemaining)
302 return false;
303
304 CostRemaining -= Cost;
305
306 // Okay, we can only really hoist these out if their operands do
307 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000308 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000309 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000310 return false;
311 // Okay, it's safe to do this! Remember this instruction.
312 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000313 return true;
314}
Chris Lattner466a0492002-05-21 20:50:24 +0000315
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000316/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000317/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000318static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000319 // Normal constant int.
320 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000321 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000322 return CI;
323
324 // This is some kind of pointer constant. Turn it into a pointer-sized
325 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000326 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000327
328 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
329 if (isa<ConstantPointerNull>(V))
330 return ConstantInt::get(PtrTy, 0);
331
332 // IntToPtr const int.
333 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
334 if (CE->getOpcode() == Instruction::IntToPtr)
335 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
336 // The constant is very likely to have the right type already.
337 if (CI->getType() == PtrTy)
338 return CI;
339 else
340 return cast<ConstantInt>
341 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
342 }
Craig Topperf40110f2014-04-25 05:29:35 +0000343 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000344}
345
Mehdi Aminiffd01002014-11-20 22:40:25 +0000346namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000347
Mehdi Aminiffd01002014-11-20 22:40:25 +0000348/// Given a chain of or (||) or and (&&) comparison of a value against a
349/// constant, this will try to recover the information required for a switch
350/// structure.
351/// It will depth-first traverse the chain of comparison, seeking for patterns
352/// like %a == 12 or %a < 4 and combine them to produce a set of integer
353/// representing the different cases for the switch.
354/// Note that if the chain is composed of '||' it will build the set of elements
355/// that matches the comparisons (i.e. any of this value validate the chain)
356/// while for a chain of '&&' it will build the set elements that make the test
357/// fail.
358struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000359 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000360 Value *CompValue; /// Value found for the switch comparison
361 Value *Extra; /// Extra clause to be checked before the switch
362 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
363 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000364
Mehdi Aminiffd01002014-11-20 22:40:25 +0000365 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000366 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
367 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
368 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000369 }
370
Mehdi Aminiffd01002014-11-20 22:40:25 +0000371 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000372 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000373 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000374 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000375
Mehdi Aminiffd01002014-11-20 22:40:25 +0000376private:
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000377
Mehdi Aminiffd01002014-11-20 22:40:25 +0000378 /// Try to set the current value used for the comparison, it succeeds only if
379 /// it wasn't set before or if the new value is the same as the old one
380 bool setValueOnce(Value *NewVal) {
381 if(CompValue && CompValue != NewVal) return false;
382 CompValue = NewVal;
383 return (CompValue != nullptr);
384 }
385
386 /// Try to match Instruction "I" as a comparison against a constant and
387 /// populates the array Vals with the set of values that match (or do not
388 /// match depending on isEQ).
389 /// Return false on failure. On success, the Value the comparison matched
390 /// against is placed in CompValue.
391 /// If CompValue is already set, the function is expected to fail if a match
392 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000393 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000394 // If this is an icmp against a constant, handle this as one of the cases.
395 ICmpInst *ICI;
396 ConstantInt *C;
397 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
398 (C = GetConstantInt(I->getOperand(1), DL)))) {
399 return false;
400 }
401
402 Value *RHSVal;
403 ConstantInt *RHSC;
404
405 // Pattern match a special case
406 // (x & ~2^x) == y --> x == y || x == y|2^x
407 // This undoes a transformation done by instcombine to fuse 2 compares.
408 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
409 if (match(ICI->getOperand(0),
410 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
411 APInt Not = ~RHSC->getValue();
412 if (Not.isPowerOf2()) {
413 // If we already have a value for the switch, it has to match!
414 if(!setValueOnce(RHSVal))
415 return false;
416
417 Vals.push_back(C);
418 Vals.push_back(ConstantInt::get(C->getContext(),
419 C->getValue() | Not));
420 UsedICmps++;
421 return true;
422 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000423 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000424
425 // If we already have a value for the switch, it has to match!
426 if(!setValueOnce(ICI->getOperand(0)))
427 return false;
428
429 UsedICmps++;
430 Vals.push_back(C);
431 return ICI->getOperand(0);
432 }
433
434 // 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 +0000435 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
436 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000437
438 // Shift the range if the compare is fed by an add. This is the range
439 // compare idiom as emitted by instcombine.
440 Value *CandidateVal = I->getOperand(0);
441 if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
442 Span = Span.subtract(RHSC->getValue());
443 CandidateVal = RHSVal;
444 }
445
446 // If this is an and/!= check, then we are looking to build the set of
447 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
448 // x != 0 && x != 1.
449 if (!isEQ)
450 Span = Span.inverse();
451
452 // If there are a ton of values, we don't want to make a ginormous switch.
453 if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
454 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000455 }
456
457 // If we already have a value for the switch, it has to match!
Mehdi Aminiffd01002014-11-20 22:40:25 +0000458 if(!setValueOnce(CandidateVal))
459 return false;
460
461 // Add all values from the range to the set
462 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
463 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000464
465 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000466 return true;
467
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000468 }
469
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000470 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000471 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
472 /// the value being compared, and stick the list constants into the Vals
473 /// vector.
474 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000475 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000476 Instruction *I = dyn_cast<Instruction>(V);
477 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000478
Mehdi Aminiffd01002014-11-20 22:40:25 +0000479 // Keep a stack (SmallVector for efficiency) for depth-first traversal
480 SmallVector<Value *, 8> DFT;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000481
Mehdi Aminiffd01002014-11-20 22:40:25 +0000482 // Initialize
483 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000484
Mehdi Aminiffd01002014-11-20 22:40:25 +0000485 while(!DFT.empty()) {
486 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000487
Mehdi Aminiffd01002014-11-20 22:40:25 +0000488 if (Instruction *I = dyn_cast<Instruction>(V)) {
489 // If it is a || (or && depending on isEQ), process the operands.
490 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
491 DFT.push_back(I->getOperand(1));
492 DFT.push_back(I->getOperand(0));
493 continue;
494 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000495
Mehdi Aminiffd01002014-11-20 22:40:25 +0000496 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000497 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000498 // Match succeed, continue the loop
499 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000500 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000501
Mehdi Aminiffd01002014-11-20 22:40:25 +0000502 // One element of the sequence of || (or &&) could not be match as a
503 // comparison against the same value as the others.
504 // We allow only one "Extra" case to be checked before the switch
505 if (!Extra) {
506 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000507 continue;
508 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000509 // Failed to parse a proper sequence, abort now
510 CompValue = nullptr;
511 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000512 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000513 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000514};
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000515
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000516}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000517
Eli Friedmancb61afb2008-12-16 20:54:32 +0000518static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000519 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000520 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
521 Cond = dyn_cast<Instruction>(SI->getCondition());
522 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
523 if (BI->isConditional())
524 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000525 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
526 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000527 }
528
529 TI->eraseFromParent();
530 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
531}
532
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000533/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000534/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000535Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000536 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000537 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
538 // Do not permit merging of large switch instructions into their
539 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000540 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
541 pred_end(SI->getParent())) <= 128)
542 CV = SI->getCondition();
543 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000544 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000545 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000546 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000547 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000548 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000549
550 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000551 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000552 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
553 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000554 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000555 CV = Ptr;
556 }
557 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000558 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000559}
560
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000561/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000562/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000563BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000564GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000565 std::vector<ValueEqualityComparisonCase>
566 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000567 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000568 Cases.reserve(SI->getNumCases());
569 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
570 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
571 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000572 return SI->getDefaultDest();
573 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000574
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000575 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000576 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000577 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
578 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000579 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000580 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000581 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000582}
583
Eric Christopherb65acc62012-07-02 23:22:21 +0000584
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000585/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000586/// in the list that match the specified block.
587static void EliminateBlockCases(BasicBlock *BB,
588 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000589 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000590}
591
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000592/// Return true if there are any keys in C1 that exist in C2 as well.
Eric Christopherb65acc62012-07-02 23:22:21 +0000593static bool
594ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
595 std::vector<ValueEqualityComparisonCase > &C2) {
596 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
597
598 // Make V1 be smaller than V2.
599 if (V1->size() > V2->size())
600 std::swap(V1, V2);
601
602 if (V1->size() == 0) return false;
603 if (V1->size() == 1) {
604 // Just scan V2.
605 ConstantInt *TheVal = (*V1)[0].Value;
606 for (unsigned i = 0, e = V2->size(); i != e; ++i)
607 if (TheVal == (*V2)[i].Value)
608 return true;
609 }
610
611 // Otherwise, just sort both lists and compare element by element.
612 array_pod_sort(V1->begin(), V1->end());
613 array_pod_sort(V2->begin(), V2->end());
614 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
615 while (i1 != e1 && i2 != e2) {
616 if ((*V1)[i1].Value == (*V2)[i2].Value)
617 return true;
618 if ((*V1)[i1].Value < (*V2)[i2].Value)
619 ++i1;
620 else
621 ++i2;
622 }
623 return false;
624}
625
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000626/// If TI is known to be a terminator instruction and its block is known to
627/// only have a single predecessor block, check to see if that predecessor is
628/// also a value comparison with the same value, and if that comparison
629/// determines the outcome of this comparison. If so, simplify TI. This does a
630/// very limited form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000631bool SimplifyCFGOpt::
632SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000633 BasicBlock *Pred,
634 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000635 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
636 if (!PredVal) return false; // Not a value comparison in predecessor.
637
638 Value *ThisVal = isValueEqualityComparison(TI);
639 assert(ThisVal && "This isn't a value comparison!!");
640 if (ThisVal != PredVal) return false; // Different predicates.
641
Andrew Trick3051aa12012-08-29 21:46:38 +0000642 // TODO: Preserve branch weight metadata, similarly to how
643 // FoldValueComparisonIntoPredecessors preserves it.
644
Chris Lattner1cca9592005-02-24 06:17:52 +0000645 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000646 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000647 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
648 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000649 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000650
Chris Lattner1cca9592005-02-24 06:17:52 +0000651 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000652 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000653 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000654 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000655
656 // If TI's block is the default block from Pred's comparison, potentially
657 // simplify TI based on this knowledge.
658 if (PredDef == TI->getParent()) {
659 // If we are here, we know that the value is none of those cases listed in
660 // PredCases. If there are any cases in ThisCases that are in PredCases, we
661 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000662 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000663 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000664
Chris Lattner4088e2b2010-12-13 01:47:07 +0000665 if (isa<BranchInst>(TI)) {
666 // Okay, one of the successors of this condbr is dead. Convert it to a
667 // uncond br.
668 assert(ThisCases.size() == 1 && "Branch can only have one case!");
669 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000670 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000671 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000672
Chris Lattner4088e2b2010-12-13 01:47:07 +0000673 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000674 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000675
Chris Lattner4088e2b2010-12-13 01:47:07 +0000676 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
677 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000678
Chris Lattner4088e2b2010-12-13 01:47:07 +0000679 EraseTerminatorInstAndDCECond(TI);
680 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000681 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000682
Chris Lattner4088e2b2010-12-13 01:47:07 +0000683 SwitchInst *SI = cast<SwitchInst>(TI);
684 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000685 SmallPtrSet<Constant*, 16> DeadCases;
686 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
687 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000688
David Greene725c7c32010-01-05 01:26:52 +0000689 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000690 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000691
Manman Ren8691e522012-09-14 21:53:06 +0000692 // Collect branch weights into a vector.
693 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000694 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000695 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
696 if (HasWeight)
697 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
698 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000699 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000700 Weights.push_back(CI->getValue().getZExtValue());
701 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000702 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
703 --i;
704 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000705 if (HasWeight) {
706 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
707 Weights.pop_back();
708 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000709 i.getCaseSuccessor()->removePredecessor(TI->getParent());
710 SI->removeCase(i);
711 }
712 }
Manman Ren97c18762012-10-11 22:28:34 +0000713 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000714 SI->setMetadata(LLVMContext::MD_prof,
715 MDBuilder(SI->getParent()->getContext()).
716 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000717
718 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000719 return true;
720 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000721
Chris Lattner4088e2b2010-12-13 01:47:07 +0000722 // Otherwise, TI's block must correspond to some matched value. Find out
723 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000724 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000725 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000726 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
727 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000728 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000729 return false; // Cannot handle multiple values coming to this block.
730 TIV = PredCases[i].Value;
731 }
732 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000733
734 // Okay, we found the one constant that our value can be if we get into TI's
735 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000736 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000737 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
738 if (ThisCases[i].Value == TIV) {
739 TheRealDest = ThisCases[i].Dest;
740 break;
741 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000742
743 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000744 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000745
746 // Remove PHI node entries for dead edges.
747 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000748 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
749 if (*SI != CheckEdge)
750 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000751 else
Craig Topperf40110f2014-04-25 05:29:35 +0000752 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000753
754 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000755 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000756 (void) NI;
757
758 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
759 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
760
761 EraseTerminatorInstAndDCECond(TI);
762 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000763}
764
Dale Johannesen7f99d222009-03-12 21:01:11 +0000765namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000766 /// This class implements a stable ordering of constant
Dale Johannesen7f99d222009-03-12 21:01:11 +0000767 /// integers that does not depend on their address. This is important for
768 /// applications that sort ConstantInt's to ensure uniqueness.
769 struct ConstantIntOrdering {
770 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
771 return LHS->getValue().ult(RHS->getValue());
772 }
773 };
774}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000775
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000776static int ConstantIntSortPredicate(ConstantInt *const *P1,
777 ConstantInt *const *P2) {
778 const ConstantInt *LHS = *P1;
779 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000780 if (LHS->getValue().ult(RHS->getValue()))
781 return 1;
782 if (LHS->getValue() == RHS->getValue())
783 return 0;
784 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000785}
786
Andrew Trick3051aa12012-08-29 21:46:38 +0000787static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000788 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000789 if (ProfMD && ProfMD->getOperand(0))
790 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
791 return MDS->getString().equals("branch_weights");
792
793 return false;
794}
795
Manman Ren571d9e42012-09-11 17:43:35 +0000796/// Get Weights of a given TerminatorInst, the default weight is at the front
797/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
798/// metadata.
799static void GetBranchWeights(TerminatorInst *TI,
800 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000801 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000802 assert(MD);
803 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000804 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000805 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000806 }
807
Manman Ren571d9e42012-09-11 17:43:35 +0000808 // If TI is a conditional eq, the default case is the false case,
809 // and the corresponding branch-weight data is at index 2. We swap the
810 // default weight to be the first entry.
811 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
812 assert(Weights.size() == 2);
813 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
814 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
815 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000816 }
817}
818
Manman Renf1cb16e2014-01-27 23:39:03 +0000819/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000820static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000821 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
822 if (Max > UINT_MAX) {
823 unsigned Offset = 32 - countLeadingZeros(Max);
824 for (uint64_t &I : Weights)
825 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000826 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000827}
828
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000829/// The specified terminator is a value equality comparison instruction
830/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000831/// See if any of the predecessors of the terminator block are value comparisons
832/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000833bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
834 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000835 BasicBlock *BB = TI->getParent();
836 Value *CV = isValueEqualityComparison(TI); // CondVal
837 assert(CV && "Not a comparison?");
838 bool Changed = false;
839
Chris Lattner6b39cb92008-02-18 07:42:56 +0000840 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000841 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000842 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000843
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000844 // See if the predecessor is a comparison with the same value.
845 TerminatorInst *PTI = Pred->getTerminator();
846 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
847
848 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
849 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000850 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000851 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
852
Eric Christopherb65acc62012-07-02 23:22:21 +0000853 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000854 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
855
856 // Based on whether the default edge from PTI goes to BB or not, fill in
857 // PredCases and PredDefault with the new switch cases we would like to
858 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000859 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000860
Andrew Trick3051aa12012-08-29 21:46:38 +0000861 // Update the branch weight metadata along the way
862 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000863 bool PredHasWeights = HasBranchWeights(PTI);
864 bool SuccHasWeights = HasBranchWeights(TI);
865
Manman Ren5e5049d2012-09-14 19:05:19 +0000866 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000867 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000868 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000869 if (Weights.size() != 1 + PredCases.size())
870 PredHasWeights = SuccHasWeights = false;
871 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000872 // If there are no predecessor weights but there are successor weights,
873 // populate Weights with 1, which will later be scaled to the sum of
874 // successor's weights
875 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000876
Manman Ren571d9e42012-09-11 17:43:35 +0000877 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000878 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000879 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000880 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000881 if (SuccWeights.size() != 1 + BBCases.size())
882 PredHasWeights = SuccHasWeights = false;
883 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000884 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000885
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000886 if (PredDefault == BB) {
887 // If this is the default destination from PTI, only the edges in TI
888 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000889 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
890 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
891 if (PredCases[i].Dest != BB)
892 PTIHandled.insert(PredCases[i].Value);
893 else {
894 // The default destination is BB, we don't need explicit targets.
895 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000896
Manman Ren571d9e42012-09-11 17:43:35 +0000897 if (PredHasWeights || SuccHasWeights) {
898 // Increase weight for the default case.
899 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000900 std::swap(Weights[i+1], Weights.back());
901 Weights.pop_back();
902 }
903
Eric Christopherb65acc62012-07-02 23:22:21 +0000904 PredCases.pop_back();
905 --i; --e;
906 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000907
Eric Christopherb65acc62012-07-02 23:22:21 +0000908 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000909 if (PredDefault != BBDefault) {
910 PredDefault->removePredecessor(Pred);
911 PredDefault = BBDefault;
912 NewSuccessors.push_back(BBDefault);
913 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000914
Manman Ren571d9e42012-09-11 17:43:35 +0000915 unsigned CasesFromPred = Weights.size();
916 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000917 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
918 if (!PTIHandled.count(BBCases[i].Value) &&
919 BBCases[i].Dest != BBDefault) {
920 PredCases.push_back(BBCases[i]);
921 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000922 if (SuccHasWeights || PredHasWeights) {
923 // The default weight is at index 0, so weight for the ith case
924 // should be at index i+1. Scale the cases from successor by
925 // PredDefaultWeight (Weights[0]).
926 Weights.push_back(Weights[0] * SuccWeights[i+1]);
927 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000928 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000929 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000930
Manman Ren571d9e42012-09-11 17:43:35 +0000931 if (SuccHasWeights || PredHasWeights) {
932 ValidTotalSuccWeight += SuccWeights[0];
933 // Scale the cases from predecessor by ValidTotalSuccWeight.
934 for (unsigned i = 1; i < CasesFromPred; ++i)
935 Weights[i] *= ValidTotalSuccWeight;
936 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
937 Weights[0] *= SuccWeights[0];
938 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000939 } else {
940 // If this is not the default destination from PSI, only the edges
941 // in SI that occur in PSI with a destination of BB will be
942 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000943 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000944 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000945 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
946 if (PredCases[i].Dest == BB) {
947 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000948
949 if (PredHasWeights || SuccHasWeights) {
950 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
951 std::swap(Weights[i+1], Weights.back());
952 Weights.pop_back();
953 }
954
Eric Christopherb65acc62012-07-02 23:22:21 +0000955 std::swap(PredCases[i], PredCases.back());
956 PredCases.pop_back();
957 --i; --e;
958 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000959
960 // Okay, now we know which constants were sent to BB from the
961 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000962 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
963 if (PTIHandled.count(BBCases[i].Value)) {
964 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000965 if (PredHasWeights || SuccHasWeights)
966 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000967 PredCases.push_back(BBCases[i]);
968 NewSuccessors.push_back(BBCases[i].Dest);
969 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
970 }
971
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000972 // If there are any constants vectored to BB that TI doesn't handle,
973 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000974 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000975 PTIHandled.begin(),
976 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000977 if (PredHasWeights || SuccHasWeights)
978 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000979 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000980 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000981 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000982 }
983
984 // Okay, at this point, we know which new successor Pred will get. Make
985 // sure we update the number of entries in the PHI nodes for these
986 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +0000987 for (BasicBlock *NewSuccessor : NewSuccessors)
988 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000989
Devang Patel58380552011-05-18 20:53:17 +0000990 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000991 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +0000992 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000993 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +0000994 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000995 }
996
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000997 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +0000998 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
999 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001000 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +00001001 for (ValueEqualityComparisonCase &V : PredCases)
1002 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001003
Andrew Trick3051aa12012-08-29 21:46:38 +00001004 if (PredHasWeights || SuccHasWeights) {
1005 // Halve the weights if any of them cannot fit in an uint32_t
1006 FitWeights(Weights);
1007
1008 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1009
1010 NewSI->setMetadata(LLVMContext::MD_prof,
1011 MDBuilder(BB->getContext()).
1012 createBranchWeights(MDWeights));
1013 }
1014
Eli Friedmancb61afb2008-12-16 20:54:32 +00001015 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001016
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001017 // Okay, last check. If BB is still a successor of PSI, then we must
1018 // have an infinite loop case. If so, add an infinitely looping block
1019 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001020 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001021 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1022 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001023 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001024 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001025 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00001026 InfLoopBlock = BasicBlock::Create(BB->getContext(),
1027 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001028 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001029 }
1030 NewSI->setSuccessor(i, InfLoopBlock);
1031 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001032
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001033 Changed = true;
1034 }
1035 }
1036 return Changed;
1037}
1038
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001039// If we would need to insert a select that uses the value of this invoke
1040// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1041// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001042static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1043 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001044 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001045 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001046 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001047 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1048 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1049 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1050 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1051 return false;
1052 }
1053 }
1054 }
1055 return true;
1056}
1057
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001058static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1059
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001060/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1061/// in the two blocks up into the branch block. The caller of this function
1062/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001063static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001064 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001065 // This does very trivial matching, with limited scanning, to find identical
1066 // instructions in the two blocks. In particular, we don't want to get into
1067 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1068 // such, we currently just scan for obviously identical instructions in an
1069 // identical order.
1070 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1071 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1072
Devang Patelf10e2872009-02-04 00:03:08 +00001073 BasicBlock::iterator BB1_Itr = BB1->begin();
1074 BasicBlock::iterator BB2_Itr = BB2->begin();
1075
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001076 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001077 // Skip debug info if it is not identical.
1078 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1079 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1080 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1081 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001082 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001083 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001084 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001085 }
Devang Patele48ddf82011-04-07 00:30:15 +00001086 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001087 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001088 return false;
1089
Chris Lattner389cfac2004-11-30 00:29:14 +00001090 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001091
David Majnemerc82f27a2013-06-03 20:43:12 +00001092 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001093 do {
1094 // If we are hoisting the terminator instruction, don't move one (making a
1095 // broken BB), instead clone it, and remove BI.
1096 if (isa<TerminatorInst>(I1))
1097 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001098
Chad Rosier54390052015-02-23 19:15:16 +00001099 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1100 return Changed;
1101
Chris Lattner389cfac2004-11-30 00:29:14 +00001102 // For a normal instruction, we just move one to right before the branch,
1103 // then replace all uses of the other with the first. Finally, we remove
1104 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001105 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001106 if (!I2->use_empty())
1107 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001108 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001109 unsigned KnownIDs[] = {
Piotr Padlewskidc9b2cf2015-10-02 22:12:22 +00001110 LLVMContext::MD_tbaa, LLVMContext::MD_range,
1111 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
Artur Pilipenko5c5011d2015-11-02 17:53:51 +00001112 LLVMContext::MD_nonnull, LLVMContext::MD_invariant_group,
1113 LLVMContext::MD_align, LLVMContext::MD_dereferenceable,
1114 LLVMContext::MD_dereferenceable_or_null};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001115 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001116 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001117 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001118
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001119 I1 = &*BB1_Itr++;
1120 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001121 // Skip debug info if it is not identical.
1122 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1123 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1124 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1125 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001126 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001127 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001128 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001129 }
Devang Patele48ddf82011-04-07 00:30:15 +00001130 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001131
1132 return true;
1133
1134HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001135 // It may not be possible to hoist an invoke.
1136 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001137 return Changed;
1138
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001139 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001140 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001141 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001142 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1143 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1144 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1145 if (BB1V == BB2V)
1146 continue;
1147
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001148 // Check for passingValueIsAlwaysUndefined here because we would rather
1149 // eliminate undefined control flow then converting it to a select.
1150 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1151 passingValueIsAlwaysUndefined(BB2V, PN))
1152 return Changed;
1153
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001154 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001155 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001156 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001157 return Changed;
1158 }
1159 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001160
Chris Lattner389cfac2004-11-30 00:29:14 +00001161 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001162 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001163 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001164 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001165 I1->replaceAllUsesWith(NT);
1166 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001167 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001168 }
1169
Devang Patel1407fb42011-05-19 20:52:46 +00001170 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001171 // Hoisting one of the terminators from our successor is a great thing.
1172 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1173 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1174 // nodes, so we insert select instruction to compute the final result.
1175 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001176 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001177 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001178 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001179 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001180 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1181 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001182 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001183
Chris Lattner4088e2b2010-12-13 01:47:07 +00001184 // These values do not agree. Insert a select instruction before NT
1185 // that determines the right value.
1186 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001187 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001188 SI = cast<SelectInst>
1189 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1190 BB1V->getName()+"."+BB2V->getName()));
1191
Chris Lattner4088e2b2010-12-13 01:47:07 +00001192 // Make the PHI node use the select for all incoming values for BB1/BB2
1193 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1194 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1195 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001196 }
1197 }
1198
1199 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001200 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1201 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001202
Eli Friedmancb61afb2008-12-16 20:54:32 +00001203 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001204 return true;
1205}
1206
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001207/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001208/// check whether BBEnd has only two predecessors and the other predecessor
1209/// ends with an unconditional branch. If it is true, sink any common code
1210/// in the two predecessors to BBEnd.
1211static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1212 assert(BI1->isUnconditional());
1213 BasicBlock *BB1 = BI1->getParent();
1214 BasicBlock *BBEnd = BI1->getSuccessor(0);
1215
1216 // Check that BBEnd has two predecessors and the other predecessor ends with
1217 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001218 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1219 BasicBlock *Pred0 = *PI++;
1220 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001221 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001222 BasicBlock *Pred1 = *PI++;
1223 if (PI != PE) // More than two predecessors.
1224 return false;
1225 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001226 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1227 if (!BI2 || !BI2->isUnconditional())
1228 return false;
1229
1230 // Gather the PHI nodes in BBEnd.
Michael Liao5313da32014-12-23 08:26:55 +00001231 SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
Craig Topperf40110f2014-04-25 05:29:35 +00001232 Instruction *FirstNonPhiInBBEnd = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001233 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
Manman Ren93ab6492012-09-20 22:37:36 +00001234 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1235 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001236 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Michael Liao5313da32014-12-23 08:26:55 +00001237 JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
Manman Ren93ab6492012-09-20 22:37:36 +00001238 } else {
1239 FirstNonPhiInBBEnd = &*I;
1240 break;
1241 }
1242 }
1243 if (!FirstNonPhiInBBEnd)
1244 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001245
Manman Ren93ab6492012-09-20 22:37:36 +00001246 // This does very trivial matching, with limited scanning, to find identical
1247 // instructions in the two blocks. We scan backward for obviously identical
1248 // instructions in an identical order.
1249 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
Michael Liao5313da32014-12-23 08:26:55 +00001250 RE1 = BB1->getInstList().rend(),
1251 RI2 = BB2->getInstList().rbegin(),
1252 RE2 = BB2->getInstList().rend();
Manman Ren93ab6492012-09-20 22:37:36 +00001253 // Skip debug info.
1254 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1255 if (RI1 == RE1)
1256 return false;
1257 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1258 if (RI2 == RE2)
1259 return false;
1260 // Skip the unconditional branches.
1261 ++RI1;
1262 ++RI2;
1263
1264 bool Changed = false;
1265 while (RI1 != RE1 && RI2 != RE2) {
1266 // Skip debug info.
1267 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1268 if (RI1 == RE1)
1269 return Changed;
1270 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1271 if (RI2 == RE2)
1272 return Changed;
1273
1274 Instruction *I1 = &*RI1, *I2 = &*RI2;
Michael Liao5313da32014-12-23 08:26:55 +00001275 auto InstPair = std::make_pair(I1, I2);
Manman Ren93ab6492012-09-20 22:37:36 +00001276 // I1 and I2 should have a single use in the same PHI node, and they
1277 // perform the same operation.
1278 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1279 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1280 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
David Majnemerba275f92015-08-19 19:54:02 +00001281 I1->isEHPad() || I2->isEHPad() ||
Manman Ren93ab6492012-09-20 22:37:36 +00001282 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1283 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1284 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1285 !I1->hasOneUse() || !I2->hasOneUse() ||
Michael Liao5313da32014-12-23 08:26:55 +00001286 !JointValueMap.count(InstPair))
Manman Ren93ab6492012-09-20 22:37:36 +00001287 return Changed;
1288
1289 // Check whether we should swap the operands of ICmpInst.
Michael Liao5313da32014-12-23 08:26:55 +00001290 // TODO: Add support of communativity.
Manman Ren93ab6492012-09-20 22:37:36 +00001291 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1292 bool SwapOpnds = false;
1293 if (ICmp1 && ICmp2 &&
1294 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1295 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1296 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1297 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1298 ICmp2->swapOperands();
1299 SwapOpnds = true;
1300 }
1301 if (!I1->isSameOperationAs(I2)) {
1302 if (SwapOpnds)
1303 ICmp2->swapOperands();
1304 return Changed;
1305 }
1306
1307 // The operands should be either the same or they need to be generated
1308 // with a PHI node after sinking. We only handle the case where there is
1309 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001310 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Michael Liao5313da32014-12-23 08:26:55 +00001311 unsigned Op1Idx = ~0U;
Manman Ren93ab6492012-09-20 22:37:36 +00001312 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1313 if (I1->getOperand(I) == I2->getOperand(I))
1314 continue;
Michael Liao5313da32014-12-23 08:26:55 +00001315 // Early exit if we have more-than one pair of different operands or if
1316 // we need a PHI node to replace a constant.
1317 if (Op1Idx != ~0U ||
Manman Ren93ab6492012-09-20 22:37:36 +00001318 isa<Constant>(I1->getOperand(I)) ||
1319 isa<Constant>(I2->getOperand(I))) {
1320 // If we can't sink the instructions, undo the swapping.
1321 if (SwapOpnds)
1322 ICmp2->swapOperands();
1323 return Changed;
1324 }
1325 DifferentOp1 = I1->getOperand(I);
1326 Op1Idx = I;
1327 DifferentOp2 = I2->getOperand(I);
1328 }
1329
Michael Liao5313da32014-12-23 08:26:55 +00001330 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
1331 DEBUG(dbgs() << " " << *I2 << "\n");
1332
1333 // We insert the pair of different operands to JointValueMap and
1334 // remove (I1, I2) from JointValueMap.
1335 if (Op1Idx != ~0U) {
1336 auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
1337 if (!NewPN) {
1338 NewPN =
1339 PHINode::Create(DifferentOp1->getType(), 2,
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001340 DifferentOp1->getName() + ".sink", &BBEnd->front());
Michael Liao5313da32014-12-23 08:26:55 +00001341 NewPN->addIncoming(DifferentOp1, BB1);
1342 NewPN->addIncoming(DifferentOp2, BB2);
1343 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1344 }
Manman Ren93ab6492012-09-20 22:37:36 +00001345 // I1 should use NewPN instead of DifferentOp1.
1346 I1->setOperand(Op1Idx, NewPN);
Manman Ren93ab6492012-09-20 22:37:36 +00001347 }
Michael Liao5313da32014-12-23 08:26:55 +00001348 PHINode *OldPN = JointValueMap[InstPair];
1349 JointValueMap.erase(InstPair);
Manman Ren93ab6492012-09-20 22:37:36 +00001350
Manman Ren93ab6492012-09-20 22:37:36 +00001351 // We need to update RE1 and RE2 if we are going to sink the first
1352 // instruction in the basic block down.
1353 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1354 // Sink the instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001355 BBEnd->getInstList().splice(FirstNonPhiInBBEnd->getIterator(),
1356 BB1->getInstList(), I1);
Manman Ren93ab6492012-09-20 22:37:36 +00001357 if (!OldPN->use_empty())
1358 OldPN->replaceAllUsesWith(I1);
1359 OldPN->eraseFromParent();
1360
1361 if (!I2->use_empty())
1362 I2->replaceAllUsesWith(I1);
1363 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001364 // TODO: Use combineMetadata here to preserve what metadata we can
1365 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001366 I2->eraseFromParent();
1367
1368 if (UpdateRE1)
1369 RE1 = BB1->getInstList().rend();
1370 if (UpdateRE2)
1371 RE2 = BB2->getInstList().rend();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001372 FirstNonPhiInBBEnd = &*I1;
Manman Ren93ab6492012-09-20 22:37:36 +00001373 NumSinkCommons++;
1374 Changed = true;
1375 }
1376 return Changed;
1377}
1378
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001379/// \brief Determine if we can hoist sink a sole store instruction out of a
1380/// conditional block.
1381///
1382/// We are looking for code like the following:
1383/// BrBB:
1384/// store i32 %add, i32* %arrayidx2
1385/// ... // No other stores or function calls (we could be calling a memory
1386/// ... // function).
1387/// %cmp = icmp ult %x, %y
1388/// br i1 %cmp, label %EndBB, label %ThenBB
1389/// ThenBB:
1390/// store i32 %add5, i32* %arrayidx2
1391/// br label EndBB
1392/// EndBB:
1393/// ...
1394/// We are going to transform this into:
1395/// BrBB:
1396/// store i32 %add, i32* %arrayidx2
1397/// ... //
1398/// %cmp = icmp ult %x, %y
1399/// %add.add5 = select i1 %cmp, i32 %add, %add5
1400/// store i32 %add.add5, i32* %arrayidx2
1401/// ...
1402///
1403/// \return The pointer to the value of the previous store if the store can be
1404/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001405static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1406 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001407 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1408 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001409 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001410
1411 // Volatile or atomic.
1412 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001413 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001414
1415 Value *StorePtr = StoreToHoist->getPointerOperand();
1416
1417 // Look for a store to the same pointer in BrBB.
1418 unsigned MaxNumInstToLookAt = 10;
1419 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1420 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1421 Instruction *CurI = &*RI;
1422
1423 // Could be calling an instruction that effects memory like free().
1424 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001425 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001426
1427 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1428 // Found the previous store make sure it stores to the same location.
1429 if (SI && SI->getPointerOperand() == StorePtr)
1430 // Found the previous store, return its value operand.
1431 return SI->getValueOperand();
1432 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001433 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001434 }
1435
Craig Topperf40110f2014-04-25 05:29:35 +00001436 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001437}
1438
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001439/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001440///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001441/// Note that this is a very risky transform currently. Speculating
1442/// instructions like this is most often not desirable. Instead, there is an MI
1443/// pass which can do it with full awareness of the resource constraints.
1444/// However, some cases are "obvious" and we should do directly. An example of
1445/// this is speculating a single, reasonably cheap instruction.
1446///
1447/// There is only one distinct advantage to flattening the CFG at the IR level:
1448/// it makes very common but simplistic optimizations such as are common in
1449/// instcombine and the DAG combiner more powerful by removing CFG edges and
1450/// modeling their effects with easier to reason about SSA value graphs.
1451///
1452///
1453/// An illustration of this transform is turning this IR:
1454/// \code
1455/// BB:
1456/// %cmp = icmp ult %x, %y
1457/// br i1 %cmp, label %EndBB, label %ThenBB
1458/// ThenBB:
1459/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001460/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001461/// EndBB:
1462/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1463/// ...
1464/// \endcode
1465///
1466/// Into this IR:
1467/// \code
1468/// BB:
1469/// %cmp = icmp ult %x, %y
1470/// %sub = sub %x, %y
1471/// %cond = select i1 %cmp, 0, %sub
1472/// ...
1473/// \endcode
1474///
1475/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001476static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001477 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001478 // Be conservative for now. FP select instruction can often be expensive.
1479 Value *BrCond = BI->getCondition();
1480 if (isa<FCmpInst>(BrCond))
1481 return false;
1482
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001483 BasicBlock *BB = BI->getParent();
1484 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1485
1486 // If ThenBB is actually on the false edge of the conditional branch, remember
1487 // to swap the select operands later.
1488 bool Invert = false;
1489 if (ThenBB != BI->getSuccessor(0)) {
1490 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1491 Invert = true;
1492 }
1493 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1494
Chandler Carruthceff2222013-01-25 05:40:09 +00001495 // Keep a count of how many times instructions are used within CondBB when
1496 // they are candidates for sinking into CondBB. Specifically:
1497 // - They are defined in BB, and
1498 // - They have no side effects, and
1499 // - All of their uses are in CondBB.
1500 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1501
Chandler Carruth7481ca82013-01-24 11:52:58 +00001502 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001503 Value *SpeculatedStoreValue = nullptr;
1504 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001505 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001506 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001507 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001508 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001509 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001510 if (isa<DbgInfoIntrinsic>(I))
1511 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001512
Mark Lacey274f48b2015-04-12 18:18:51 +00001513 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001514 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001515 ++SpeculationCost;
1516 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001517 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001518
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001519 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001520 if (!isSafeToSpeculativelyExecute(I) &&
1521 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1522 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001523 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001524 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001525 ComputeSpeculationCost(I, TTI) >
1526 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001527 return false;
1528
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001529 // Store the store speculation candidate.
1530 if (SpeculatedStoreValue)
1531 SpeculatedStore = cast<StoreInst>(I);
1532
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001533 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001534 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001535 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001536 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001537 i != e; ++i) {
1538 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001539 if (!OpI || OpI->getParent() != BB ||
1540 OpI->mayHaveSideEffects())
1541 continue; // Not a candidate for sinking.
1542
1543 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001544 }
1545 }
Evan Cheng89200c92008-06-07 08:52:29 +00001546
Chandler Carruthceff2222013-01-25 05:40:09 +00001547 // Consider any sink candidates which are only used in CondBB as costs for
1548 // speculation. Note, while we iterate over a DenseMap here, we are summing
1549 // and so iteration order isn't significant.
1550 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1551 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1552 I != E; ++I)
1553 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001554 ++SpeculationCost;
1555 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001556 return false;
1557 }
1558
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001559 // Check that the PHI nodes can be converted to selects.
1560 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001561 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001562 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001563 Value *OrigV = PN->getIncomingValueForBlock(BB);
1564 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001565
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001566 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001567 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001568 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001569 continue;
1570
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001571 // Don't convert to selects if we could remove undefined behavior instead.
1572 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1573 passingValueIsAlwaysUndefined(ThenV, PN))
1574 return false;
1575
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001576 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001577 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1578 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1579 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001580 continue; // Known safe and cheap.
1581
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001582 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1583 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001584 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001585 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
1586 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
James Molloy7c336572015-02-11 12:15:41 +00001587 unsigned MaxCost = 2 * PHINodeFoldingThreshold *
1588 TargetTransformInfo::TCC_Basic;
1589 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00001590 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001591
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001592 // Account for the cost of an unfolded ConstantExpr which could end up
1593 // getting expanded into Instructions.
1594 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001595 // constant expression.
1596 ++SpeculationCost;
1597 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001598 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001599 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001600
1601 // If there are no PHIs to process, bail early. This helps ensure idempotence
1602 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001603 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001604 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001605
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001606 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001607 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001608
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001609 // Insert a select of the value of the speculated store.
1610 if (SpeculatedStoreValue) {
1611 IRBuilder<true, NoFolder> Builder(BI);
1612 Value *TrueV = SpeculatedStore->getValueOperand();
1613 Value *FalseV = SpeculatedStoreValue;
1614 if (Invert)
1615 std::swap(TrueV, FalseV);
1616 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1617 "." + FalseV->getName());
1618 SpeculatedStore->setOperand(0, S);
1619 }
1620
Chandler Carruth7481ca82013-01-24 11:52:58 +00001621 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001622 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
1623 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001624
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001625 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001626 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001627 for (BasicBlock::iterator I = EndBB->begin();
1628 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1629 unsigned OrigI = PN->getBasicBlockIndex(BB);
1630 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1631 Value *OrigV = PN->getIncomingValue(OrigI);
1632 Value *ThenV = PN->getIncomingValue(ThenI);
1633
1634 // Skip PHIs which are trivial.
1635 if (OrigV == ThenV)
1636 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001637
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001638 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001639 // false value is the preexisting value. Swap them if the branch
1640 // destinations were inverted.
1641 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001642 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001643 std::swap(TrueV, FalseV);
1644 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1645 TrueV->getName() + "." + FalseV->getName());
1646 PN->setIncomingValue(OrigI, V);
1647 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001648 }
1649
Evan Cheng89553cc2008-06-12 21:15:59 +00001650 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001651 return true;
1652}
1653
Tom Stellarde1631dd2013-10-21 20:07:30 +00001654/// \returns True if this block contains a CallInst with the NoDuplicate
1655/// attribute.
1656static bool HasNoDuplicateCall(const BasicBlock *BB) {
1657 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1658 const CallInst *CI = dyn_cast<CallInst>(I);
1659 if (!CI)
1660 continue;
1661 if (CI->cannotDuplicate())
1662 return true;
1663 }
1664 return false;
1665}
1666
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001667/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001668static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1669 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001670 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001671
Devang Patel84fceff2009-03-10 18:00:05 +00001672 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001673 if (isa<DbgInfoIntrinsic>(BBI))
1674 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001675 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001676 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001677
Dale Johannesened6f5a82009-03-12 23:18:09 +00001678 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001679 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001680 for (User *U : BBI->users()) {
1681 Instruction *UI = cast<Instruction>(U);
1682 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001683 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001684
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001685 // Looks ok, continue checking.
1686 }
Chris Lattner6c701062005-09-20 01:48:40 +00001687
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001688 return true;
1689}
1690
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001691/// If we have a conditional branch on a PHI node value that is defined in the
1692/// same block as the branch and if any PHI entries are constants, thread edges
1693/// corresponding to that entry to be branches to their ultimate destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001694static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001695 BasicBlock *BB = BI->getParent();
1696 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001697 // NOTE: we currently cannot transform this case if the PHI node is used
1698 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001699 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1700 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001701
Chris Lattner748f9032005-09-19 23:49:37 +00001702 // Degenerate case of a single entry PHI.
1703 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001704 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001705 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001706 }
1707
1708 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001709 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001710
Tom Stellarde1631dd2013-10-21 20:07:30 +00001711 if (HasNoDuplicateCall(BB)) return false;
1712
Chris Lattner748f9032005-09-19 23:49:37 +00001713 // Okay, this is a simple enough basic block. See if any phi values are
1714 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001715 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001716 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001717 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001718
Chris Lattner4088e2b2010-12-13 01:47:07 +00001719 // Okay, we now know that all edges from PredBB should be revectored to
1720 // branch to RealDest.
1721 BasicBlock *PredBB = PN->getIncomingBlock(i);
1722 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001723
Chris Lattner4088e2b2010-12-13 01:47:07 +00001724 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001725 // Skip if the predecessor's terminator is an indirect branch.
1726 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001727
Chris Lattner4088e2b2010-12-13 01:47:07 +00001728 // The dest block might have PHI nodes, other predecessors and other
1729 // difficult cases. Instead of being smart about this, just insert a new
1730 // block that jumps to the destination block, effectively splitting
1731 // the edge we are about to create.
1732 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1733 RealDest->getName()+".critedge",
1734 RealDest->getParent(), RealDest);
1735 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001736
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001737 // Update PHI nodes.
1738 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001739
1740 // BB may have instructions that are being threaded over. Clone these
1741 // instructions into EdgeBB. We know that there will be no uses of the
1742 // cloned instructions outside of EdgeBB.
1743 BasicBlock::iterator InsertPt = EdgeBB->begin();
1744 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1745 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1746 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1747 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1748 continue;
1749 }
1750 // Clone the instruction.
1751 Instruction *N = BBI->clone();
1752 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001753
Chris Lattner4088e2b2010-12-13 01:47:07 +00001754 // Update operands due to translation.
1755 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1756 i != e; ++i) {
1757 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1758 if (PI != TranslateMap.end())
1759 *i = PI->second;
1760 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001761
Chris Lattner4088e2b2010-12-13 01:47:07 +00001762 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001763 if (Value *V = SimplifyInstruction(N, DL)) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001764 TranslateMap[&*BBI] = V;
Chris Lattnerd7beca32010-12-14 06:17:25 +00001765 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001766 } else {
1767 // Insert the new instruction into its new home.
1768 EdgeBB->getInstList().insert(InsertPt, N);
1769 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001770 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001771 }
1772 }
1773
1774 // Loop over all of the edges from PredBB to BB, changing them to branch
1775 // to EdgeBB instead.
1776 TerminatorInst *PredBBTI = PredBB->getTerminator();
1777 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1778 if (PredBBTI->getSuccessor(i) == BB) {
1779 BB->removePredecessor(PredBB);
1780 PredBBTI->setSuccessor(i, EdgeBB);
1781 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001782
Chris Lattner4088e2b2010-12-13 01:47:07 +00001783 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001784 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001785 }
Chris Lattner748f9032005-09-19 23:49:37 +00001786
1787 return false;
1788}
1789
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001790/// Given a BB that starts with the specified two-entry PHI node,
1791/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001792static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
1793 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001794 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1795 // statement", which has a very simple dominance structure. Basically, we
1796 // are trying to find the condition that is being branched on, which
1797 // subsequently causes this merge to happen. We really want control
1798 // dependence information for this check, but simplifycfg can't keep it up
1799 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001800 BasicBlock *BB = PN->getParent();
1801 BasicBlock *IfTrue, *IfFalse;
1802 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001803 if (!IfCond ||
1804 // Don't bother if the branch will be constant folded trivially.
1805 isa<ConstantInt>(IfCond))
1806 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001807
Chris Lattner95adf8f12006-11-18 19:19:36 +00001808 // Okay, we found that we can merge this two-entry phi node into a select.
1809 // Doing so would require us to fold *all* two entry phi nodes in this block.
1810 // At some point this becomes non-profitable (particularly if the target
1811 // doesn't support cmov's). Only do this transformation if there are two or
1812 // fewer PHI nodes in this block.
1813 unsigned NumPhis = 0;
1814 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1815 if (NumPhis > 2)
1816 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001817
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001818 // Loop over the PHI's seeing if we can promote them all to select
1819 // instructions. While we are at it, keep track of the instructions
1820 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001821 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001822 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1823 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00001824 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
1825 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001826
Chris Lattner7499b452010-12-14 08:46:09 +00001827 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1828 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001829 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001830 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001831 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001832 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001833 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001834
Peter Collingbournee3511e12011-04-29 18:47:31 +00001835 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001836 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001837 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001838 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001839 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001840 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001841
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001842 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001843 // we ran out of PHIs then we simplified them all.
1844 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001845 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001846
Chris Lattner7499b452010-12-14 08:46:09 +00001847 // Don't fold i1 branches on PHIs which contain binary operators. These can
1848 // often be turned into switches and other things.
1849 if (PN->getType()->isIntegerTy(1) &&
1850 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1851 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1852 isa<BinaryOperator>(IfCond)))
1853 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001854
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001855 // If we all PHI nodes are promotable, check to make sure that all
1856 // instructions in the predecessor blocks can be promoted as well. If
1857 // not, we won't be able to get rid of the control flow, so it's not
1858 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001859 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001860 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1861 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1862 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001863 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001864 } else {
1865 DomBlock = *pred_begin(IfBlock1);
1866 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +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 Lattner9ac168d2010-12-14 07:41:39 +00001875 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001876 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001877 } else {
1878 DomBlock = *pred_begin(IfBlock2);
1879 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001880 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001881 // This is not an aggressive instruction that we can promote.
1882 // Because of this, we won't be able to get rid of the control
1883 // flow, so the xform is not worth it.
1884 return false;
1885 }
1886 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001887
Chris Lattner9fd838d2010-12-14 07:23:10 +00001888 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001889 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001890
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001891 // If we can still promote the PHI nodes after this gauntlet of tests,
1892 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001893 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001894 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001895
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001896 // Move all 'aggressive' instructions, which are defined in the
1897 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001898 if (IfBlock1)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001899 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001900 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001901 IfBlock1->getTerminator()->getIterator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001902 if (IfBlock2)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001903 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00001904 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001905 IfBlock2->getTerminator()->getIterator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001906
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001907 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1908 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001909 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1910 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001911
1912 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001913 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001914 PN->replaceAllUsesWith(NV);
1915 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001916 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001917 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001918
Chris Lattner335f0e42010-12-14 08:01:53 +00001919 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1920 // has been flattened. Change DomBlock to jump directly to our new block to
1921 // avoid other simplifycfg's kicking in on the diamond.
1922 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001923 Builder.SetInsertPoint(OldTI);
1924 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001925 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001926 return true;
1927}
Chris Lattner748f9032005-09-19 23:49:37 +00001928
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001929/// If we found a conditional branch that goes to two returning blocks,
1930/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00001931/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001932static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001933 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001934 assert(BI->isConditional() && "Must be a conditional branch");
1935 BasicBlock *TrueSucc = BI->getSuccessor(0);
1936 BasicBlock *FalseSucc = BI->getSuccessor(1);
1937 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1938 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001939
Chris Lattner86bbf332008-04-24 00:01:19 +00001940 // Check to ensure both blocks are empty (just a return) or optionally empty
1941 // with PHI nodes. If there are other instructions, merging would cause extra
1942 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001943 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001944 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001945 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001946 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001947
Devang Pateldd14e0f2011-05-18 21:33:11 +00001948 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001949 // Okay, we found a branch that is going to two return nodes. If
1950 // there is no return value for this function, just change the
1951 // branch into a return.
1952 if (FalseRet->getNumOperands() == 0) {
1953 TrueSucc->removePredecessor(BI->getParent());
1954 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001955 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001956 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001957 return true;
1958 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001959
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001960 // Otherwise, figure out what the true and false return values are
1961 // so we can insert a new select instruction.
1962 Value *TrueValue = TrueRet->getReturnValue();
1963 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001964
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001965 // Unwrap any PHI nodes in the return blocks.
1966 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1967 if (TVPN->getParent() == TrueSucc)
1968 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1969 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1970 if (FVPN->getParent() == FalseSucc)
1971 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001972
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001973 // In order for this transformation to be safe, we must be able to
1974 // unconditionally execute both operands to the return. This is
1975 // normally the case, but we could have a potentially-trapping
1976 // constant expression that prevents this transformation from being
1977 // safe.
1978 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1979 if (TCV->canTrap())
1980 return false;
1981 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1982 if (FCV->canTrap())
1983 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001984
Chris Lattner86bbf332008-04-24 00:01:19 +00001985 // Okay, we collected all the mapped values and checked them for sanity, and
1986 // defined to really do this transformation. First, update the CFG.
1987 TrueSucc->removePredecessor(BI->getParent());
1988 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001989
Chris Lattner86bbf332008-04-24 00:01:19 +00001990 // Insert select instructions where needed.
1991 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001992 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001993 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001994 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1995 } else if (isa<UndefValue>(TrueValue)) {
1996 TrueValue = FalseValue;
1997 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00001998 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1999 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00002000 }
Chris Lattner86bbf332008-04-24 00:01:19 +00002001 }
2002
Andrew Trickf3cf1932012-08-29 21:46:36 +00002003 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00002004 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
2005
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00002006 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002007
David Greene725c7c32010-01-05 01:26:52 +00002008 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002009 << "\n " << *BI << "NewRet = " << *RI
2010 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002011
Eli Friedmancb61afb2008-12-16 20:54:32 +00002012 EraseTerminatorInstAndDCECond(BI);
2013
Chris Lattner86bbf332008-04-24 00:01:19 +00002014 return true;
2015}
2016
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002017/// Given a conditional BranchInstruction, retrieve the probabilities of the
2018/// branch taking each edge. Fills in the two APInt parameters and returns true,
2019/// or returns false if no or invalid metadata was found.
Juergen Ributzka194350a2014-12-09 17:32:12 +00002020static bool ExtractBranchMetadata(BranchInst *BI,
2021 uint64_t &ProbTrue, uint64_t &ProbFalse) {
2022 assert(BI->isConditional() &&
2023 "Looking for probabilities on unconditional branch?");
2024 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
2025 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002026 ConstantInt *CITrue =
2027 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
2028 ConstantInt *CIFalse =
2029 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00002030 if (!CITrue || !CIFalse) return false;
2031 ProbTrue = CITrue->getValue().getZExtValue();
2032 ProbFalse = CIFalse->getValue().getZExtValue();
2033 return true;
2034}
2035
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002036/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002037/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002038static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002039 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2040 return false;
2041 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
2042 Instruction *PBI = &*I;
2043 // Check whether Inst and PBI generate the same value.
2044 if (Inst->isIdenticalTo(PBI)) {
2045 Inst->replaceAllUsesWith(PBI);
2046 Inst->eraseFromParent();
2047 return true;
2048 }
2049 }
2050 return false;
2051}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002052
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002053/// If this basic block is simple enough, and if a predecessor branches to us
2054/// and one of our successors, fold the block into the predecessor and use
2055/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002056bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002057 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002058
Craig Topperf40110f2014-04-25 05:29:35 +00002059 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002060 if (BI->isConditional())
2061 Cond = dyn_cast<Instruction>(BI->getCondition());
2062 else {
2063 // For unconditional branch, check for a simple CFG pattern, where
2064 // BB has a single predecessor and BB's successor is also its predecessor's
2065 // successor. If such pattern exisits, check for CSE between BB and its
2066 // predecessor.
2067 if (BasicBlock *PB = BB->getSinglePredecessor())
2068 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2069 if (PBI->isConditional() &&
2070 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2071 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2072 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2073 I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002074 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002075 if (isa<CmpInst>(Curr)) {
2076 Cond = Curr;
2077 break;
2078 }
2079 // Quit if we can't remove this instruction.
2080 if (!checkCSEInPredecessor(Curr, PB))
2081 return false;
2082 }
2083 }
2084
Craig Topperf40110f2014-04-25 05:29:35 +00002085 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002086 return false;
2087 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002088
Craig Topperf40110f2014-04-25 05:29:35 +00002089 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2090 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002091 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002092
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002093 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002094 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002095
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002096 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002097 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002098
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002099 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002100 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002101
Jingyue Wufc029672014-09-30 22:23:38 +00002102 // Only allow this transformation if computing the condition doesn't involve
2103 // too many instructions and these involved instructions can be executed
2104 // unconditionally. We denote all involved instructions except the condition
2105 // as "bonus instructions", and only allow this transformation when the
2106 // number of the bonus instructions does not exceed a certain threshold.
2107 unsigned NumBonusInsts = 0;
2108 for (auto I = BB->begin(); Cond != I; ++I) {
2109 // Ignore dbg intrinsics.
2110 if (isa<DbgInfoIntrinsic>(I))
2111 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002112 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002113 return false;
2114 // I has only one use and can be executed unconditionally.
2115 Instruction *User = dyn_cast<Instruction>(I->user_back());
2116 if (User == nullptr || User->getParent() != BB)
2117 return false;
2118 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2119 // to use any other instruction, User must be an instruction between next(I)
2120 // and Cond.
2121 ++NumBonusInsts;
2122 // Early exits once we reach the limit.
2123 if (NumBonusInsts > BonusInstThreshold)
2124 return false;
2125 }
2126
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002127 // Cond is known to be a compare or binary operator. Check to make sure that
2128 // neither operand is a potentially-trapping constant expression.
2129 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2130 if (CE->canTrap())
2131 return false;
2132 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2133 if (CE->canTrap())
2134 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002135
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002136 // Finally, don't infinitely unroll conditional loops.
2137 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002138 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002139 if (TrueDest == BB || FalseDest == BB)
2140 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002141
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002142 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2143 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002144 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002145
Chris Lattner80b03a12008-07-13 22:23:11 +00002146 // Check that we have two conditional branches. If there is a PHI node in
2147 // the common successor, verify that the same value flows in from both
2148 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002149 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002150 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002151 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002152 !SafeToMergeTerminators(BI, PBI)) ||
2153 (!BI->isConditional() &&
2154 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002155 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002156
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002157 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002158 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002159 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002160
Manman Rend33f4ef2012-06-13 05:43:29 +00002161 if (BI->isConditional()) {
2162 if (PBI->getSuccessor(0) == TrueDest)
2163 Opc = Instruction::Or;
2164 else if (PBI->getSuccessor(1) == FalseDest)
2165 Opc = Instruction::And;
2166 else if (PBI->getSuccessor(0) == FalseDest)
2167 Opc = Instruction::And, InvertPredCond = true;
2168 else if (PBI->getSuccessor(1) == TrueDest)
2169 Opc = Instruction::Or, InvertPredCond = true;
2170 else
2171 continue;
2172 } else {
2173 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2174 continue;
2175 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002176
David Greene725c7c32010-01-05 01:26:52 +00002177 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002178 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002179
Chris Lattner55eaae12008-07-13 21:20:19 +00002180 // If we need to invert the condition in the pred block to match, do so now.
2181 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002182 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002183
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002184 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2185 CmpInst *CI = cast<CmpInst>(NewCond);
2186 CI->setPredicate(CI->getInversePredicate());
2187 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002188 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002189 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002190 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002191
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002192 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002193 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002194 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002195
Jingyue Wufc029672014-09-30 22:23:38 +00002196 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002197 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002198 // bonus instructions to a predecessor block.
2199 ValueToValueMapTy VMap; // maps original values to cloned values
2200 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002201 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002202 // instructions.
2203 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2204 if (isa<DbgInfoIntrinsic>(BonusInst))
2205 continue;
2206 Instruction *NewBonusInst = BonusInst->clone();
2207 RemapInstruction(NewBonusInst, VMap,
2208 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002209 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002210
2211 // If we moved a load, we cannot any longer claim any knowledge about
2212 // its potential value. The previous information might have been valid
2213 // only given the branch precondition.
2214 // For an analogous reason, we must also drop all the metadata whose
2215 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002216 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002217
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002218 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2219 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002220 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002221 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002222
Chris Lattner55eaae12008-07-13 21:20:19 +00002223 // Clone Cond into the predecessor basic block, and or/and the
2224 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002225 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002226 RemapInstruction(New, VMap,
2227 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002228 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002229 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002230 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002231
Manman Rend33f4ef2012-06-13 05:43:29 +00002232 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002233 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002234 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002235 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002236 PBI->setCondition(NewCond);
2237
Manman Renbfb9d432012-09-15 00:39:57 +00002238 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002239 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2240 PredFalseWeight);
2241 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2242 SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002243 SmallVector<uint64_t, 8> NewWeights;
2244
Manman Rend33f4ef2012-06-13 05:43:29 +00002245 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002246 if (PredHasWeights && SuccHasWeights) {
2247 // PBI: br i1 %x, BB, FalseDest
2248 // BI: br i1 %y, TrueDest, FalseDest
2249 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2250 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2251 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2252 // TrueWeight for PBI * FalseWeight for BI.
2253 // We assume that total weights of a BranchInst can fit into 32 bits.
2254 // Therefore, we will not have overflow using 64-bit arithmetic.
2255 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2256 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2257 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002258 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2259 PBI->setSuccessor(0, TrueDest);
2260 }
2261 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002262 if (PredHasWeights && SuccHasWeights) {
2263 // PBI: br i1 %x, TrueDest, BB
2264 // BI: br i1 %y, TrueDest, FalseDest
2265 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2266 // FalseWeight for PBI * TrueWeight for BI.
2267 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2268 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2269 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2270 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2271 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002272 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2273 PBI->setSuccessor(1, FalseDest);
2274 }
Manman Renbfb9d432012-09-15 00:39:57 +00002275 if (NewWeights.size() == 2) {
2276 // Halve the weights if any of them cannot fit in an uint32_t
2277 FitWeights(NewWeights);
2278
2279 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2280 PBI->setMetadata(LLVMContext::MD_prof,
2281 MDBuilder(BI->getContext()).
2282 createBranchWeights(MDWeights));
2283 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002284 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002285 } else {
2286 // Update PHI nodes in the common successors.
2287 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002288 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002289 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2290 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002291 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002292 if (PBI->getSuccessor(0) == TrueDest) {
2293 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2294 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2295 // is false: !PBI_Cond and BI_Value
2296 Instruction *NotCond =
2297 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2298 "not.cond"));
2299 MergedCond =
2300 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2301 NotCond, New,
2302 "and.cond"));
2303 if (PBI_C->isOne())
2304 MergedCond =
2305 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2306 PBI->getCondition(), MergedCond,
2307 "or.cond"));
2308 } else {
2309 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2310 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2311 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002312 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002313 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2314 PBI->getCondition(), New,
2315 "and.cond"));
2316 if (PBI_C->isOne()) {
2317 Instruction *NotCond =
2318 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2319 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002320 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002321 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2322 NotCond, MergedCond,
2323 "or.cond"));
2324 }
2325 }
2326 // Update PHI Node.
2327 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2328 MergedCond);
2329 }
2330 // Change PBI from Conditional to Unconditional.
2331 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2332 EraseTerminatorInstAndDCECond(PBI);
2333 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002334 }
Devang Pateld715ec82011-04-06 22:37:20 +00002335
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002336 // TODO: If BB is reachable from all paths through PredBlock, then we
2337 // could replace PBI's branch probabilities with BI's.
2338
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002339 // Copy any debug value intrinsics into the end of PredBlock.
2340 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2341 if (isa<DbgInfoIntrinsic>(*I))
2342 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002343
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002344 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002345 }
2346 return false;
2347}
2348
James Molloy4de84dd2015-11-04 15:28:04 +00002349// If there is only one store in BB1 and BB2, return it, otherwise return
2350// nullptr.
2351static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2352 StoreInst *S = nullptr;
2353 for (auto *BB : {BB1, BB2}) {
2354 if (!BB)
2355 continue;
2356 for (auto &I : *BB)
2357 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2358 if (S)
2359 // Multiple stores seen.
2360 return nullptr;
2361 else
2362 S = SI;
2363 }
2364 }
2365 return S;
2366}
2367
2368static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2369 Value *AlternativeV = nullptr) {
2370 // PHI is going to be a PHI node that allows the value V that is defined in
2371 // BB to be referenced in BB's only successor.
2372 //
2373 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2374 // doesn't matter to us what the other operand is (it'll never get used). We
2375 // could just create a new PHI with an undef incoming value, but that could
2376 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2377 // other PHI. So here we directly look for some PHI in BB's successor with V
2378 // as an incoming operand. If we find one, we use it, else we create a new
2379 // one.
2380 //
2381 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2382 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2383 // where OtherBB is the single other predecessor of BB's only successor.
2384 PHINode *PHI = nullptr;
2385 BasicBlock *Succ = BB->getSingleSuccessor();
2386
2387 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2388 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2389 PHI = cast<PHINode>(I);
2390 if (!AlternativeV)
2391 break;
2392
2393 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2394 auto PredI = pred_begin(Succ);
2395 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2396 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2397 break;
2398 PHI = nullptr;
2399 }
2400 if (PHI)
2401 return PHI;
2402
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002403 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
James Molloy4de84dd2015-11-04 15:28:04 +00002404 PHI->addIncoming(V, BB);
2405 for (BasicBlock *PredBB : predecessors(Succ))
2406 if (PredBB != BB)
2407 PHI->addIncoming(AlternativeV ? AlternativeV : UndefValue::get(V->getType()),
2408 PredBB);
2409 return PHI;
2410}
2411
2412static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2413 BasicBlock *QTB, BasicBlock *QFB,
2414 BasicBlock *PostBB, Value *Address,
2415 bool InvertPCond, bool InvertQCond) {
2416 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2417 return Operator::getOpcode(&I) == Instruction::BitCast &&
2418 I.getType()->isPointerTy();
2419 };
2420
2421 // If we're not in aggressive mode, we only optimize if we have some
2422 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2423 auto IsWorthwhile = [&](BasicBlock *BB) {
2424 if (!BB)
2425 return true;
2426 // Heuristic: if the block can be if-converted/phi-folded and the
2427 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2428 // thread this store.
James Molloy9e959ac2015-11-05 08:40:19 +00002429 unsigned N = 0;
2430 for (auto &I : *BB) {
2431 // Cheap instructions viable for folding.
2432 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2433 isa<StoreInst>(I))
2434 ++N;
2435 // Free instructions.
2436 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2437 IsaBitcastOfPointerType(I))
2438 continue;
2439 else
James Molloy4de84dd2015-11-04 15:28:04 +00002440 return false;
James Molloy9e959ac2015-11-05 08:40:19 +00002441 }
2442 return N <= PHINodeFoldingThreshold;
James Molloy4de84dd2015-11-04 15:28:04 +00002443 };
2444
2445 if (!MergeCondStoresAggressively && (!IsWorthwhile(PTB) ||
2446 !IsWorthwhile(PFB) ||
2447 !IsWorthwhile(QTB) ||
2448 !IsWorthwhile(QFB)))
2449 return false;
2450
2451 // For every pointer, there must be exactly two stores, one coming from
2452 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2453 // store (to any address) in PTB,PFB or QTB,QFB.
2454 // FIXME: We could relax this restriction with a bit more work and performance
2455 // testing.
2456 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2457 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2458 if (!PStore || !QStore)
2459 return false;
2460
2461 // Now check the stores are compatible.
2462 if (!QStore->isUnordered() || !PStore->isUnordered())
2463 return false;
2464
2465 // Check that sinking the store won't cause program behavior changes. Sinking
2466 // the store out of the Q blocks won't change any behavior as we're sinking
2467 // from a block to its unconditional successor. But we're moving a store from
2468 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2469 // So we need to check that there are no aliasing loads or stores in
2470 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2471 // operations between PStore and the end of its parent block.
2472 //
2473 // The ideal way to do this is to query AliasAnalysis, but we don't
2474 // preserve AA currently so that is dangerous. Be super safe and just
2475 // check there are no other memory operations at all.
2476 for (auto &I : *QFB->getSinglePredecessor())
2477 if (I.mayReadOrWriteMemory())
2478 return false;
2479 for (auto &I : *QFB)
2480 if (&I != QStore && I.mayReadOrWriteMemory())
2481 return false;
2482 if (QTB)
2483 for (auto &I : *QTB)
2484 if (&I != QStore && I.mayReadOrWriteMemory())
2485 return false;
2486 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2487 I != E; ++I)
2488 if (&*I != PStore && I->mayReadOrWriteMemory())
2489 return false;
2490
2491 // OK, we're going to sink the stores to PostBB. The store has to be
2492 // conditional though, so first create the predicate.
2493 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2494 ->getCondition();
2495 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2496 ->getCondition();
2497
2498 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2499 PStore->getParent());
2500 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2501 QStore->getParent(), PPHI);
2502
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002503 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2504
James Molloy4de84dd2015-11-04 15:28:04 +00002505 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2506 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2507
2508 if (InvertPCond)
2509 PPred = QB.CreateNot(PPred);
2510 if (InvertQCond)
2511 QPred = QB.CreateNot(QPred);
2512 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2513
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002514 auto *T =
2515 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
James Molloy4de84dd2015-11-04 15:28:04 +00002516 QB.SetInsertPoint(T);
2517 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2518 AAMDNodes AAMD;
2519 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2520 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2521 SI->setAAMetadata(AAMD);
2522
2523 QStore->eraseFromParent();
2524 PStore->eraseFromParent();
2525
2526 return true;
2527}
2528
2529static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI) {
2530 // The intention here is to find diamonds or triangles (see below) where each
2531 // conditional block contains a store to the same address. Both of these
2532 // stores are conditional, so they can't be unconditionally sunk. But it may
2533 // be profitable to speculatively sink the stores into one merged store at the
2534 // end, and predicate the merged store on the union of the two conditions of
2535 // PBI and QBI.
2536 //
2537 // This can reduce the number of stores executed if both of the conditions are
2538 // true, and can allow the blocks to become small enough to be if-converted.
2539 // This optimization will also chain, so that ladders of test-and-set
2540 // sequences can be if-converted away.
2541 //
2542 // We only deal with simple diamonds or triangles:
2543 //
2544 // PBI or PBI or a combination of the two
2545 // / \ | \
2546 // PTB PFB | PFB
2547 // \ / | /
2548 // QBI QBI
2549 // / \ | \
2550 // QTB QFB | QFB
2551 // \ / | /
2552 // PostBB PostBB
2553 //
2554 // We model triangles as a type of diamond with a nullptr "true" block.
2555 // Triangles are canonicalized so that the fallthrough edge is represented by
2556 // a true condition, as in the diagram above.
2557 //
2558 BasicBlock *PTB = PBI->getSuccessor(0);
2559 BasicBlock *PFB = PBI->getSuccessor(1);
2560 BasicBlock *QTB = QBI->getSuccessor(0);
2561 BasicBlock *QFB = QBI->getSuccessor(1);
2562 BasicBlock *PostBB = QFB->getSingleSuccessor();
2563
2564 bool InvertPCond = false, InvertQCond = false;
2565 // Canonicalize fallthroughs to the true branches.
2566 if (PFB == QBI->getParent()) {
2567 std::swap(PFB, PTB);
2568 InvertPCond = true;
2569 }
2570 if (QFB == PostBB) {
2571 std::swap(QFB, QTB);
2572 InvertQCond = true;
2573 }
2574
2575 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
2576 // and QFB may not. Model fallthroughs as a nullptr block.
2577 if (PTB == QBI->getParent())
2578 PTB = nullptr;
2579 if (QTB == PostBB)
2580 QTB = nullptr;
2581
2582 // Legality bailouts. We must have at least the non-fallthrough blocks and
2583 // the post-dominating block, and the non-fallthroughs must only have one
2584 // predecessor.
2585 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
2586 return BB->getSinglePredecessor() == P &&
2587 BB->getSingleSuccessor() == S;
2588 };
2589 if (!PostBB ||
2590 !HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
2591 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
2592 return false;
2593 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
2594 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
2595 return false;
2596 if (PostBB->getNumUses() != 2 || QBI->getParent()->getNumUses() != 2)
2597 return false;
2598
2599 // OK, this is a sequence of two diamonds or triangles.
2600 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
2601 SmallPtrSet<Value *,4> PStoreAddresses, QStoreAddresses;
2602 for (auto *BB : {PTB, PFB}) {
2603 if (!BB)
2604 continue;
2605 for (auto &I : *BB)
2606 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2607 PStoreAddresses.insert(SI->getPointerOperand());
2608 }
2609 for (auto *BB : {QTB, QFB}) {
2610 if (!BB)
2611 continue;
2612 for (auto &I : *BB)
2613 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
2614 QStoreAddresses.insert(SI->getPointerOperand());
2615 }
2616
2617 set_intersect(PStoreAddresses, QStoreAddresses);
2618 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
2619 // clear what it contains.
2620 auto &CommonAddresses = PStoreAddresses;
2621
2622 bool Changed = false;
2623 for (auto *Address : CommonAddresses)
2624 Changed |= mergeConditionalStoreToAddress(
2625 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond);
2626 return Changed;
2627}
2628
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002629/// If we have a conditional branch as a predecessor of another block,
2630/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00002631/// that PBI and BI are both conditional branches, and BI is in one of the
2632/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00002633static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
2634 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00002635 assert(PBI->isConditional() && BI->isConditional());
2636 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002637
Chris Lattner9aada1d2008-07-13 21:53:26 +00002638 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002639 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002640 // this conditional branch redundant.
2641 if (PBI->getCondition() == BI->getCondition() &&
2642 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2643 // Okay, the outcome of this conditional branch is statically
2644 // knowable. If this block had a single pred, handle specially.
2645 if (BB->getSinglePredecessor()) {
2646 // Turn this into a branch on constant.
2647 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002648 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002649 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002650 return true; // Nuke the branch on constant.
2651 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002652
Chris Lattner9aada1d2008-07-13 21:53:26 +00002653 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2654 // in the constant and simplify the block result. Subsequent passes of
2655 // simplifycfg will thread the block.
2656 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002657 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002658 PHINode *NewPN = PHINode::Create(
2659 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
2660 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00002661 // Okay, we're going to insert the PHI node. Since PBI is not the only
2662 // predecessor, compute the PHI'd conditional value for all of the preds.
2663 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002664 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002665 BasicBlock *P = *PI;
2666 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002667 PBI != BI && PBI->isConditional() &&
2668 PBI->getCondition() == BI->getCondition() &&
2669 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2670 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002671 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002672 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002673 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002674 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002675 }
Gabor Greif8629f122010-07-12 10:59:23 +00002676 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002677
Chris Lattner9aada1d2008-07-13 21:53:26 +00002678 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002679 return true;
2680 }
2681 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002682
Philip Reamesb42db212015-10-14 22:46:19 +00002683 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2684 if (CE->canTrap())
2685 return false;
2686
Philip Reames846e3e42015-10-29 03:11:49 +00002687 // If BI is reached from the true path of PBI and PBI's condition implies
2688 // BI's condition, we know the direction of the BI branch.
2689 if (PBI->getSuccessor(0) == BI->getParent() &&
Sanjoy Das55ea67c2015-11-06 19:01:08 +00002690 isImpliedCondition(PBI->getCondition(), BI->getCondition(), DL) &&
Philip Reames846e3e42015-10-29 03:11:49 +00002691 PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
2692 BB->getSinglePredecessor()) {
2693 // Turn this into a branch on constant.
2694 auto *OldCond = BI->getCondition();
2695 BI->setCondition(ConstantInt::getTrue(BB->getContext()));
2696 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
2697 return true; // Nuke the branch on constant.
2698 }
2699
James Molloy4de84dd2015-11-04 15:28:04 +00002700 // If both branches are conditional and both contain stores to the same
2701 // address, remove the stores from the conditionals and create a conditional
2702 // merged store at the end.
2703 if (MergeCondStores && mergeConditionalStores(PBI, BI))
2704 return true;
2705
Chris Lattner9aada1d2008-07-13 21:53:26 +00002706 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002707 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002708 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002709 BasicBlock::iterator BBI = BB->begin();
2710 // Ignore dbg intrinsics.
2711 while (isa<DbgInfoIntrinsic>(BBI))
2712 ++BBI;
2713 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002714 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002715
Chris Lattner834ab4e2008-07-13 22:04:41 +00002716 int PBIOp, BIOp;
2717 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2718 PBIOp = BIOp = 0;
2719 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2720 PBIOp = 0, BIOp = 1;
2721 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2722 PBIOp = 1, BIOp = 0;
2723 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2724 PBIOp = BIOp = 1;
2725 else
2726 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002727
Chris Lattner834ab4e2008-07-13 22:04:41 +00002728 // Check to make sure that the other destination of this branch
2729 // isn't BB itself. If so, this is an infinite loop that will
2730 // keep getting unwound.
2731 if (PBI->getSuccessor(PBIOp) == BB)
2732 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002733
2734 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002735 // insertion of a large number of select instructions. For targets
2736 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002737
Sanjay Patela932da82014-07-07 21:19:00 +00002738 // Also do not perform this transformation if any phi node in the common
2739 // destination block can trap when reached by BB or PBB (PR17073). In that
2740 // case, it would be unsafe to hoist the operation into a select instruction.
2741
2742 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002743 unsigned NumPhis = 0;
2744 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002745 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002746 if (NumPhis > 2) // Disable this xform.
2747 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002748
Sanjay Patela932da82014-07-07 21:19:00 +00002749 PHINode *PN = cast<PHINode>(II);
2750 Value *BIV = PN->getIncomingValueForBlock(BB);
2751 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2752 if (CE->canTrap())
2753 return false;
2754
2755 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2756 Value *PBIV = PN->getIncomingValue(PBBIdx);
2757 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2758 if (CE->canTrap())
2759 return false;
2760 }
2761
Chris Lattner834ab4e2008-07-13 22:04:41 +00002762 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002763 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002764
David Greene725c7c32010-01-05 01:26:52 +00002765 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002766 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002767
2768
Chris Lattner80b03a12008-07-13 22:23:11 +00002769 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2770 // branch in it, where one edge (OtherDest) goes back to itself but the other
2771 // exits. We don't *know* that the program avoids the infinite loop
2772 // (even though that seems likely). If we do this xform naively, we'll end up
2773 // recursively unpeeling the loop. Since we know that (after the xform is
2774 // done) that the block *is* infinite if reached, we just make it an obviously
2775 // infinite loop with no cond branch.
2776 if (OtherDest == BB) {
2777 // Insert it at the end of the function, because it's either code,
2778 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002779 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2780 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002781 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2782 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002783 }
2784
David Greene725c7c32010-01-05 01:26:52 +00002785 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002786
Chris Lattner834ab4e2008-07-13 22:04:41 +00002787 // BI may have other predecessors. Because of this, we leave
2788 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002789
Chris Lattner834ab4e2008-07-13 22:04:41 +00002790 // Make sure we get to CommonDest on True&True directions.
2791 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002792 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002793 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002794 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2795
Chris Lattner834ab4e2008-07-13 22:04:41 +00002796 Value *BICond = BI->getCondition();
2797 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002798 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2799
Chris Lattner834ab4e2008-07-13 22:04:41 +00002800 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002801 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002802
Chris Lattner834ab4e2008-07-13 22:04:41 +00002803 // Modify PBI to branch on the new condition to the new dests.
2804 PBI->setCondition(Cond);
2805 PBI->setSuccessor(0, CommonDest);
2806 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002807
Manman Ren2d4c10f2012-09-17 21:30:40 +00002808 // Update branch weight for PBI.
2809 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00002810 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2811 PredFalseWeight);
2812 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2813 SuccFalseWeight);
Manman Ren2d4c10f2012-09-17 21:30:40 +00002814 if (PredHasWeights && SuccHasWeights) {
2815 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2816 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2817 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2818 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2819 // The weight to CommonDest should be PredCommon * SuccTotal +
2820 // PredOther * SuccCommon.
2821 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00002822 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
2823 PredOther * SuccCommon,
2824 PredOther * SuccOther};
Manman Ren2d4c10f2012-09-17 21:30:40 +00002825 // Halve the weights if any of them cannot fit in an uint32_t
2826 FitWeights(NewWeights);
2827
Manman Ren2d4c10f2012-09-17 21:30:40 +00002828 PBI->setMetadata(LLVMContext::MD_prof,
Benjamin Kramerea68a942015-02-19 15:26:17 +00002829 MDBuilder(BI->getContext())
2830 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00002831 }
2832
Chris Lattner834ab4e2008-07-13 22:04:41 +00002833 // OtherDest may have phi nodes. If so, add an entry from PBI's
2834 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002835 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002836
Chris Lattner834ab4e2008-07-13 22:04:41 +00002837 // We know that the CommonDest already had an edge from PBI to
2838 // it. If it has PHIs though, the PHIs may have different
2839 // entries for BB and PBI's BB. If so, insert a select to make
2840 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002841 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002842 for (BasicBlock::iterator II = CommonDest->begin();
2843 (PN = dyn_cast<PHINode>(II)); ++II) {
2844 Value *BIV = PN->getIncomingValueForBlock(BB);
2845 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2846 Value *PBIV = PN->getIncomingValue(PBBIdx);
2847 if (BIV != PBIV) {
2848 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002849 Value *NV = cast<SelectInst>
2850 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002851 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002852 }
2853 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002854
David Greene725c7c32010-01-05 01:26:52 +00002855 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2856 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002857
Chris Lattner834ab4e2008-07-13 22:04:41 +00002858 // This basic block is probably dead. We know it has at least
2859 // one fewer predecessor.
2860 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002861}
2862
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002863// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
2864// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00002865// Takes care of updating the successors and removing the old terminator.
2866// Also makes sure not to introduce new successors by assuming that edges to
2867// non-successor TrueBBs and FalseBBs aren't reachable.
2868static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002869 BasicBlock *TrueBB, BasicBlock *FalseBB,
2870 uint32_t TrueWeight,
2871 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002872 // Remove any superfluous successor edges from the CFG.
2873 // First, figure out which successors to preserve.
2874 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2875 // successor.
2876 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002877 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002878
2879 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00002880 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002881 // Make sure only to keep exactly one copy of each edge.
2882 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002883 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002884 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002885 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002886 else
David Majnemerdc3b67b2015-10-21 18:22:24 +00002887 Succ->removePredecessor(OldTerm->getParent(),
2888 /*DontDeleteUselessPHIs=*/true);
Frits van Bommel8e158492011-01-11 12:52:11 +00002889 }
2890
Devang Patel2c2ea222011-05-18 18:43:31 +00002891 IRBuilder<> Builder(OldTerm);
2892 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2893
Frits van Bommel8e158492011-01-11 12:52:11 +00002894 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002895 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002896 if (TrueBB == FalseBB)
2897 // We were only looking for one successor, and it was present.
2898 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002899 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002900 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002901 // We found both of the successors we were looking for.
2902 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002903 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2904 if (TrueWeight != FalseWeight)
2905 NewBI->setMetadata(LLVMContext::MD_prof,
2906 MDBuilder(OldTerm->getContext()).
2907 createBranchWeights(TrueWeight, FalseWeight));
2908 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002909 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2910 // Neither of the selected blocks were successors, so this
2911 // terminator must be unreachable.
2912 new UnreachableInst(OldTerm->getContext(), OldTerm);
2913 } else {
2914 // One of the selected values was a successor, but the other wasn't.
2915 // Insert an unconditional branch to the one that was found;
2916 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002917 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002918 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002919 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002920 else
2921 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002922 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002923 }
2924
2925 EraseTerminatorInstAndDCECond(OldTerm);
2926 return true;
2927}
2928
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002929// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00002930// (switch (select cond, X, Y)) on constant X, Y
2931// with a branch - conditional if X and Y lead to distinct BBs,
2932// unconditional otherwise.
2933static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2934 // Check for constant integer values in the select.
2935 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2936 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2937 if (!TrueVal || !FalseVal)
2938 return false;
2939
2940 // Find the relevant condition and destinations.
2941 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002942 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2943 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002944
Manman Ren774246a2012-09-17 22:28:55 +00002945 // Get weight for TrueBB and FalseBB.
2946 uint32_t TrueWeight = 0, FalseWeight = 0;
2947 SmallVector<uint64_t, 8> Weights;
2948 bool HasWeights = HasBranchWeights(SI);
2949 if (HasWeights) {
2950 GetBranchWeights(SI, Weights);
2951 if (Weights.size() == 1 + SI->getNumCases()) {
2952 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2953 getSuccessorIndex()];
2954 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2955 getSuccessorIndex()];
2956 }
2957 }
2958
Frits van Bommel8ae07992011-02-28 09:44:07 +00002959 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002960 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2961 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002962}
2963
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002964// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002965// (indirectbr (select cond, blockaddress(@fn, BlockA),
2966// blockaddress(@fn, BlockB)))
2967// with
2968// (br cond, BlockA, BlockB).
2969static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2970 // Check that both operands of the select are block addresses.
2971 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2972 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2973 if (!TBA || !FBA)
2974 return false;
2975
2976 // Extract the actual blocks.
2977 BasicBlock *TrueBB = TBA->getBasicBlock();
2978 BasicBlock *FalseBB = FBA->getBasicBlock();
2979
Frits van Bommel8e158492011-01-11 12:52:11 +00002980 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002981 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2982 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002983}
2984
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002985/// This is called when we find an icmp instruction
2986/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002987/// block that ends with an uncond branch. We are looking for a very specific
2988/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2989/// this case, we merge the first two "or's of icmp" into a switch, but then the
2990/// default value goes to an uncond block with a seteq in it, we get something
2991/// like:
2992///
2993/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2994/// DEFAULT:
2995/// %tmp = icmp eq i8 %A, 92
2996/// br label %end
2997/// end:
2998/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00002999///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003000/// We prefer to split the edge to 'end' so that there is a true/false entry to
3001/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003002static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003003 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
3004 const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
3005 AssumptionCache *AC) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003006 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00003007
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003008 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3009 // complex.
3010 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
3011
3012 Value *V = ICI->getOperand(0);
3013 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00003014
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003015 // The pattern we're looking for is where our only predecessor is a switch on
3016 // 'V' and this block is the default case for the switch. In this case we can
3017 // fold the compared value into the switch to simplify things.
3018 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00003019 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003020
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003021 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3022 if (SI->getCondition() != V)
3023 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003024
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003025 // If BB is reachable on a non-default case, then we simply know the value of
3026 // V in this block. Substitute it and constant fold the icmp instruction
3027 // away.
3028 if (SI->getDefaultDest() != BB) {
3029 ConstantInt *VVal = SI->findCaseDest(BB);
3030 assert(VVal && "Should have a unique destination value");
3031 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003032
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003033 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00003034 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003035 ICI->eraseFromParent();
3036 }
3037 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003038 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003039 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003040
Chris Lattner62cc76e2010-12-13 03:43:57 +00003041 // Ok, the block is reachable from the default dest. If the constant we're
3042 // comparing exists in one of the other edges, then we can constant fold ICI
3043 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003044 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00003045 Value *V;
3046 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3047 V = ConstantInt::getFalse(BB->getContext());
3048 else
3049 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003050
Chris Lattner62cc76e2010-12-13 03:43:57 +00003051 ICI->replaceAllUsesWith(V);
3052 ICI->eraseFromParent();
3053 // BB is now empty, so it is likely to simplify away.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003054 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00003055 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003056
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003057 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3058 // the block.
3059 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003060 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00003061 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003062 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3063 return false;
3064
3065 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3066 // true in the PHI.
3067 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
3068 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
3069
3070 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3071 std::swap(DefaultCst, NewCst);
3072
3073 // Replace ICI (which is used by the PHI for the default value) with true or
3074 // false depending on if it is EQ or NE.
3075 ICI->replaceAllUsesWith(DefaultCst);
3076 ICI->eraseFromParent();
3077
3078 // Okay, the switch goes to this block on a default value. Add an edge from
3079 // the switch to the merge point on the compared value.
3080 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
3081 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00003082 SmallVector<uint64_t, 8> Weights;
3083 bool HasWeights = HasBranchWeights(SI);
3084 if (HasWeights) {
3085 GetBranchWeights(SI, Weights);
3086 if (Weights.size() == 1 + SI->getNumCases()) {
3087 // Split weight for default case to case for "Cst".
3088 Weights[0] = (Weights[0]+1) >> 1;
3089 Weights.push_back(Weights[0]);
3090
3091 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3092 SI->setMetadata(LLVMContext::MD_prof,
3093 MDBuilder(SI->getContext()).
3094 createBranchWeights(MDWeights));
3095 }
3096 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003097 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003098
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003099 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00003100 Builder.SetInsertPoint(NewBB);
3101 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3102 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003103 PHIUse->addIncoming(NewCst, NewBB);
3104 return true;
3105}
3106
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003107/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003108/// Check to see if it is branching on an or/and chain of icmp instructions, and
3109/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003110static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3111 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003112 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00003113 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003114
Chris Lattnera69c4432010-12-13 05:03:41 +00003115 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3116 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3117 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003118
Mehdi Amini9a25cb82014-11-19 20:09:11 +00003119 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00003120 ConstantComparesGatherer ConstantCompare(Cond, DL);
3121 // Unpack the result
3122 SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
3123 Value *CompVal = ConstantCompare.CompValue;
3124 unsigned UsedICmps = ConstantCompare.UsedICmps;
3125 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003126
Chris Lattnera69c4432010-12-13 05:03:41 +00003127 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00003128 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00003129
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003130 // Avoid turning single icmps into a switch.
3131 if (UsedICmps <= 1)
3132 return false;
3133
Mehdi Aminiffd01002014-11-20 22:40:25 +00003134 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3135
Chris Lattnera69c4432010-12-13 05:03:41 +00003136 // There might be duplicate constants in the list, which the switch
3137 // instruction can't handle, remove them now.
3138 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3139 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003140
Chris Lattnera69c4432010-12-13 05:03:41 +00003141 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00003142 // transformation. A switch with one value is just a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003143 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003144
Andrew Trick3051aa12012-08-29 21:46:38 +00003145 // TODO: Preserve branch weight metadata, similarly to how
3146 // FoldValueComparisonIntoPredecessors preserves it.
3147
Chris Lattnera69c4432010-12-13 05:03:41 +00003148 // Figure out which block is which destination.
3149 BasicBlock *DefaultBB = BI->getSuccessor(1);
3150 BasicBlock *EdgeBB = BI->getSuccessor(0);
3151 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003152
Chris Lattnera69c4432010-12-13 05:03:41 +00003153 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003154
Chris Lattnerd7beca32010-12-14 06:17:25 +00003155 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003156 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003157
Chris Lattnera69c4432010-12-13 05:03:41 +00003158 // If there are any extra values that couldn't be folded into the switch
3159 // then we evaluate them with an explicit branch first. Split the block
3160 // right before the condbr to handle it.
3161 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003162 BasicBlock *NewBB =
3163 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00003164 // Remove the uncond branch added to the old block.
3165 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00003166 Builder.SetInsertPoint(OldTI);
3167
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003168 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00003169 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003170 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00003171 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003172
Chris Lattnera69c4432010-12-13 05:03:41 +00003173 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003174
Chris Lattnercb570f82010-12-13 05:34:18 +00003175 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3176 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003177 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003178
Chris Lattnerd7beca32010-12-14 06:17:25 +00003179 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
3180 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00003181 BB = NewBB;
3182 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00003183
3184 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00003185 // Convert pointer to int before we switch.
3186 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003187 CompVal = Builder.CreatePtrToInt(
3188 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00003189 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003190
Chris Lattnera69c4432010-12-13 05:03:41 +00003191 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00003192 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00003193
Chris Lattnera69c4432010-12-13 05:03:41 +00003194 // Add all of the 'cases' to the switch instruction.
3195 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3196 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003197
Chris Lattnera69c4432010-12-13 05:03:41 +00003198 // We added edges from PI to the EdgeBB. As such, if there were any
3199 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3200 // the number of edges added.
3201 for (BasicBlock::iterator BBI = EdgeBB->begin();
3202 isa<PHINode>(BBI); ++BBI) {
3203 PHINode *PN = cast<PHINode>(BBI);
3204 Value *InVal = PN->getIncomingValueForBlock(BB);
3205 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
3206 PN->addIncoming(InVal, BB);
3207 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003208
Chris Lattnera69c4432010-12-13 05:03:41 +00003209 // Erase the old branch instruction.
3210 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003211
Chris Lattnerd7beca32010-12-14 06:17:25 +00003212 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00003213 return true;
3214}
3215
Duncan Sands29192d02011-09-05 12:57:57 +00003216bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
3217 // If this is a trivial landing pad that just continues unwinding the caught
3218 // exception then zap the landing pad, turning its invokes into calls.
3219 BasicBlock *BB = RI->getParent();
3220 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
Chen Li7009cd32015-10-23 21:13:01 +00003221 if (RI->getValue() != LPInst)
3222 // Not a landing pad, or the resume is not unwinding the exception that
3223 // caused control to branch here.
Duncan Sands29192d02011-09-05 12:57:57 +00003224 return false;
3225
Chen Li7009cd32015-10-23 21:13:01 +00003226 // Check that there are no other instructions except for debug intrinsics.
3227 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
Duncan Sands29192d02011-09-05 12:57:57 +00003228 while (++I != E)
3229 if (!isa<DbgInfoIntrinsic>(I))
3230 return false;
3231
Chen Lic6e28782015-10-22 20:48:38 +00003232 // Turn all invokes that unwind here into calls and delete the basic block.
Chen Li7009cd32015-10-23 21:13:01 +00003233 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3234 BasicBlock *Pred = *PI++;
3235 removeUnwindEdge(Pred);
Chen Lic6e28782015-10-22 20:48:38 +00003236 }
3237
Chen Li7009cd32015-10-23 21:13:01 +00003238 // The landingpad is now unreachable. Zap it.
3239 BB->eraseFromParent();
3240 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00003241}
3242
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003243bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
3244 // If this is a trivial cleanup pad that executes no instructions, it can be
3245 // eliminated. If the cleanup pad continues to the caller, any predecessor
3246 // that is an EH pad will be updated to continue to the caller and any
3247 // predecessor that terminates with an invoke instruction will have its invoke
3248 // instruction converted to a call instruction. If the cleanup pad being
3249 // simplified does not continue to the caller, each predecessor will be
3250 // updated to continue to the unwind destination of the cleanup pad being
3251 // simplified.
3252 BasicBlock *BB = RI->getParent();
3253 Instruction *CPInst = dyn_cast<CleanupPadInst>(BB->getFirstNonPHI());
3254 if (!CPInst)
3255 // This isn't an empty cleanup.
3256 return false;
3257
3258 // Check that there are no other instructions except for debug intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003259 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003260 while (++I != E)
3261 if (!isa<DbgInfoIntrinsic>(I))
3262 return false;
3263
3264 // If the cleanup return we are simplifying unwinds to the caller, this
3265 // will set UnwindDest to nullptr.
3266 BasicBlock *UnwindDest = RI->getUnwindDest();
3267
3268 // We're about to remove BB from the control flow. Before we do, sink any
3269 // PHINodes into the unwind destination. Doing this before changing the
3270 // control flow avoids some potentially slow checks, since we can currently
3271 // be certain that UnwindDest and BB have no common predecessors (since they
3272 // are both EH pads).
3273 if (UnwindDest) {
3274 // First, go through the PHI nodes in UnwindDest and update any nodes that
3275 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003276 for (BasicBlock::iterator I = UnwindDest->begin(),
3277 IE = UnwindDest->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003278 I != IE; ++I) {
3279 PHINode *DestPN = cast<PHINode>(I);
James Molloy4de84dd2015-11-04 15:28:04 +00003280
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003281 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003282 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003283 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003284 // This PHI node has an incoming value that corresponds to a control
3285 // path through the cleanup pad we are removing. If the incoming
3286 // value is in the cleanup pad, it must be a PHINode (because we
3287 // verified above that the block is otherwise empty). Otherwise, the
3288 // value is either a constant or a value that dominates the cleanup
3289 // pad being removed.
3290 //
3291 // Because BB and UnwindDest are both EH pads, all of their
3292 // predecessors must unwind to these blocks, and since no instruction
3293 // can have multiple unwind destinations, there will be no overlap in
3294 // incoming blocks between SrcPN and DestPN.
3295 Value *SrcVal = DestPN->getIncomingValue(Idx);
3296 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3297
3298 // Remove the entry for the block we are deleting.
3299 DestPN->removeIncomingValue(Idx, false);
3300
3301 if (SrcPN && SrcPN->getParent() == BB) {
3302 // If the incoming value was a PHI node in the cleanup pad we are
3303 // removing, we need to merge that PHI node's incoming values into
3304 // DestPN.
James Molloy4de84dd2015-11-04 15:28:04 +00003305 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003306 SrcIdx != SrcE; ++SrcIdx) {
3307 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3308 SrcPN->getIncomingBlock(SrcIdx));
3309 }
3310 } else {
3311 // Otherwise, the incoming value came from above BB and
3312 // so we can just reuse it. We must associate all of BB's
3313 // predecessors with this value.
3314 for (auto *pred : predecessors(BB)) {
3315 DestPN->addIncoming(SrcVal, pred);
3316 }
3317 }
3318 }
3319
3320 // Sink any remaining PHI nodes directly into UnwindDest.
3321 Instruction *InsertPt = UnwindDest->getFirstNonPHI();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003322 for (BasicBlock::iterator I = BB->begin(),
3323 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003324 I != IE;) {
3325 // The iterator must be incremented here because the instructions are
3326 // being moved to another block.
3327 PHINode *PN = cast<PHINode>(I++);
3328 if (PN->use_empty())
3329 // If the PHI node has no uses, just leave it. It will be erased
3330 // when we erase BB below.
3331 continue;
3332
3333 // Otherwise, sink this PHI node into UnwindDest.
3334 // Any predecessors to UnwindDest which are not already represented
3335 // must be back edges which inherit the value from the path through
3336 // BB. In this case, the PHI value must reference itself.
3337 for (auto *pred : predecessors(UnwindDest))
3338 if (pred != BB)
3339 PN->addIncoming(PN, pred);
3340 PN->moveBefore(InsertPt);
3341 }
3342 }
3343
3344 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3345 // The iterator must be updated here because we are removing this pred.
3346 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003347 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003348 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003349 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003350 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003351 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003352 }
3353 }
3354
3355 // The cleanup pad is now unreachable. Zap it.
3356 BB->eraseFromParent();
3357 return true;
3358}
3359
Devang Pateldd14e0f2011-05-18 21:33:11 +00003360bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003361 BasicBlock *BB = RI->getParent();
3362 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003363
Chris Lattner25c3af32010-12-13 06:25:44 +00003364 // Find predecessors that end with branches.
3365 SmallVector<BasicBlock*, 8> UncondBranchPreds;
3366 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00003367 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
3368 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00003369 TerminatorInst *PTI = P->getTerminator();
3370 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
3371 if (BI->isUnconditional())
3372 UncondBranchPreds.push_back(P);
3373 else
3374 CondBranchPreds.push_back(BI);
3375 }
3376 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003377
Chris Lattner25c3af32010-12-13 06:25:44 +00003378 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00003379 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003380 while (!UncondBranchPreds.empty()) {
3381 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
3382 DEBUG(dbgs() << "FOLDING: " << *BB
3383 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00003384 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00003385 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003386
Chris Lattner25c3af32010-12-13 06:25:44 +00003387 // If we eliminated all predecessors of the block, delete the block now.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003388 if (pred_empty(BB))
Chris Lattner25c3af32010-12-13 06:25:44 +00003389 // We know there are no successors, so just nuke the block.
3390 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003391
Chris Lattner25c3af32010-12-13 06:25:44 +00003392 return true;
3393 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003394
Chris Lattner25c3af32010-12-13 06:25:44 +00003395 // Check out all of the conditional branches going to this return
3396 // instruction. If any of them just select between returns, change the
3397 // branch itself into a select/return pair.
3398 while (!CondBranchPreds.empty()) {
3399 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003400
Chris Lattner25c3af32010-12-13 06:25:44 +00003401 // Check to see if the non-BB successor is also a return block.
3402 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
3403 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00003404 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00003405 return true;
3406 }
3407 return false;
3408}
3409
Chris Lattner25c3af32010-12-13 06:25:44 +00003410bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
3411 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003412
Chris Lattner25c3af32010-12-13 06:25:44 +00003413 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003414
Chris Lattner25c3af32010-12-13 06:25:44 +00003415 // If there are any instructions immediately before the unreachable that can
3416 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003417 while (UI->getIterator() != BB->begin()) {
3418 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00003419 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003420 // Do not delete instructions that can have side effects which might cause
3421 // the unreachable to not be reachable; specifically, calls and volatile
3422 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00003423 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003424
3425 if (BBI->mayHaveSideEffects()) {
3426 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3427 if (SI->isVolatile())
3428 break;
3429 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3430 if (LI->isVolatile())
3431 break;
3432 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3433 if (RMWI->isVolatile())
3434 break;
3435 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3436 if (CXI->isVolatile())
3437 break;
3438 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3439 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003440 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003441 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003442 // Note that deleting LandingPad's here is in fact okay, although it
3443 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3444 // all the predecessors of this block will be the unwind edges of Invokes,
3445 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003446 }
3447
Eli Friedmanaac35b32011-03-09 00:48:33 +00003448 // Delete this instruction (any uses are guaranteed to be dead)
3449 if (!BBI->use_empty())
3450 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003451 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003452 Changed = true;
3453 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003454
Chris Lattner25c3af32010-12-13 06:25:44 +00003455 // If the unreachable instruction is the first in the block, take a gander
3456 // at all of the predecessors of this instruction, and simplify them.
3457 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003458
Chris Lattner25c3af32010-12-13 06:25:44 +00003459 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3460 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3461 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003462 IRBuilder<> Builder(TI);
Chris Lattner25c3af32010-12-13 06:25:44 +00003463 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3464 if (BI->isUnconditional()) {
3465 if (BI->getSuccessor(0) == BB) {
3466 new UnreachableInst(TI->getContext(), TI);
3467 TI->eraseFromParent();
3468 Changed = true;
3469 }
3470 } else {
3471 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003472 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003473 EraseTerminatorInstAndDCECond(BI);
3474 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003475 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003476 EraseTerminatorInstAndDCECond(BI);
3477 Changed = true;
3478 }
3479 }
3480 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003481 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003482 i != e; ++i)
3483 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003484 BB->removePredecessor(SI->getParent());
3485 SI->removeCase(i);
3486 --i; --e;
3487 Changed = true;
3488 }
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003489 } else if ((isa<InvokeInst>(TI) &&
3490 cast<InvokeInst>(TI)->getUnwindDest() == BB) ||
3491 isa<CatchEndPadInst>(TI) || isa<TerminatePadInst>(TI)) {
3492 removeUnwindEdge(TI->getParent());
3493 Changed = true;
David Majnemer49293702015-10-27 22:43:56 +00003494 } else if (isa<CleanupReturnInst>(TI) || isa<CleanupEndPadInst>(TI)) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003495 new UnreachableInst(TI->getContext(), TI);
3496 TI->eraseFromParent();
3497 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00003498 }
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003499 // TODO: If TI is a CatchPadInst, then (BB must be its normal dest and)
3500 // we can eliminate it, redirecting its preds to its unwind successor,
3501 // or to the next outer handler if the removed catch is the last for its
3502 // catchendpad.
Chris Lattner25c3af32010-12-13 06:25:44 +00003503 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003504
Chris Lattner25c3af32010-12-13 06:25:44 +00003505 // If this block is now dead, remove it.
Ramkumar Ramachandra40c3e032015-01-13 03:46:47 +00003506 if (pred_empty(BB) &&
Chris Lattner25c3af32010-12-13 06:25:44 +00003507 BB != &BB->getParent()->getEntryBlock()) {
3508 // We know there are no successors, so just nuke the block.
3509 BB->eraseFromParent();
3510 return true;
3511 }
3512
3513 return Changed;
3514}
3515
Hans Wennborg68000082015-01-26 19:52:32 +00003516static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
3517 assert(Cases.size() >= 1);
3518
3519 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3520 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
3521 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
3522 return false;
3523 }
3524 return true;
3525}
3526
3527/// Turn a switch with two reachable destinations into an integer range
3528/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003529static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003530 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003531
Hans Wennborg68000082015-01-26 19:52:32 +00003532 bool HasDefault =
3533 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003534
Hans Wennborg68000082015-01-26 19:52:32 +00003535 // Partition the cases into two sets with different destinations.
3536 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
3537 BasicBlock *DestB = nullptr;
3538 SmallVector <ConstantInt *, 16> CasesA;
3539 SmallVector <ConstantInt *, 16> CasesB;
3540
3541 for (SwitchInst::CaseIt I : SI->cases()) {
3542 BasicBlock *Dest = I.getCaseSuccessor();
3543 if (!DestA) DestA = Dest;
3544 if (Dest == DestA) {
3545 CasesA.push_back(I.getCaseValue());
3546 continue;
3547 }
3548 if (!DestB) DestB = Dest;
3549 if (Dest == DestB) {
3550 CasesB.push_back(I.getCaseValue());
3551 continue;
3552 }
3553 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003554 }
3555
Hans Wennborg68000082015-01-26 19:52:32 +00003556 assert(DestA && DestB && "Single-destination switch should have been folded.");
3557 assert(DestA != DestB);
3558 assert(DestB != SI->getDefaultDest());
3559 assert(!CasesB.empty() && "There must be non-default cases.");
3560 assert(!CasesA.empty() || HasDefault);
3561
3562 // Figure out if one of the sets of cases form a contiguous range.
3563 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
3564 BasicBlock *ContiguousDest = nullptr;
3565 BasicBlock *OtherDest = nullptr;
3566 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
3567 ContiguousCases = &CasesA;
3568 ContiguousDest = DestA;
3569 OtherDest = DestB;
3570 } else if (CasesAreContiguous(CasesB)) {
3571 ContiguousCases = &CasesB;
3572 ContiguousDest = DestB;
3573 OtherDest = DestA;
3574 } else
3575 return false;
3576
3577 // Start building the compare and branch.
3578
3579 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
3580 Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003581
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003582 Value *Sub = SI->getCondition();
3583 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00003584 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
3585
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003586 Value *Cmp;
3587 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00003588 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003589 Cmp = ConstantInt::getTrue(SI->getContext());
3590 else
3591 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00003592 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003593
Manman Ren56575552012-09-18 00:47:33 +00003594 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00003595 if (HasBranchWeights(SI)) {
3596 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00003597 GetBranchWeights(SI, Weights);
3598 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00003599 uint64_t TrueWeight = 0;
3600 uint64_t FalseWeight = 0;
3601 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
3602 if (SI->getSuccessor(I) == ContiguousDest)
3603 TrueWeight += Weights[I];
3604 else
3605 FalseWeight += Weights[I];
3606 }
3607 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
3608 TrueWeight /= 2;
3609 FalseWeight /= 2;
3610 }
Manman Ren56575552012-09-18 00:47:33 +00003611 NewBI->setMetadata(LLVMContext::MD_prof,
Hans Wennborg68000082015-01-26 19:52:32 +00003612 MDBuilder(SI->getContext()).createBranchWeights(
3613 (uint32_t)TrueWeight, (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00003614 }
3615 }
3616
Hans Wennborg68000082015-01-26 19:52:32 +00003617 // Prune obsolete incoming values off the successors' PHI nodes.
3618 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
3619 unsigned PreviousEdges = ContiguousCases->size();
3620 if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
3621 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003622 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3623 }
Hans Wennborg68000082015-01-26 19:52:32 +00003624 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
3625 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
3626 if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
3627 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
3628 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3629 }
3630
3631 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003632 SI->eraseFromParent();
3633
3634 return true;
3635}
Chris Lattner25c3af32010-12-13 06:25:44 +00003636
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003637/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003638/// and use it to remove dead cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003639static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
3640 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003641 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003642 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003643 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003644 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003645
3646 // Gather dead cases.
3647 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003648 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003649 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3650 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3651 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003652 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003653 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003654 }
3655 }
3656
Philip Reames98a2dab2015-08-26 23:56:46 +00003657 // If we can prove that the cases must cover all possible values, the
Philip Reames05370132015-09-10 17:44:47 +00003658 // default destination becomes dead and we can remove it. If we know some
3659 // of the bits in the value, we can use that to more precisely compute the
3660 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00003661 bool HasDefault =
3662 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Philip Reames05370132015-09-10 17:44:47 +00003663 const unsigned NumUnknownBits = Bits -
3664 (KnownZero.Or(KnownOne)).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00003665 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00003666 if (HasDefault && DeadCases.empty() &&
3667 NumUnknownBits < 64 /* avoid overflow */ &&
3668 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00003669 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
3670 BasicBlock *NewDefault = SplitBlockPredecessors(SI->getDefaultDest(),
3671 SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003672 SI->setDefaultDest(&*NewDefault);
3673 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00003674 auto *OldTI = NewDefault->getTerminator();
3675 new UnreachableInst(SI->getContext(), OldTI);
3676 EraseTerminatorInstAndDCECond(OldTI);
3677 return true;
3678 }
3679
Manman Ren56575552012-09-18 00:47:33 +00003680 SmallVector<uint64_t, 8> Weights;
3681 bool HasWeight = HasBranchWeights(SI);
3682 if (HasWeight) {
3683 GetBranchWeights(SI, Weights);
3684 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3685 }
3686
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003687 // Remove dead cases from the switch.
3688 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003689 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003690 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003691 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003692 if (HasWeight) {
3693 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3694 Weights.pop_back();
3695 }
3696
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003697 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003698 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003699 SI->removeCase(Case);
3700 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003701 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003702 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3703 SI->setMetadata(LLVMContext::MD_prof,
3704 MDBuilder(SI->getParent()->getContext()).
3705 createBranchWeights(MDWeights));
3706 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003707
3708 return !DeadCases.empty();
3709}
3710
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003711/// If BB would be eligible for simplification by
3712/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003713/// by an unconditional branch), look at the phi node for BB in the successor
3714/// block and see if the incoming value is equal to CaseValue. If so, return
3715/// the phi node, and set PhiIndex to BB's index in the phi node.
3716static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3717 BasicBlock *BB,
3718 int *PhiIndex) {
3719 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003720 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003721 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003722 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003723
3724 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3725 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003726 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003727
3728 BasicBlock *Succ = Branch->getSuccessor(0);
3729
3730 BasicBlock::iterator I = Succ->begin();
3731 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3732 int Idx = PHI->getBasicBlockIndex(BB);
3733 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3734
3735 Value *InValue = PHI->getIncomingValue(Idx);
3736 if (InValue != CaseValue) continue;
3737
3738 *PhiIndex = Idx;
3739 return PHI;
3740 }
3741
Craig Topperf40110f2014-04-25 05:29:35 +00003742 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003743}
3744
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003745/// Try to forward the condition of a switch instruction to a phi node
3746/// dominated by the switch, if that would mean that some of the destination
3747/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003748/// Returns true if a change is made.
3749static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3750 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3751 ForwardingNodesMap ForwardingNodes;
3752
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003753 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003754 ConstantInt *CaseValue = I.getCaseValue();
3755 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003756
3757 int PhiIndex;
3758 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3759 &PhiIndex);
3760 if (!PHI) continue;
3761
3762 ForwardingNodes[PHI].push_back(PhiIndex);
3763 }
3764
3765 bool Changed = false;
3766
3767 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3768 E = ForwardingNodes.end(); I != E; ++I) {
3769 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003770 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003771
3772 if (Indexes.size() < 2) continue;
3773
3774 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3775 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3776 Changed = true;
3777 }
3778
3779 return Changed;
3780}
3781
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003782/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003783/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003784static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003785 if (C->isThreadDependent())
3786 return false;
3787 if (C->isDLLImportDependent())
3788 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003789
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003790 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3791 return CE->isGEPWithNoNotionalOverIndexing();
3792
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003793 return isa<ConstantFP>(C) ||
3794 isa<ConstantInt>(C) ||
3795 isa<ConstantPointerNull>(C) ||
3796 isa<GlobalValue>(C) ||
3797 isa<UndefValue>(C);
3798}
3799
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003800/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003801/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003802static Constant *LookupConstant(Value *V,
3803 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3804 if (Constant *C = dyn_cast<Constant>(V))
3805 return C;
3806 return ConstantPool.lookup(V);
3807}
3808
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003809/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003810/// simple instructions such as binary operations where both operands are
3811/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003812/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003813static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003814ConstantFold(Instruction *I, const DataLayout &DL,
3815 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003816 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003817 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3818 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003819 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003820 if (A->isAllOnesValue())
3821 return LookupConstant(Select->getTrueValue(), ConstantPool);
3822 if (A->isNullValue())
3823 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003824 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003825 }
3826
Benjamin Kramer7c302602013-11-12 12:24:36 +00003827 SmallVector<Constant *, 4> COps;
3828 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3829 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3830 COps.push_back(A);
3831 else
Craig Topperf40110f2014-04-25 05:29:35 +00003832 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003833 }
3834
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003835 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00003836 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3837 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003838 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00003839
3840 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003841}
3842
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003843/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003844/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003845/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003846/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003847static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003848GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00003849 BasicBlock **CommonDest,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003850 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
3851 const DataLayout &DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003852 // The block from which we enter the common destination.
3853 BasicBlock *Pred = SI->getParent();
3854
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003855 // If CaseDest is empty except for some side-effect free instructions through
3856 // which we can constant-propagate the CaseVal, continue to its successor.
3857 SmallDenseMap<Value*, Constant*> ConstantPool;
3858 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3859 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3860 ++I) {
3861 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3862 // If the terminator is a simple branch, continue to the next block.
3863 if (T->getNumSuccessors() != 1)
3864 return false;
3865 Pred = CaseDest;
3866 CaseDest = T->getSuccessor(0);
3867 } else if (isa<DbgInfoIntrinsic>(I)) {
3868 // Skip debug intrinsic.
3869 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003870 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003871 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00003872
3873 // If the instruction has uses outside this block or a phi node slot for
3874 // the block, it is not safe to bypass the instruction since it would then
3875 // no longer dominate all its uses.
3876 for (auto &Use : I->uses()) {
3877 User *User = Use.getUser();
3878 if (Instruction *I = dyn_cast<Instruction>(User))
3879 if (I->getParent() == CaseDest)
3880 continue;
3881 if (PHINode *Phi = dyn_cast<PHINode>(User))
3882 if (Phi->getIncomingBlock(Use) == CaseDest)
3883 continue;
3884 return false;
3885 }
3886
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003887 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003888 } else {
3889 break;
3890 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003891 }
3892
3893 // If we did not have a CommonDest before, use the current one.
3894 if (!*CommonDest)
3895 *CommonDest = CaseDest;
3896 // If the destination isn't the common one, abort.
3897 if (CaseDest != *CommonDest)
3898 return false;
3899
3900 // Get the values for this case from phi nodes in the destination block.
3901 BasicBlock::iterator I = (*CommonDest)->begin();
3902 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3903 int Idx = PHI->getBasicBlockIndex(Pred);
3904 if (Idx == -1)
3905 continue;
3906
Hans Wennborg09acdb92012-10-31 15:14:39 +00003907 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3908 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003909 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003910 return false;
3911
3912 // Be conservative about which kinds of constants we support.
3913 if (!ValidLookupTableConstant(ConstVal))
3914 return false;
3915
3916 Res.push_back(std::make_pair(PHI, ConstVal));
3917 }
3918
Hans Wennborgac114a32014-01-12 00:44:41 +00003919 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003920}
3921
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003922// Helper function used to add CaseVal to the list of cases that generate
3923// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003924static void MapCaseToResult(ConstantInt *CaseVal,
3925 SwitchCaseResultVectorTy &UniqueResults,
3926 Constant *Result) {
3927 for (auto &I : UniqueResults) {
3928 if (I.first == Result) {
3929 I.second.push_back(CaseVal);
3930 return;
3931 }
3932 }
3933 UniqueResults.push_back(std::make_pair(Result,
3934 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3935}
3936
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003937// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003938// results for the PHI node of the common destination block for a switch
3939// instruction. Returns false if multiple PHI nodes have been found or if
3940// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003941static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
3942 BasicBlock *&CommonDest,
3943 SwitchCaseResultVectorTy &UniqueResults,
3944 Constant *&DefaultResult,
3945 const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003946 for (auto &I : SI->cases()) {
3947 ConstantInt *CaseVal = I.getCaseValue();
3948
3949 // Resulting value at phi nodes for this case value.
3950 SwitchCaseResultsTy Results;
3951 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3952 DL))
3953 return false;
3954
3955 // Only one value per case is permitted
3956 if (Results.size() > 1)
3957 return false;
3958 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3959
3960 // Check the PHI consistency.
3961 if (!PHI)
3962 PHI = Results[0].first;
3963 else if (PHI != Results[0].first)
3964 return false;
3965 }
3966 // Find the default result value.
3967 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3968 BasicBlock *DefaultDest = SI->getDefaultDest();
3969 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3970 DL);
3971 // If the default value is not found abort unless the default destination
3972 // is unreachable.
3973 DefaultResult =
3974 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3975 if ((!DefaultResult &&
3976 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3977 return false;
3978
3979 return true;
3980}
3981
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003982// Helper function that checks if it is possible to transform a switch with only
3983// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003984// Example:
3985// switch (a) {
3986// case 10: %0 = icmp eq i32 %a, 10
3987// return 10; %1 = select i1 %0, i32 10, i32 4
3988// case 20: ----> %2 = icmp eq i32 %a, 20
3989// return 2; %3 = select i1 %2, i32 2, i32 %1
3990// default:
3991// return 4;
3992// }
3993static Value *
3994ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3995 Constant *DefaultResult, Value *Condition,
3996 IRBuilder<> &Builder) {
3997 assert(ResultVector.size() == 2 &&
3998 "We should have exactly two unique results at this point");
3999 // If we are selecting between only two cases transform into a simple
4000 // select or a two-way select if default is possible.
4001 if (ResultVector[0].second.size() == 1 &&
4002 ResultVector[1].second.size() == 1) {
4003 ConstantInt *const FirstCase = ResultVector[0].second[0];
4004 ConstantInt *const SecondCase = ResultVector[1].second[0];
4005
4006 bool DefaultCanTrigger = DefaultResult;
4007 Value *SelectValue = ResultVector[1].first;
4008 if (DefaultCanTrigger) {
4009 Value *const ValueCompare =
4010 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4011 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4012 DefaultResult, "switch.select");
4013 }
4014 Value *const ValueCompare =
4015 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
4016 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
4017 "switch.select");
4018 }
4019
4020 return nullptr;
4021}
4022
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004023// Helper function to cleanup a switch instruction that has been converted into
4024// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004025static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4026 Value *SelectValue,
4027 IRBuilder<> &Builder) {
4028 BasicBlock *SelectBB = SI->getParent();
4029 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4030 PHI->removeIncomingValue(SelectBB);
4031 PHI->addIncoming(SelectValue, SelectBB);
4032
4033 Builder.CreateBr(PHI->getParent());
4034
4035 // Remove the switch.
4036 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4037 BasicBlock *Succ = SI->getSuccessor(i);
4038
4039 if (Succ == PHI->getParent())
4040 continue;
4041 Succ->removePredecessor(SelectBB);
4042 }
4043 SI->eraseFromParent();
4044}
4045
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004046/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004047/// phi nodes in a common successor block with only two different
4048/// constant values, replace the switch with select.
4049static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004050 AssumptionCache *AC, const DataLayout &DL) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004051 Value *const Cond = SI->getCondition();
4052 PHINode *PHI = nullptr;
4053 BasicBlock *CommonDest = nullptr;
4054 Constant *DefaultResult;
4055 SwitchCaseResultVectorTy UniqueResults;
4056 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004057 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
4058 DL))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004059 return false;
4060 // Selects choose between maximum two values.
4061 if (UniqueResults.size() != 2)
4062 return false;
4063 assert(PHI != nullptr && "PHI for value select not found");
4064
4065 Builder.SetInsertPoint(SI);
4066 Value *SelectValue = ConvertTwoCaseSwitch(
4067 UniqueResults,
4068 DefaultResult, Cond, Builder);
4069 if (SelectValue) {
4070 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4071 return true;
4072 }
4073 // The switch couldn't be converted into a select.
4074 return false;
4075}
4076
Hans Wennborg776d7122012-09-26 09:34:53 +00004077namespace {
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004078 /// This class represents a lookup table that can be used to replace a switch.
Hans Wennborg776d7122012-09-26 09:34:53 +00004079 class SwitchLookupTable {
4080 public:
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004081 /// Create a lookup table to use as a switch replacement with the contents
4082 /// of Values, using DefaultValue to fill any holes in the table.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004083 SwitchLookupTable(
4084 Module &M, uint64_t TableSize, ConstantInt *Offset,
4085 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4086 Constant *DefaultValue, const DataLayout &DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004087
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004088 /// Build instructions with Builder to retrieve the value at
Hans Wennborg776d7122012-09-26 09:34:53 +00004089 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00004090 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00004091
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004092 /// Return true if a table with TableSize elements of
Hans Wennborg39583b82012-09-26 09:44:49 +00004093 /// type ElementType would fit in a target-legal register.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004094 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004095 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004096
Hans Wennborg776d7122012-09-26 09:34:53 +00004097 private:
4098 // Depending on the contents of the table, it can be represented in
4099 // different ways.
4100 enum {
4101 // For tables where each element contains the same value, we just have to
4102 // store that single value and return it for each lookup.
4103 SingleValueKind,
4104
Erik Eckstein105374f2014-11-17 09:13:57 +00004105 // For tables where there is a linear relationship between table index
4106 // and values. We calculate the result with a simple multiplication
4107 // and addition instead of a table lookup.
4108 LinearMapKind,
4109
Hans Wennborg39583b82012-09-26 09:44:49 +00004110 // For small tables with integer elements, we can pack them into a bitmap
4111 // that fits into a target-legal register. Values are retrieved by
4112 // shift and mask operations.
4113 BitMapKind,
4114
Hans Wennborg776d7122012-09-26 09:34:53 +00004115 // The table is stored as an array of values. Values are retrieved by load
4116 // instructions from the table.
4117 ArrayKind
4118 } Kind;
4119
4120 // For SingleValueKind, this is the single value.
4121 Constant *SingleValue;
4122
Hans Wennborg39583b82012-09-26 09:44:49 +00004123 // For BitMapKind, this is the bitmap.
4124 ConstantInt *BitMap;
4125 IntegerType *BitMapElementTy;
4126
Erik Eckstein105374f2014-11-17 09:13:57 +00004127 // For LinearMapKind, these are the constants used to derive the value.
4128 ConstantInt *LinearOffset;
4129 ConstantInt *LinearMultiplier;
4130
Hans Wennborg776d7122012-09-26 09:34:53 +00004131 // For ArrayKind, this is the array.
4132 GlobalVariable *Array;
4133 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +00004134}
Hans Wennborg776d7122012-09-26 09:34:53 +00004135
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004136SwitchLookupTable::SwitchLookupTable(
4137 Module &M, uint64_t TableSize, ConstantInt *Offset,
4138 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
4139 Constant *DefaultValue, const DataLayout &DL)
Craig Topperf40110f2014-04-25 05:29:35 +00004140 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00004141 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004142 assert(Values.size() && "Can't build lookup table without values!");
4143 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004144
4145 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00004146 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004147
Hans Wennborgac114a32014-01-12 00:44:41 +00004148 Type *ValueType = Values.begin()->second->getType();
4149
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004150 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00004151 SmallVector<Constant*, 64> TableContents(TableSize);
4152 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4153 ConstantInt *CaseVal = Values[I].first;
4154 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00004155 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004156
Hans Wennborg776d7122012-09-26 09:34:53 +00004157 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
4158 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004159 TableContents[Idx] = CaseRes;
4160
Hans Wennborg776d7122012-09-26 09:34:53 +00004161 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004162 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004163 }
4164
4165 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00004166 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00004167 assert(DefaultValue &&
4168 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00004169 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00004170 for (uint64_t I = 0; I < TableSize; ++I) {
4171 if (!TableContents[I])
4172 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004173 }
4174
Hans Wennborg776d7122012-09-26 09:34:53 +00004175 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004176 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004177 }
4178
Hans Wennborg776d7122012-09-26 09:34:53 +00004179 // If each element in the table contains the same value, we only need to store
4180 // that single value.
4181 if (SingleValue) {
4182 Kind = SingleValueKind;
4183 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004184 }
4185
Erik Eckstein105374f2014-11-17 09:13:57 +00004186 // Check if we can derive the value with a linear transformation from the
4187 // table index.
4188 if (isa<IntegerType>(ValueType)) {
4189 bool LinearMappingPossible = true;
4190 APInt PrevVal;
4191 APInt DistToPrev;
4192 assert(TableSize >= 2 && "Should be a SingleValue table.");
4193 // Check if there is the same distance between two consecutive values.
4194 for (uint64_t I = 0; I < TableSize; ++I) {
4195 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4196 if (!ConstVal) {
4197 // This is an undef. We could deal with it, but undefs in lookup tables
4198 // are very seldom. It's probably not worth the additional complexity.
4199 LinearMappingPossible = false;
4200 break;
4201 }
4202 APInt Val = ConstVal->getValue();
4203 if (I != 0) {
4204 APInt Dist = Val - PrevVal;
4205 if (I == 1) {
4206 DistToPrev = Dist;
4207 } else if (Dist != DistToPrev) {
4208 LinearMappingPossible = false;
4209 break;
4210 }
4211 }
4212 PrevVal = Val;
4213 }
4214 if (LinearMappingPossible) {
4215 LinearOffset = cast<ConstantInt>(TableContents[0]);
4216 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4217 Kind = LinearMapKind;
4218 ++NumLinearMaps;
4219 return;
4220 }
4221 }
4222
Hans Wennborg39583b82012-09-26 09:44:49 +00004223 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004224 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004225 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004226 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4227 for (uint64_t I = TableSize; I > 0; --I) {
4228 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00004229 // Insert values into the bitmap. Undef values are set to zero.
4230 if (!isa<UndefValue>(TableContents[I - 1])) {
4231 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4232 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4233 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004234 }
4235 BitMap = ConstantInt::get(M.getContext(), TableInt);
4236 BitMapElementTy = IT;
4237 Kind = BitMapKind;
4238 ++NumBitMaps;
4239 return;
4240 }
4241
Hans Wennborg776d7122012-09-26 09:34:53 +00004242 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004243 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004244 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4245
Hans Wennborg776d7122012-09-26 09:34:53 +00004246 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
4247 GlobalVariable::PrivateLinkage,
4248 Initializer,
4249 "switch.table");
4250 Array->setUnnamedAddr(true);
4251 Kind = ArrayKind;
4252}
4253
Manman Ren4d189fb2014-07-24 21:13:20 +00004254Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004255 switch (Kind) {
4256 case SingleValueKind:
4257 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00004258 case LinearMapKind: {
4259 // Derive the result value from the input value.
4260 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4261 false, "switch.idx.cast");
4262 if (!LinearMultiplier->isOne())
4263 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4264 if (!LinearOffset->isZero())
4265 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4266 return Result;
4267 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004268 case BitMapKind: {
4269 // Type of the bitmap (e.g. i59).
4270 IntegerType *MapTy = BitMap->getType();
4271
4272 // Cast Index to the same type as the bitmap.
4273 // Note: The Index is <= the number of elements in the table, so
4274 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00004275 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004276
4277 // Multiply the shift amount by the element width.
4278 ShiftAmt = Builder.CreateMul(ShiftAmt,
4279 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
4280 "switch.shiftamt");
4281
4282 // Shift down.
4283 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
4284 "switch.downshift");
4285 // Mask off.
4286 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
4287 "switch.masked");
4288 }
Hans Wennborg776d7122012-09-26 09:34:53 +00004289 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00004290 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00004291 IntegerType *IT = cast<IntegerType>(Index->getType());
4292 uint64_t TableSize = Array->getInitializer()->getType()
4293 ->getArrayNumElements();
4294 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
4295 Index = Builder.CreateZExt(Index,
4296 IntegerType::get(IT->getContext(),
4297 IT->getBitWidth() + 1),
4298 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00004299
Hans Wennborg776d7122012-09-26 09:34:53 +00004300 Value *GEPIndices[] = { Builder.getInt32(0), Index };
David Blaikieaa41cd52015-04-03 21:33:42 +00004301 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
4302 GEPIndices, "switch.gep");
Hans Wennborg776d7122012-09-26 09:34:53 +00004303 return Builder.CreateLoad(GEP, "switch.load");
4304 }
4305 }
4306 llvm_unreachable("Unknown lookup table kind!");
4307}
4308
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004309bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00004310 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00004311 Type *ElementType) {
4312 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004313 if (!IT)
4314 return false;
4315 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
4316 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00004317
4318 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
4319 if (TableSize >= UINT_MAX/IT->getBitWidth())
4320 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004321 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00004322}
4323
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004324/// Determine whether a lookup table should be built for this switch, based on
4325/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004326static bool
4327ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
4328 const TargetTransformInfo &TTI, const DataLayout &DL,
4329 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004330 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
4331 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00004332
Chandler Carruth77d433d2012-11-30 09:26:25 +00004333 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00004334 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00004335 for (const auto &I : ResultTypes) {
4336 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004337
4338 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004339 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004340
4341 // Saturate this flag to false.
4342 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004343 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00004344
4345 // If both flags saturate, we're done. NOTE: This *only* works with
4346 // saturating flags, and all flags have to saturate first due to the
4347 // non-deterministic behavior of iterating over a dense map.
4348 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00004349 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00004350 }
Evan Cheng65df8082012-11-30 02:02:42 +00004351
Chandler Carruth77d433d2012-11-30 09:26:25 +00004352 // If each table would fit in a register, we should build it anyway.
4353 if (AllTablesFitInRegister)
4354 return true;
4355
4356 // Don't build a table that doesn't fit in-register if it has illegal types.
4357 if (HasIllegalType)
4358 return false;
4359
4360 // The table density should be at least 40%. This is the same criterion as for
4361 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
4362 // FIXME: Find the best cut-off.
4363 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004364}
4365
Erik Eckstein0d86c762014-11-27 15:13:14 +00004366/// Try to reuse the switch table index compare. Following pattern:
4367/// \code
4368/// if (idx < tablesize)
4369/// r = table[idx]; // table does not contain default_value
4370/// else
4371/// r = default_value;
4372/// if (r != default_value)
4373/// ...
4374/// \endcode
4375/// Is optimized to:
4376/// \code
4377/// cond = idx < tablesize;
4378/// if (cond)
4379/// r = table[idx];
4380/// else
4381/// r = default_value;
4382/// if (cond)
4383/// ...
4384/// \endcode
4385/// Jump threading will then eliminate the second if(cond).
4386static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
4387 BranchInst *RangeCheckBranch, Constant *DefaultValue,
4388 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
4389
4390 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
4391 if (!CmpInst)
4392 return;
4393
4394 // We require that the compare is in the same block as the phi so that jump
4395 // threading can do its work afterwards.
4396 if (CmpInst->getParent() != PhiBlock)
4397 return;
4398
4399 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
4400 if (!CmpOp1)
4401 return;
4402
4403 Value *RangeCmp = RangeCheckBranch->getCondition();
4404 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
4405 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
4406
4407 // Check if the compare with the default value is constant true or false.
4408 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4409 DefaultValue, CmpOp1, true);
4410 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
4411 return;
4412
4413 // Check if the compare with the case values is distinct from the default
4414 // compare result.
4415 for (auto ValuePair : Values) {
4416 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
4417 ValuePair.second, CmpOp1, true);
4418 if (!CaseConst || CaseConst == DefaultConst)
4419 return;
4420 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
4421 "Expect true or false as compare result.");
4422 }
James Molloy4de84dd2015-11-04 15:28:04 +00004423
Erik Eckstein0d86c762014-11-27 15:13:14 +00004424 // Check if the branch instruction dominates the phi node. It's a simple
4425 // dominance check, but sufficient for our needs.
4426 // Although this check is invariant in the calling loops, it's better to do it
4427 // at this late stage. Practically we do it at most once for a switch.
4428 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
4429 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
4430 BasicBlock *Pred = *PI;
4431 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
4432 return;
4433 }
4434
4435 if (DefaultConst == FalseConst) {
4436 // The compare yields the same result. We can replace it.
4437 CmpInst->replaceAllUsesWith(RangeCmp);
4438 ++NumTableCmpReuses;
4439 } else {
4440 // The compare yields the same result, just inverted. We can replace it.
4441 Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
4442 ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
4443 RangeCheckBranch);
4444 CmpInst->replaceAllUsesWith(InvertedTableCmp);
4445 ++NumTableCmpReuses;
4446 }
4447}
4448
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004449/// If the switch is only used to initialize one or more phi nodes in a common
4450/// successor block with different constant values, replace the switch with
4451/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004452static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
4453 const DataLayout &DL,
4454 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004455 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00004456
Hans Wennborgc3c8d952012-11-07 21:35:12 +00004457 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004458 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00004459 return false;
4460
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004461 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
4462 // split off a dense part and build a lookup table for that.
4463
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004464 // FIXME: This creates arrays of GEPs to constant strings, which means each
4465 // GEP needs a runtime relocation in PIC code. We should just build one big
4466 // string and lookup indices into that.
4467
Hans Wennborg4744ac12014-01-15 05:00:27 +00004468 // Ignore switches with less than three cases. Lookup tables will not make them
4469 // faster, so we don't analyze them.
4470 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004471 return false;
4472
4473 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00004474 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004475 assert(SI->case_begin() != SI->case_end());
4476 SwitchInst::CaseIt CI = SI->case_begin();
4477 ConstantInt *MinCaseVal = CI.getCaseValue();
4478 ConstantInt *MaxCaseVal = CI.getCaseValue();
4479
Craig Topperf40110f2014-04-25 05:29:35 +00004480 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004481 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004482 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
4483 SmallDenseMap<PHINode*, Constant*> DefaultResults;
4484 SmallDenseMap<PHINode*, Type*> ResultTypes;
4485 SmallVector<PHINode*, 4> PHIs;
4486
4487 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
4488 ConstantInt *CaseVal = CI.getCaseValue();
4489 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
4490 MinCaseVal = CaseVal;
4491 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
4492 MaxCaseVal = CaseVal;
4493
4494 // Resulting value at phi nodes for this case value.
4495 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
4496 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004497 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004498 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004499 return false;
4500
4501 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004502 for (const auto &I : Results) {
4503 PHINode *PHI = I.first;
4504 Constant *Value = I.second;
4505 if (!ResultLists.count(PHI))
4506 PHIs.push_back(PHI);
4507 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004508 }
4509 }
4510
Hans Wennborgac114a32014-01-12 00:44:41 +00004511 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00004512 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004513 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
4514 }
4515
4516 uint64_t NumResults = ResultLists[PHIs[0]].size();
4517 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
4518 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
4519 bool TableHasHoles = (NumResults < TableSize);
4520
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004521 // If the table has holes, we need a constant result for the default case
4522 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004523 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Erik Eckstein0d86c762014-11-27 15:13:14 +00004524 bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004525 &CommonDest, DefaultResultsList, DL);
Hans Wennborga6a11a92014-11-18 02:37:11 +00004526
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004527 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4528 if (NeedMask) {
4529 // As an extra penalty for the validity test we require more cases.
4530 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4531 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004532 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004533 return false;
4534 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004535
Hans Wennborga6a11a92014-11-18 02:37:11 +00004536 for (const auto &I : DefaultResultsList) {
4537 PHINode *PHI = I.first;
4538 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004539 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004540 }
4541
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004542 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004543 return false;
4544
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004545 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004546 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004547 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4548 "switch.lookup",
4549 CommonDest->getParent(),
4550 CommonDest);
4551
Michael Gottesmanc024f322013-10-20 07:04:37 +00004552 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004553 Builder.SetInsertPoint(SI);
4554 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4555 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004556
4557 // Compute the maximum table size representable by the integer type we are
4558 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004559 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004560 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004561 assert(MaxTableSize >= TableSize &&
4562 "It is impossible for a switch to have more entries than the max "
4563 "representable value of its input integer type's size.");
4564
Hans Wennborgb64cb272015-01-26 19:52:34 +00004565 // If the default destination is unreachable, or if the lookup table covers
4566 // all values of the conditional variable, branch directly to the lookup table
4567 // BB. Otherwise, check that the condition is within the case range.
4568 const bool DefaultIsReachable =
4569 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4570 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00004571 BranchInst *RangeCheckBranch = nullptr;
4572
Hans Wennborgb64cb272015-01-26 19:52:34 +00004573 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00004574 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00004575 // Note: We call removeProdecessor later since we need to be able to get the
4576 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00004577 } else {
4578 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004579 MinCaseVal->getType(), TableSize));
Erik Eckstein0d86c762014-11-27 15:13:14 +00004580 RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00004581 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004582
4583 // Populate the BB that does the lookups.
4584 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004585
4586 if (NeedMask) {
4587 // Before doing the lookup we do the hole check.
4588 // The LookupBB is therefore re-purposed to do the hole check
4589 // and we create a new LookupBB.
4590 BasicBlock *MaskBB = LookupBB;
4591 MaskBB->setName("switch.hole_check");
4592 LookupBB = BasicBlock::Create(Mod.getContext(),
4593 "switch.lookup",
4594 CommonDest->getParent(),
4595 CommonDest);
4596
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004597 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4598 // unnecessary illegal types.
4599 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4600 APInt MaskInt(TableSizePowOf2, 0);
4601 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004602 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004603 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4604 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4605 uint64_t Idx = (ResultList[I].first->getValue() -
4606 MinCaseVal->getValue()).getLimitedValue();
4607 MaskInt |= One << Idx;
4608 }
4609 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4610
4611 // Get the TableIndex'th bit of the bitmask.
4612 // If this bit is 0 (meaning hole) jump to the default destination,
4613 // else continue with table lookup.
4614 IntegerType *MapTy = TableMask->getType();
4615 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4616 "switch.maskindex");
4617 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4618 "switch.shifted");
4619 Value *LoBit = Builder.CreateTrunc(Shifted,
4620 Type::getInt1Ty(Mod.getContext()),
4621 "switch.lobit");
4622 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4623
4624 Builder.SetInsertPoint(LookupBB);
4625 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4626 }
4627
Hans Wennborg86ac6302015-04-24 20:57:56 +00004628 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
4629 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4630 // do not delete PHINodes here.
4631 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4632 /*DontDeleteUselessPHIs=*/true);
4633 }
4634
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004635 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004636 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4637 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004638 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004639
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004640 // If using a bitmask, use any value to fill the lookup table holes.
4641 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Erik Eckstein0d86c762014-11-27 15:13:14 +00004642 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004643
Manman Ren4d189fb2014-07-24 21:13:20 +00004644 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004645
Hans Wennborgf744fa92012-09-19 14:24:21 +00004646 // If the result is used to return immediately from the function, we want to
4647 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004648 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4649 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004650 Builder.CreateRet(Result);
4651 ReturnedEarly = true;
4652 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004653 }
4654
Erik Eckstein0d86c762014-11-27 15:13:14 +00004655 // Do a small peephole optimization: re-use the switch table compare if
4656 // possible.
4657 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
4658 BasicBlock *PhiBlock = PHI->getParent();
4659 // Search for compare instructions which use the phi.
4660 for (auto *User : PHI->users()) {
4661 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
4662 }
4663 }
4664
Hans Wennborgf744fa92012-09-19 14:24:21 +00004665 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004666 }
4667
4668 if (!ReturnedEarly)
4669 Builder.CreateBr(CommonDest);
4670
4671 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004672 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004673 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004674
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004675 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004676 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004677 Succ->removePredecessor(SI->getParent());
4678 }
4679 SI->eraseFromParent();
4680
4681 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004682 if (NeedMask)
4683 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004684 return true;
4685}
4686
Devang Patela7ec47d2011-05-18 20:35:38 +00004687bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004688 BasicBlock *BB = SI->getParent();
4689
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004690 if (isValueEqualityComparison(SI)) {
4691 // If we only have one predecessor, and if it is a branch on this value,
4692 // see if that predecessor totally determines the outcome of this switch.
4693 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4694 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004695 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004696
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004697 Value *Cond = SI->getCondition();
4698 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4699 if (SimplifySwitchOnSelect(SI, Select))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004700 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004701
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004702 // If the block only contains the switch, see if we can fold the block
4703 // away into any preds.
4704 BasicBlock::iterator BBI = BB->begin();
4705 // Ignore dbg intrinsics.
4706 while (isa<DbgInfoIntrinsic>(BBI))
4707 ++BBI;
4708 if (SI == &*BBI)
4709 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004710 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004711 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004712
4713 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004714 if (TurnSwitchRangeIntoICmp(SI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004715 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004716
4717 // Remove unreachable cases.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004718 if (EliminateDeadSwitchCases(SI, AC, DL))
4719 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004720
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004721 if (SwitchToSelect(SI, Builder, AC, DL))
4722 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004723
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004724 if (ForwardSwitchConditionToPHI(SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004725 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004726
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004727 if (SwitchToLookupTable(SI, Builder, DL, TTI))
4728 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004729
Chris Lattner25c3af32010-12-13 06:25:44 +00004730 return false;
4731}
4732
4733bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4734 BasicBlock *BB = IBI->getParent();
4735 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004736
Chris Lattner25c3af32010-12-13 06:25:44 +00004737 // Eliminate redundant destinations.
4738 SmallPtrSet<Value *, 8> Succs;
4739 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4740 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00004741 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004742 Dest->removePredecessor(BB);
4743 IBI->removeDestination(i);
4744 --i; --e;
4745 Changed = true;
4746 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004747 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004748
4749 if (IBI->getNumDestinations() == 0) {
4750 // If the indirectbr has no successors, change it to unreachable.
4751 new UnreachableInst(IBI->getContext(), IBI);
4752 EraseTerminatorInstAndDCECond(IBI);
4753 return true;
4754 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004755
Chris Lattner25c3af32010-12-13 06:25:44 +00004756 if (IBI->getNumDestinations() == 1) {
4757 // If the indirectbr has one successor, change it to a direct branch.
4758 BranchInst::Create(IBI->getDestination(0), IBI);
4759 EraseTerminatorInstAndDCECond(IBI);
4760 return true;
4761 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004762
Chris Lattner25c3af32010-12-13 06:25:44 +00004763 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4764 if (SimplifyIndirectBrOnSelect(IBI, SI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004765 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004766 }
4767 return Changed;
4768}
4769
Philip Reames2b969d72015-03-24 22:28:45 +00004770/// Given an block with only a single landing pad and a unconditional branch
4771/// try to find another basic block which this one can be merged with. This
4772/// handles cases where we have multiple invokes with unique landing pads, but
4773/// a shared handler.
4774///
4775/// We specifically choose to not worry about merging non-empty blocks
4776/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
4777/// practice, the optimizer produces empty landing pad blocks quite frequently
4778/// when dealing with exception dense code. (see: instcombine, gvn, if-else
4779/// sinking in this file)
4780///
4781/// This is primarily a code size optimization. We need to avoid performing
4782/// any transform which might inhibit optimization (such as our ability to
4783/// specialize a particular handler via tail commoning). We do this by not
4784/// merging any blocks which require us to introduce a phi. Since the same
4785/// values are flowing through both blocks, we don't loose any ability to
4786/// specialize. If anything, we make such specialization more likely.
4787///
4788/// TODO - This transformation could remove entries from a phi in the target
4789/// block when the inputs in the phi are the same for the two blocks being
4790/// merged. In some cases, this could result in removal of the PHI entirely.
4791static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
4792 BasicBlock *BB) {
4793 auto Succ = BB->getUniqueSuccessor();
4794 assert(Succ);
4795 // If there's a phi in the successor block, we'd likely have to introduce
4796 // a phi into the merged landing pad block.
4797 if (isa<PHINode>(*Succ->begin()))
4798 return false;
4799
4800 for (BasicBlock *OtherPred : predecessors(Succ)) {
4801 if (BB == OtherPred)
4802 continue;
4803 BasicBlock::iterator I = OtherPred->begin();
4804 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
4805 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
4806 continue;
4807 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4808 BranchInst *BI2 = dyn_cast<BranchInst>(I);
4809 if (!BI2 || !BI2->isIdenticalTo(BI))
4810 continue;
4811
4812 // We've found an identical block. Update our predeccessors to take that
4813 // path instead and make ourselves dead.
4814 SmallSet<BasicBlock *, 16> Preds;
4815 Preds.insert(pred_begin(BB), pred_end(BB));
4816 for (BasicBlock *Pred : Preds) {
4817 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
4818 assert(II->getNormalDest() != BB &&
4819 II->getUnwindDest() == BB && "unexpected successor");
4820 II->setUnwindDest(OtherPred);
4821 }
4822
4823 // The debug info in OtherPred doesn't cover the merged control flow that
4824 // used to go through BB. We need to delete it or update it.
4825 for (auto I = OtherPred->begin(), E = OtherPred->end();
4826 I != E;) {
4827 Instruction &Inst = *I; I++;
4828 if (isa<DbgInfoIntrinsic>(Inst))
4829 Inst.eraseFromParent();
4830 }
4831
4832 SmallSet<BasicBlock *, 16> Succs;
4833 Succs.insert(succ_begin(BB), succ_end(BB));
4834 for (BasicBlock *Succ : Succs) {
4835 Succ->removePredecessor(BB);
4836 }
4837
4838 IRBuilder<> Builder(BI);
4839 Builder.CreateUnreachable();
4840 BI->eraseFromParent();
4841 return true;
4842 }
4843 return false;
4844}
4845
Devang Patel767f6932011-05-18 18:28:48 +00004846bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00004847 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004848
Manman Ren93ab6492012-09-20 22:37:36 +00004849 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4850 return true;
4851
Chris Lattner25c3af32010-12-13 06:25:44 +00004852 // If the Terminator is the only non-phi instruction, simplify the block.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004853 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00004854 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4855 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4856 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004857
Chris Lattner25c3af32010-12-13 06:25:44 +00004858 // If the only instruction in the block is a seteq/setne comparison
4859 // against a constant, try to simplify the block.
4860 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4861 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4862 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4863 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004864 if (I->isTerminator() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004865 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
4866 BonusInstThreshold, AC))
Chris Lattner25c3af32010-12-13 06:25:44 +00004867 return true;
4868 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004869
Philip Reames2b969d72015-03-24 22:28:45 +00004870 // See if we can merge an empty landing pad block with another which is
4871 // equivalent.
4872 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
4873 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
4874 if (I->isTerminator() &&
4875 TryToMergeLandingPad(LPad, BI, BB))
4876 return true;
4877 }
4878
Manman Rend33f4ef2012-06-13 05:43:29 +00004879 // If this basic block is ONLY a compare and a branch, and if a predecessor
4880 // branches to us and our successor, fold the comparison into the
4881 // predecessor and use logical operations to update the incoming value
4882 // for PHI nodes in common successor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004883 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4884 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004885 return false;
4886}
4887
James Molloy4de84dd2015-11-04 15:28:04 +00004888static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
4889 BasicBlock *PredPred = nullptr;
4890 for (auto *P : predecessors(BB)) {
4891 BasicBlock *PPred = P->getSinglePredecessor();
4892 if (!PPred || (PredPred && PredPred != PPred))
4893 return nullptr;
4894 PredPred = PPred;
4895 }
4896 return PredPred;
4897}
Chris Lattner25c3af32010-12-13 06:25:44 +00004898
Devang Patela7ec47d2011-05-18 20:35:38 +00004899bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004900 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004901
Chris Lattner25c3af32010-12-13 06:25:44 +00004902 // Conditional branch
4903 if (isValueEqualityComparison(BI)) {
4904 // If we only have one predecessor, and if it is a branch on this value,
4905 // see if that predecessor totally determines the outcome of this
4906 // switch.
4907 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00004908 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004909 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004910
Chris Lattner25c3af32010-12-13 06:25:44 +00004911 // This block must be empty, except for the setcond inst, if it exists.
4912 // Ignore dbg intrinsics.
4913 BasicBlock::iterator I = BB->begin();
4914 // Ignore dbg intrinsics.
4915 while (isa<DbgInfoIntrinsic>(I))
4916 ++I;
4917 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00004918 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004919 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004920 } else if (&*I == cast<Instruction>(BI->getCondition())){
4921 ++I;
4922 // Ignore dbg intrinsics.
4923 while (isa<DbgInfoIntrinsic>(I))
4924 ++I;
Devang Patel58380552011-05-18 20:53:17 +00004925 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004926 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004927 }
4928 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004929
Chris Lattner25c3af32010-12-13 06:25:44 +00004930 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004931 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00004932 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004933
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00004934 // If this basic block is ONLY a compare and a branch, and if a predecessor
4935 // branches to us and one of our successors, fold the comparison into the
4936 // predecessor and use logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004937 if (FoldBranchToCommonDest(BI, BonusInstThreshold))
4938 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004939
Chris Lattner25c3af32010-12-13 06:25:44 +00004940 // We have a conditional branch to two blocks that are only reachable
4941 // from BI. We know that the condbr dominates the two blocks, so see if
4942 // there is any identical code in the "then" and "else" blocks. If so, we
4943 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00004944 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4945 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004946 if (HoistThenElseCodeToIf(BI, TTI))
4947 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004948 } else {
4949 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004950 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00004951 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4952 if (Succ0TI->getNumSuccessors() == 1 &&
4953 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004954 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
4955 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004956 }
Craig Topperf40110f2014-04-25 05:29:35 +00004957 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004958 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004959 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00004960 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4961 if (Succ1TI->getNumSuccessors() == 1 &&
4962 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004963 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
4964 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004965 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004966
Chris Lattner25c3af32010-12-13 06:25:44 +00004967 // If this is a branch on a phi node in the current block, thread control
4968 // through this block if any PHI node entries are constants.
4969 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4970 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004971 if (FoldCondBranchOnPHI(BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004972 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004973
Chris Lattner25c3af32010-12-13 06:25:44 +00004974 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004975 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4976 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00004977 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00004978 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004979 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004980
James Molloy4de84dd2015-11-04 15:28:04 +00004981 // Look for diamond patterns.
4982 if (MergeCondStores)
4983 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
4984 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
4985 if (PBI != BI && PBI->isConditional())
4986 if (mergeConditionalStores(PBI, BI))
4987 return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
4988
Chris Lattner25c3af32010-12-13 06:25:44 +00004989 return false;
4990}
4991
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004992/// Check if passing a value to an instruction will cause undefined behavior.
4993static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4994 Constant *C = dyn_cast<Constant>(V);
4995 if (!C)
4996 return false;
4997
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004998 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004999 return false;
5000
5001 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005002 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00005003 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005004
5005 // Now make sure that there are no instructions in between that can alter
5006 // control flow (eg. calls)
5007 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00005008 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005009 return false;
5010
5011 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5012 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5013 if (GEP->getPointerOperand() == I)
5014 return passingValueIsAlwaysUndefined(V, GEP);
5015
5016 // Look through bitcasts.
5017 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5018 return passingValueIsAlwaysUndefined(V, BC);
5019
Benjamin Kramer0655b782011-08-26 02:25:55 +00005020 // Load from null is undefined.
5021 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005022 if (!LI->isVolatile())
5023 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005024
Benjamin Kramer0655b782011-08-26 02:25:55 +00005025 // Store to null is undefined.
5026 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005027 if (!SI->isVolatile())
5028 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005029 }
5030 return false;
5031}
5032
5033/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005034/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005035static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5036 for (BasicBlock::iterator i = BB->begin();
5037 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5038 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5039 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5040 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5041 IRBuilder<> Builder(T);
5042 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5043 BB->removePredecessor(PHI->getIncomingBlock(i));
5044 // Turn uncoditional branches into unreachables and remove the dead
5045 // destination from conditional branches.
5046 if (BI->isUnconditional())
5047 Builder.CreateUnreachable();
5048 else
5049 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
5050 BI->getSuccessor(0));
5051 BI->eraseFromParent();
5052 return true;
5053 }
5054 // TODO: SwitchInst.
5055 }
5056
5057 return false;
5058}
5059
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005060bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00005061 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00005062
Chris Lattnerd7beca32010-12-14 06:17:25 +00005063 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00005064 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00005065
Dan Gohman4a63fad2010-08-14 00:29:42 +00005066 // Remove basic blocks that have no predecessors (except the entry block)...
5067 // or that just have themself as a predecessor. These are unreachable.
Ramkumar Ramachandra181233b2015-01-13 04:17:47 +00005068 if ((pred_empty(BB) &&
Chris Lattnerd7beca32010-12-14 06:17:25 +00005069 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00005070 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00005071 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00005072 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00005073 return true;
5074 }
5075
Chris Lattner031340a2003-08-17 19:41:53 +00005076 // Check to see if we can constant propagate this terminator instruction
5077 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00005078 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00005079
Dan Gohman1a951062009-10-30 22:39:04 +00005080 // Check for and eliminate duplicate PHI nodes in this block.
5081 Changed |= EliminateDuplicatePHINodes(BB);
5082
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005083 // Check for and remove branches that will always cause undefined behavior.
5084 Changed |= removeUndefIntroducingPredecessor(BB);
5085
Chris Lattner2e3832d2010-12-13 05:10:48 +00005086 // Merge basic blocks into their predecessor if there is only one distinct
5087 // pred, and if there is only one distinct successor of the predecessor, and
5088 // if there are no PHI nodes.
5089 //
5090 if (MergeBlockIntoPredecessor(BB))
5091 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005092
Devang Patel15ad6762011-05-18 18:01:27 +00005093 IRBuilder<> Builder(BB);
5094
Dan Gohman20af5a02008-03-11 21:53:06 +00005095 // If there is a trivial two-entry PHI node in this basic block, and we can
5096 // eliminate it, do so now.
5097 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5098 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005099 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00005100
Devang Patela7ec47d2011-05-18 20:35:38 +00005101 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00005102 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00005103 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00005104 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005105 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00005106 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005107 }
5108 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00005109 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00005110 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
5111 if (SimplifyResume(RI, Builder)) return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00005112 } else if (CleanupReturnInst *RI =
5113 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5114 if (SimplifyCleanupReturn(RI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005115 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00005116 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005117 } else if (UnreachableInst *UI =
5118 dyn_cast<UnreachableInst>(BB->getTerminator())) {
5119 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005120 } else if (IndirectBrInst *IBI =
5121 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
5122 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00005123 }
5124
Chris Lattner031340a2003-08-17 19:41:53 +00005125 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00005126}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005127
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005128/// This function is used to do simplification of a CFG.
5129/// For example, it adjusts branches to branches to eliminate the extra hop,
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005130/// eliminates unreachable basic blocks, and does other "peephole" optimization
5131/// of the CFG. It returns true if a modification was made.
5132///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005133bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005134 unsigned BonusInstThreshold, AssumptionCache *AC) {
5135 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
5136 BonusInstThreshold, AC).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005137}