blob: e3bdd6066be091b9e0f3a9c0c89000b58d314bbf [file] [log] [blame]
Chris Lattner466a0492002-05-21 20:50:24 +00001//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner466a0492002-05-21 20:50:24 +00009//
Chris Lattnera704ac82002-10-08 21:36:33 +000010// Peephole optimize the CFG.
Chris Lattner466a0492002-05-21 20:50:24 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SetVector.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000021#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000025#include "llvm/IR/CFG.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000026#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/MDBuilder.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000038#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Type.h"
Evan Chengd983eba2011-01-29 04:46:23 +000042#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000043#include "llvm/Support/Debug.h"
44#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Rafael Espindolaea46c322014-08-15 15:46:38 +000046#include "llvm/Transforms/Utils/Local.h"
Jingyue Wufc029672014-09-30 22:23:38 +000047#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000048#include <algorithm>
Chris Lattner5edb2f32004-10-18 04:07:22 +000049#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000050#include <set>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000051using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000052using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000053
Chandler Carruth964daaa2014-04-22 02:55:47 +000054#define DEBUG_TYPE "simplifycfg"
55
Peter Collingbourne616044a2011-04-29 18:47:38 +000056static cl::opt<unsigned>
57PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(1),
58 cl::desc("Control the amount of phi node folding to perform (default = 1)"));
59
Evan Chengd983eba2011-01-29 04:46:23 +000060static cl::opt<bool>
61DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
62 cl::desc("Duplicate return instructions into unconditional branches"));
63
Manman Ren93ab6492012-09-20 22:37:36 +000064static cl::opt<bool>
65SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
66 cl::desc("Sink common instructions down to the end block"));
67
Alp Tokercb402912014-01-24 17:20:08 +000068static cl::opt<bool> HoistCondStores(
69 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
70 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +000071
Hans Wennborg39583b82012-09-26 09:44:49 +000072STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Erik Eckstein105374f2014-11-17 09:13:57 +000073STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000074STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
Hans Wennborgb73c0b02014-03-12 18:35:40 +000075STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
Manman Ren93ab6492012-09-20 22:37:36 +000076STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +000077STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +000078
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +000079namespace {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +000080 // The first field contains the value that the switch produces when a certain
81 // case group is selected, and the second field is a vector containing the cases
82 // composing the case group.
83 typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
84 SwitchCaseResultVectorTy;
85 // The first field contains the phi node that generates a result of the switch
86 // and the second field contains the value generated for a certain case in the switch
87 // for that PHI.
88 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
89
Eric Christopherb65acc62012-07-02 23:22:21 +000090 /// ValueEqualityComparisonCase - Represents a case of a switch.
91 struct ValueEqualityComparisonCase {
92 ConstantInt *Value;
93 BasicBlock *Dest;
94
95 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
96 : Value(Value), Dest(Dest) {}
97
98 bool operator<(ValueEqualityComparisonCase RHS) const {
99 // Comparing pointers is ok as we only rely on the order for uniquing.
100 return Value < RHS.Value;
101 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000102
103 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
Eric Christopherb65acc62012-07-02 23:22:21 +0000104 };
105
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000106class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000107 const TargetTransformInfo &TTI;
Jingyue Wufc029672014-09-30 22:23:38 +0000108 unsigned BonusInstThreshold;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000109 const DataLayout *const DL;
Hal Finkel60db0582014-09-07 18:57:58 +0000110 AssumptionTracker *AT;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000111 Value *isValueEqualityComparison(TerminatorInst *TI);
112 BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000113 std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000114 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000115 BasicBlock *Pred,
116 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000117 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
118 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000119
Devang Pateldd14e0f2011-05-18 21:33:11 +0000120 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000121 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000122 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000123 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000124 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Devang Patel767f6932011-05-18 18:28:48 +0000125 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
Devang Patela7ec47d2011-05-18 20:35:38 +0000126 bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000127
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000128public:
Jingyue Wufc029672014-09-30 22:23:38 +0000129 SimplifyCFGOpt(const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
130 const DataLayout *DL, AssumptionTracker *AT)
131 : TTI(TTI), BonusInstThreshold(BonusInstThreshold), DL(DL), AT(AT) {}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000132 bool run(BasicBlock *BB);
133};
134}
135
Chris Lattner76dc2042005-08-03 00:19:45 +0000136/// SafeToMergeTerminators - Return true if it is safe to merge these two
137/// terminator instructions together.
138///
139static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
140 if (SI1 == SI2) return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000141
Chris Lattner76dc2042005-08-03 00:19:45 +0000142 // It is not safe to merge these two switch instructions if they have a common
143 // successor, and if that successor has a PHI node, and if *that* PHI node has
144 // conflicting incoming values from the two switch blocks.
145 BasicBlock *SI1BB = SI1->getParent();
146 BasicBlock *SI2BB = SI2->getParent();
Chris Lattnerb7b75142007-04-02 01:44:59 +0000147 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Andrew Trickf3cf1932012-08-29 21:46:36 +0000148
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000149 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
150 if (SI1Succs.count(*I))
151 for (BasicBlock::iterator BBI = (*I)->begin();
Chris Lattner76dc2042005-08-03 00:19:45 +0000152 isa<PHINode>(BBI); ++BBI) {
153 PHINode *PN = cast<PHINode>(BBI);
154 if (PN->getIncomingValueForBlock(SI1BB) !=
155 PN->getIncomingValueForBlock(SI2BB))
156 return false;
157 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000158
Chris Lattner76dc2042005-08-03 00:19:45 +0000159 return true;
160}
161
Manman Rend33f4ef2012-06-13 05:43:29 +0000162/// isProfitableToFoldUnconditional - Return true if it is safe and profitable
163/// to merge these two terminator instructions together, where SI1 is an
164/// unconditional branch. PhiNodes will store all PHI nodes in common
165/// successors.
166///
167static bool isProfitableToFoldUnconditional(BranchInst *SI1,
168 BranchInst *SI2,
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000169 Instruction *Cond,
Manman Rend33f4ef2012-06-13 05:43:29 +0000170 SmallVectorImpl<PHINode*> &PhiNodes) {
171 if (SI1 == SI2) return false; // Can't merge with self!
172 assert(SI1->isUnconditional() && SI2->isConditional());
173
174 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000175 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000176 // 1> We have a constant incoming value for the conditional branch;
177 // 2> We have "Cond" as the incoming value for the unconditional branch;
178 // 3> SI2->getCondition() and Cond have same operands.
179 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
180 if (!Ci2) return false;
181 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
182 Cond->getOperand(1) == Ci2->getOperand(1)) &&
183 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
184 Cond->getOperand(1) == Ci2->getOperand(0)))
185 return false;
186
187 BasicBlock *SI1BB = SI1->getParent();
188 BasicBlock *SI2BB = SI2->getParent();
189 SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000190 for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
191 if (SI1Succs.count(*I))
192 for (BasicBlock::iterator BBI = (*I)->begin();
Manman Rend33f4ef2012-06-13 05:43:29 +0000193 isa<PHINode>(BBI); ++BBI) {
194 PHINode *PN = cast<PHINode>(BBI);
195 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000196 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000197 return false;
198 PhiNodes.push_back(PN);
199 }
200 return true;
201}
202
Chris Lattner76dc2042005-08-03 00:19:45 +0000203/// AddPredecessorToBlock - Update PHI nodes in Succ to indicate that there will
204/// now be entries in it from the 'NewPred' block. The values that will be
205/// flowing into the PHI nodes will be the same as those coming in from
206/// ExistPred, an existing predecessor of Succ.
207static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
208 BasicBlock *ExistPred) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000209 if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000210
Chris Lattner80b03a12008-07-13 22:23:11 +0000211 PHINode *PN;
212 for (BasicBlock::iterator I = Succ->begin();
213 (PN = dyn_cast<PHINode>(I)); ++I)
214 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000215}
216
David Majnemer91142c42013-06-01 19:43:23 +0000217/// ComputeSpeculationCost - Compute an abstract "cost" of speculating the
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000218/// given instruction, which is assumed to be safe to speculate. 1 means
219/// cheap, 2 means less cheap, and UINT_MAX means prohibitively expensive.
Hal Finkela995f922014-07-10 14:41:31 +0000220static unsigned ComputeSpeculationCost(const User *I, const DataLayout *DL) {
221 assert(isSafeToSpeculativelyExecute(I, DL) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000222 "Instruction is not safe to speculatively execute!");
223 switch (Operator::getOpcode(I)) {
224 default:
225 // In doubt, be conservative.
226 return UINT_MAX;
227 case Instruction::GetElementPtr:
228 // GEPs are cheap if all indices are constant.
229 if (!cast<GEPOperator>(I)->hasAllConstantIndices())
230 return UINT_MAX;
231 return 1;
Louis Gerbarg1f54b822014-05-09 17:02:46 +0000232 case Instruction::ExtractValue:
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000233 case Instruction::Load:
234 case Instruction::Add:
235 case Instruction::Sub:
236 case Instruction::And:
237 case Instruction::Or:
238 case Instruction::Xor:
239 case Instruction::Shl:
240 case Instruction::LShr:
241 case Instruction::AShr:
242 case Instruction::ICmp:
243 case Instruction::Trunc:
244 case Instruction::ZExt:
245 case Instruction::SExt:
Matt Arsenaultc8fc08c2014-05-30 18:34:43 +0000246 case Instruction::BitCast:
247 case Instruction::ExtractElement:
248 case Instruction::InsertElement:
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000249 return 1; // These are all cheap.
250
251 case Instruction::Call:
252 case Instruction::Select:
253 return 2;
254 }
255}
256
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000257/// DominatesMergePoint - If we have a merge point of an "if condition" as
258/// accepted above, return true if the specified value dominates the block. We
259/// don't handle the true generality of domination here, just a special case
260/// which works well enough for us.
261///
262/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000263/// see if V (which must be an instruction) and its recursive operands
264/// that do not dominate BB have a combined cost lower than CostRemaining and
265/// are non-trapping. If both are true, the instruction is inserted into the
266/// set and true is returned.
267///
268/// The cost for most non-trapping instructions is defined as 1 except for
269/// Select whose cost is 2.
270///
271/// After this function returns, CostRemaining is decreased by the cost of
272/// V plus its non-dominating operands. If that cost is greater than
273/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000274static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000275 SmallPtrSetImpl<Instruction*> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000276 unsigned &CostRemaining,
277 const DataLayout *DL) {
Chris Lattner0aa56562004-04-09 22:50:22 +0000278 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000279 if (!I) {
280 // Non-instructions all dominate instructions, but not all constantexprs
281 // can be executed unconditionally.
282 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
283 if (C->canTrap())
284 return false;
285 return true;
286 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000287 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000288
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000289 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000290 // the bottom of this block.
291 if (PBB == BB) return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000292
Chris Lattner0aa56562004-04-09 22:50:22 +0000293 // If this instruction is defined in a block that contains an unconditional
294 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000295 // statement". If not, it definitely dominates the region.
296 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000297 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000298 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000299
Chris Lattner9ac168d2010-12-14 07:41:39 +0000300 // If we aren't allowing aggressive promotion anymore, then don't consider
301 // instructions in the 'if region'.
Craig Topperf40110f2014-04-25 05:29:35 +0000302 if (!AggressiveInsts) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000303
Peter Collingbournee3511e12011-04-29 18:47:31 +0000304 // If we have seen this instruction before, don't count it again.
305 if (AggressiveInsts->count(I)) return true;
306
Chris Lattner9ac168d2010-12-14 07:41:39 +0000307 // Okay, it looks like the instruction IS in the "condition". Check to
308 // see if it's a cheap instruction to unconditionally compute, and if it
309 // only uses stuff defined outside of the condition. If so, hoist it out.
Hal Finkela995f922014-07-10 14:41:31 +0000310 if (!isSafeToSpeculativelyExecute(I, DL))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000311 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000312
Hal Finkela995f922014-07-10 14:41:31 +0000313 unsigned Cost = ComputeSpeculationCost(I, DL);
Chris Lattner0aa56562004-04-09 22:50:22 +0000314
Peter Collingbournee3511e12011-04-29 18:47:31 +0000315 if (Cost > CostRemaining)
316 return false;
317
318 CostRemaining -= Cost;
319
320 // Okay, we can only really hoist these out if their operands do
321 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000322 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
Hal Finkela995f922014-07-10 14:41:31 +0000323 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, DL))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000324 return false;
325 // Okay, it's safe to do this! Remember this instruction.
326 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000327 return true;
328}
Chris Lattner466a0492002-05-21 20:50:24 +0000329
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000330/// GetConstantInt - Extract ConstantInt from value, looking through IntToPtr
331/// and PointerNullValue. Return NULL if value is not a constant int.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000332static ConstantInt *GetConstantInt(Value *V, const DataLayout *DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000333 // Normal constant int.
334 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000335 if (CI || !DL || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000336 return CI;
337
338 // This is some kind of pointer constant. Turn it into a pointer-sized
339 // ConstantInt if possible.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000340 IntegerType *PtrTy = cast<IntegerType>(DL->getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000341
342 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
343 if (isa<ConstantPointerNull>(V))
344 return ConstantInt::get(PtrTy, 0);
345
346 // IntToPtr const int.
347 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
348 if (CE->getOpcode() == Instruction::IntToPtr)
349 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
350 // The constant is very likely to have the right type already.
351 if (CI->getType() == PtrTy)
352 return CI;
353 else
354 return cast<ConstantInt>
355 (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
356 }
Craig Topperf40110f2014-04-25 05:29:35 +0000357 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000358}
359
Chris Lattner5a177e62010-12-13 04:26:26 +0000360/// GatherConstantCompares - Given a potentially 'or'd or 'and'd together
361/// collection of icmp eq/ne instructions that compare a value against a
362/// constant, return the value being compared, and stick the constant into the
363/// Values vector.
Chris Lattner11dafaa2010-12-13 03:30:12 +0000364static Value *
Chris Lattner5a177e62010-12-13 04:26:26 +0000365GatherConstantCompares(Value *V, std::vector<ConstantInt*> &Vals, Value *&Extra,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000366 const DataLayout *DL, bool isEQ, unsigned &UsedICmps) {
Chris Lattner5a177e62010-12-13 04:26:26 +0000367 Instruction *I = dyn_cast<Instruction>(V);
Craig Topperf40110f2014-04-25 05:29:35 +0000368 if (!I) return nullptr;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000369
Chris Lattnera442f242010-12-13 04:50:38 +0000370 // If this is an icmp against a constant, handle this as one of the cases.
Chris Lattner5a177e62010-12-13 04:26:26 +0000371 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000372 if (ConstantInt *C = GetConstantInt(I->getOperand(1), DL)) {
Benjamin Kramer37172222013-07-04 14:22:02 +0000373 Value *RHSVal;
374 ConstantInt *RHSC;
375
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000376 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
Benjamin Kramer37172222013-07-04 14:22:02 +0000377 // (x & ~2^x) == y --> x == y || x == y|2^x
378 // This undoes a transformation done by instcombine to fuse 2 compares.
379 if (match(ICI->getOperand(0),
380 m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
381 APInt Not = ~RHSC->getValue();
382 if (Not.isPowerOf2()) {
383 Vals.push_back(C);
384 Vals.push_back(
385 ConstantInt::get(C->getContext(), C->getValue() | Not));
386 UsedICmps++;
387 return RHSVal;
388 }
389 }
390
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000391 UsedICmps++;
Chris Lattner5a177e62010-12-13 04:26:26 +0000392 Vals.push_back(C);
393 return I->getOperand(0);
394 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000395
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000396 // If we have "x ult 3" comparison, for example, then we can add 0,1,2 to
397 // the set.
398 ConstantRange Span =
Chris Lattner6b8b4852010-12-18 20:22:49 +0000399 ConstantRange::makeICmpRegion(ICI->getPredicate(), C->getValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +0000400
Benjamin Kramer37172222013-07-04 14:22:02 +0000401 // Shift the range if the compare is fed by an add. This is the range
402 // compare idiom as emitted by instcombine.
403 bool hasAdd =
404 match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)));
405 if (hasAdd)
406 Span = Span.subtract(RHSC->getValue());
407
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000408 // If this is an and/!= check then we want to optimize "x ugt 2" into
409 // x != 0 && x != 1.
410 if (!isEQ)
411 Span = Span.inverse();
Andrew Trickf3cf1932012-08-29 21:46:36 +0000412
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000413 // If there are a ton of values, we don't want to make a ginormous switch.
Nick Lewycky219e6bc2012-01-19 18:19:42 +0000414 if (Span.getSetSize().ugt(8) || Span.isEmptySet())
Craig Topperf40110f2014-04-25 05:29:35 +0000415 return nullptr;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000416
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000417 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
418 Vals.push_back(ConstantInt::get(V->getContext(), Tmp));
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000419 UsedICmps++;
Benjamin Kramer37172222013-07-04 14:22:02 +0000420 return hasAdd ? RHSVal : I->getOperand(0);
Chris Lattnerd14b0f12010-12-17 06:20:15 +0000421 }
Craig Topperf40110f2014-04-25 05:29:35 +0000422 return nullptr;
Chris Lattner9b1af512010-12-13 04:18:32 +0000423 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000424
Chris Lattnera442f242010-12-13 04:50:38 +0000425 // Otherwise, we can only handle an | or &, depending on isEQ.
Chris Lattner5a177e62010-12-13 04:26:26 +0000426 if (I->getOpcode() != (isEQ ? Instruction::Or : Instruction::And))
Craig Topperf40110f2014-04-25 05:29:35 +0000427 return nullptr;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000428
Chris Lattnera442f242010-12-13 04:50:38 +0000429 unsigned NumValsBeforeLHS = Vals.size();
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000430 unsigned UsedICmpsBeforeLHS = UsedICmps;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000431 if (Value *LHS = GatherConstantCompares(I->getOperand(0), Vals, Extra, DL,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000432 isEQ, UsedICmps)) {
Chris Lattnera442f242010-12-13 04:50:38 +0000433 unsigned NumVals = Vals.size();
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000434 unsigned UsedICmpsBeforeRHS = UsedICmps;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000435 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000436 isEQ, UsedICmps)) {
Chris Lattner5a177e62010-12-13 04:26:26 +0000437 if (LHS == RHS)
438 return LHS;
Chris Lattner79db3572010-12-13 07:41:29 +0000439 Vals.resize(NumVals);
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000440 UsedICmps = UsedICmpsBeforeRHS;
Chris Lattner5a177e62010-12-13 04:26:26 +0000441 }
Chris Lattnera442f242010-12-13 04:50:38 +0000442
443 // The RHS of the or/and can't be folded in and we haven't used "Extra" yet,
444 // set it and return success.
Craig Topperf40110f2014-04-25 05:29:35 +0000445 if (Extra == nullptr || Extra == I->getOperand(1)) {
Chris Lattnera442f242010-12-13 04:50:38 +0000446 Extra = I->getOperand(1);
447 return LHS;
448 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000449
Chris Lattnera442f242010-12-13 04:50:38 +0000450 Vals.resize(NumValsBeforeLHS);
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000451 UsedICmps = UsedICmpsBeforeLHS;
Craig Topperf40110f2014-04-25 05:29:35 +0000452 return nullptr;
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000453 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000454
Chris Lattnera442f242010-12-13 04:50:38 +0000455 // If the LHS can't be folded in, but Extra is available and RHS can, try to
456 // use LHS as Extra.
Craig Topperf40110f2014-04-25 05:29:35 +0000457 if (Extra == nullptr || Extra == I->getOperand(0)) {
Chris Lattner79db3572010-12-13 07:41:29 +0000458 Value *OldExtra = Extra;
Chris Lattnera442f242010-12-13 04:50:38 +0000459 Extra = I->getOperand(0);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000460 if (Value *RHS = GatherConstantCompares(I->getOperand(1), Vals, Extra, DL,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +0000461 isEQ, UsedICmps))
Chris Lattnera442f242010-12-13 04:50:38 +0000462 return RHS;
Chris Lattner79db3572010-12-13 07:41:29 +0000463 assert(Vals.size() == NumValsBeforeLHS);
464 Extra = OldExtra;
Chris Lattnera442f242010-12-13 04:50:38 +0000465 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000466
Craig Topperf40110f2014-04-25 05:29:35 +0000467 return nullptr;
Chris Lattner6f4b45a2004-02-24 05:38:11 +0000468}
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000469
Eli Friedmancb61afb2008-12-16 20:54:32 +0000470static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000471 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000472 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
473 Cond = dyn_cast<Instruction>(SI->getCondition());
474 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
475 if (BI->isConditional())
476 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000477 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
478 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000479 }
480
481 TI->eraseFromParent();
482 if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
483}
484
Chris Lattner8e84c122008-11-27 23:25:44 +0000485/// isValueEqualityComparison - Return true if the specified terminator checks
486/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000487Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000488 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000489 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
490 // Do not permit merging of large switch instructions into their
491 // predecessors unless there is only one predecessor.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000492 if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
493 pred_end(SI->getParent())) <= 128)
494 CV = SI->getCondition();
495 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000496 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Reid Spencer266e42b2006-12-23 06:05:41 +0000497 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition()))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000498 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000499 CV = ICI->getOperand(0);
500
501 // Unwrap any lossless ptrtoint cast.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000502 if (DL && CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000503 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
504 Value *Ptr = PTII->getPointerOperand();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000505 if (PTII->getType() == DL->getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000506 CV = Ptr;
507 }
508 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000509 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000510}
511
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000512/// GetValueEqualityComparisonCases - Given a value comparison instruction,
513/// decode all of the 'cases' that it represents and return the 'default' block.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000514BasicBlock *SimplifyCFGOpt::
Misha Brukmanb1c93172005-04-21 23:48:37 +0000515GetValueEqualityComparisonCases(TerminatorInst *TI,
Eric Christopherb65acc62012-07-02 23:22:21 +0000516 std::vector<ValueEqualityComparisonCase>
517 &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000518 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000519 Cases.reserve(SI->getNumCases());
520 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
521 Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
522 i.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000523 return SI->getDefaultDest();
524 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000525
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000526 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000527 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000528 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
529 Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000530 DL),
Eric Christopherb65acc62012-07-02 23:22:21 +0000531 Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000532 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000533}
534
Eric Christopherb65acc62012-07-02 23:22:21 +0000535
536/// EliminateBlockCases - Given a vector of bb/value pairs, remove any entries
537/// in the list that match the specified block.
538static void EliminateBlockCases(BasicBlock *BB,
539 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000540 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000541}
542
543/// ValuesOverlap - Return true if there are any keys in C1 that exist in C2 as
544/// well.
545static bool
546ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
547 std::vector<ValueEqualityComparisonCase > &C2) {
548 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
549
550 // Make V1 be smaller than V2.
551 if (V1->size() > V2->size())
552 std::swap(V1, V2);
553
554 if (V1->size() == 0) return false;
555 if (V1->size() == 1) {
556 // Just scan V2.
557 ConstantInt *TheVal = (*V1)[0].Value;
558 for (unsigned i = 0, e = V2->size(); i != e; ++i)
559 if (TheVal == (*V2)[i].Value)
560 return true;
561 }
562
563 // Otherwise, just sort both lists and compare element by element.
564 array_pod_sort(V1->begin(), V1->end());
565 array_pod_sort(V2->begin(), V2->end());
566 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
567 while (i1 != e1 && i2 != e2) {
568 if ((*V1)[i1].Value == (*V2)[i2].Value)
569 return true;
570 if ((*V1)[i1].Value < (*V2)[i2].Value)
571 ++i1;
572 else
573 ++i2;
574 }
575 return false;
576}
577
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000578/// SimplifyEqualityComparisonWithOnlyPredecessor - If TI is known to be a
579/// terminator instruction and its block is known to only have a single
580/// predecessor block, check to see if that predecessor is also a value
581/// comparison with the same value, and if that comparison determines the
582/// outcome of this comparison. If so, simplify TI. This does a very limited
583/// form of jump threading.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000584bool SimplifyCFGOpt::
585SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000586 BasicBlock *Pred,
587 IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000588 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
589 if (!PredVal) return false; // Not a value comparison in predecessor.
590
591 Value *ThisVal = isValueEqualityComparison(TI);
592 assert(ThisVal && "This isn't a value comparison!!");
593 if (ThisVal != PredVal) return false; // Different predicates.
594
Andrew Trick3051aa12012-08-29 21:46:38 +0000595 // TODO: Preserve branch weight metadata, similarly to how
596 // FoldValueComparisonIntoPredecessors preserves it.
597
Chris Lattner1cca9592005-02-24 06:17:52 +0000598 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000599 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000600 BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
601 PredCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000602 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000603
Chris Lattner1cca9592005-02-24 06:17:52 +0000604 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000605 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000606 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Eric Christopherb65acc62012-07-02 23:22:21 +0000607 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000608
609 // If TI's block is the default block from Pred's comparison, potentially
610 // simplify TI based on this knowledge.
611 if (PredDef == TI->getParent()) {
612 // If we are here, we know that the value is none of those cases listed in
613 // PredCases. If there are any cases in ThisCases that are in PredCases, we
614 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000615 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000616 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000617
Chris Lattner4088e2b2010-12-13 01:47:07 +0000618 if (isa<BranchInst>(TI)) {
619 // Okay, one of the successors of this condbr is dead. Convert it to a
620 // uncond br.
621 assert(ThisCases.size() == 1 && "Branch can only have one case!");
622 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000623 Instruction *NI = Builder.CreateBr(ThisDef);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000624 (void) NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000625
Chris Lattner4088e2b2010-12-13 01:47:07 +0000626 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000627 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000628
Chris Lattner4088e2b2010-12-13 01:47:07 +0000629 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
630 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000631
Chris Lattner4088e2b2010-12-13 01:47:07 +0000632 EraseTerminatorInstAndDCECond(TI);
633 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000634 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000635
Chris Lattner4088e2b2010-12-13 01:47:07 +0000636 SwitchInst *SI = cast<SwitchInst>(TI);
637 // Okay, TI has cases that are statically dead, prune them away.
Eric Christopherb65acc62012-07-02 23:22:21 +0000638 SmallPtrSet<Constant*, 16> DeadCases;
639 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
640 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000641
David Greene725c7c32010-01-05 01:26:52 +0000642 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000643 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000644
Manman Ren8691e522012-09-14 21:53:06 +0000645 // Collect branch weights into a vector.
646 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000647 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000648 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
649 if (HasWeight)
650 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
651 ++MD_i) {
652 ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
653 assert(CI);
654 Weights.push_back(CI->getValue().getZExtValue());
655 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000656 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
657 --i;
658 if (DeadCases.count(i.getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000659 if (HasWeight) {
660 std::swap(Weights[i.getCaseIndex()+1], Weights.back());
661 Weights.pop_back();
662 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000663 i.getCaseSuccessor()->removePredecessor(TI->getParent());
664 SI->removeCase(i);
665 }
666 }
Manman Ren97c18762012-10-11 22:28:34 +0000667 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000668 SI->setMetadata(LLVMContext::MD_prof,
669 MDBuilder(SI->getParent()->getContext()).
670 createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000671
672 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000673 return true;
674 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000675
Chris Lattner4088e2b2010-12-13 01:47:07 +0000676 // Otherwise, TI's block must correspond to some matched value. Find out
677 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000678 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000679 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000680 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
681 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000682 if (TIV)
Eric Christopherb65acc62012-07-02 23:22:21 +0000683 return false; // Cannot handle multiple values coming to this block.
684 TIV = PredCases[i].Value;
685 }
686 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000687
688 // Okay, we found the one constant that our value can be if we get into TI's
689 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000690 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000691 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
692 if (ThisCases[i].Value == TIV) {
693 TheRealDest = ThisCases[i].Dest;
694 break;
695 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000696
697 // If not handled by any explicit cases, it is handled by the default case.
Craig Topperf40110f2014-04-25 05:29:35 +0000698 if (!TheRealDest) TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000699
700 // Remove PHI node entries for dead edges.
701 BasicBlock *CheckEdge = TheRealDest;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000702 for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
703 if (*SI != CheckEdge)
704 (*SI)->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000705 else
Craig Topperf40110f2014-04-25 05:29:35 +0000706 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000707
708 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000709 Instruction *NI = Builder.CreateBr(TheRealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000710 (void) NI;
711
712 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
713 << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
714
715 EraseTerminatorInstAndDCECond(TI);
716 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000717}
718
Dale Johannesen7f99d222009-03-12 21:01:11 +0000719namespace {
720 /// ConstantIntOrdering - This class implements a stable ordering of constant
721 /// integers that does not depend on their address. This is important for
722 /// applications that sort ConstantInt's to ensure uniqueness.
723 struct ConstantIntOrdering {
724 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
725 return LHS->getValue().ult(RHS->getValue());
726 }
727 };
728}
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000729
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000730static int ConstantIntSortPredicate(ConstantInt *const *P1,
731 ConstantInt *const *P2) {
732 const ConstantInt *LHS = *P1;
733 const ConstantInt *RHS = *P2;
Chris Lattnere893e262010-12-15 04:52:41 +0000734 if (LHS->getValue().ult(RHS->getValue()))
735 return 1;
736 if (LHS->getValue() == RHS->getValue())
737 return 0;
738 return -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000739}
740
Andrew Trick3051aa12012-08-29 21:46:38 +0000741static inline bool HasBranchWeights(const Instruction* I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000742 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000743 if (ProfMD && ProfMD->getOperand(0))
744 if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
745 return MDS->getString().equals("branch_weights");
746
747 return false;
748}
749
Manman Ren571d9e42012-09-11 17:43:35 +0000750/// Get Weights of a given TerminatorInst, the default weight is at the front
751/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
752/// metadata.
753static void GetBranchWeights(TerminatorInst *TI,
754 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000755 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000756 assert(MD);
757 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000758 ConstantInt *CI = cast<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000759 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000760 }
761
Manman Ren571d9e42012-09-11 17:43:35 +0000762 // If TI is a conditional eq, the default case is the false case,
763 // and the corresponding branch-weight data is at index 2. We swap the
764 // default weight to be the first entry.
765 if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
766 assert(Weights.size() == 2);
767 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
768 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
769 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000770 }
771}
772
Manman Renf1cb16e2014-01-27 23:39:03 +0000773/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000774static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000775 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
776 if (Max > UINT_MAX) {
777 unsigned Offset = 32 - countLeadingZeros(Max);
778 for (uint64_t &I : Weights)
779 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000780 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000781}
782
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000783/// FoldValueComparisonIntoPredecessors - The specified terminator is a value
784/// equality comparison instruction (either a switch or a branch on "X == c").
785/// See if any of the predecessors of the terminator block are value comparisons
786/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000787bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
788 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000789 BasicBlock *BB = TI->getParent();
790 Value *CV = isValueEqualityComparison(TI); // CondVal
791 assert(CV && "Not a comparison?");
792 bool Changed = false;
793
Chris Lattner6b39cb92008-02-18 07:42:56 +0000794 SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000795 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000796 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000797
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000798 // See if the predecessor is a comparison with the same value.
799 TerminatorInst *PTI = Pred->getTerminator();
800 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
801
802 if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
803 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000804 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000805 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
806
Eric Christopherb65acc62012-07-02 23:22:21 +0000807 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000808 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
809
810 // Based on whether the default edge from PTI goes to BB or not, fill in
811 // PredCases and PredDefault with the new switch cases we would like to
812 // build.
Chris Lattner6b39cb92008-02-18 07:42:56 +0000813 SmallVector<BasicBlock*, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000814
Andrew Trick3051aa12012-08-29 21:46:38 +0000815 // Update the branch weight metadata along the way
816 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +0000817 bool PredHasWeights = HasBranchWeights(PTI);
818 bool SuccHasWeights = HasBranchWeights(TI);
819
Manman Ren5e5049d2012-09-14 19:05:19 +0000820 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000821 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000822 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000823 if (Weights.size() != 1 + PredCases.size())
824 PredHasWeights = SuccHasWeights = false;
825 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +0000826 // If there are no predecessor weights but there are successor weights,
827 // populate Weights with 1, which will later be scaled to the sum of
828 // successor's weights
829 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000830
Manman Ren571d9e42012-09-11 17:43:35 +0000831 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +0000832 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +0000833 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +0000834 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +0000835 if (SuccWeights.size() != 1 + BBCases.size())
836 PredHasWeights = SuccHasWeights = false;
837 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +0000838 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +0000839
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000840 if (PredDefault == BB) {
841 // If this is the default destination from PTI, only the edges in TI
842 // that don't occur in PTI, or that branch to BB will be activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000843 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
844 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
845 if (PredCases[i].Dest != BB)
846 PTIHandled.insert(PredCases[i].Value);
847 else {
848 // The default destination is BB, we don't need explicit targets.
849 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000850
Manman Ren571d9e42012-09-11 17:43:35 +0000851 if (PredHasWeights || SuccHasWeights) {
852 // Increase weight for the default case.
853 Weights[0] += Weights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000854 std::swap(Weights[i+1], Weights.back());
855 Weights.pop_back();
856 }
857
Eric Christopherb65acc62012-07-02 23:22:21 +0000858 PredCases.pop_back();
859 --i; --e;
860 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000861
Eric Christopherb65acc62012-07-02 23:22:21 +0000862 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000863 if (PredDefault != BBDefault) {
864 PredDefault->removePredecessor(Pred);
865 PredDefault = BBDefault;
866 NewSuccessors.push_back(BBDefault);
867 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000868
Manman Ren571d9e42012-09-11 17:43:35 +0000869 unsigned CasesFromPred = Weights.size();
870 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +0000871 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
872 if (!PTIHandled.count(BBCases[i].Value) &&
873 BBCases[i].Dest != BBDefault) {
874 PredCases.push_back(BBCases[i]);
875 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +0000876 if (SuccHasWeights || PredHasWeights) {
877 // The default weight is at index 0, so weight for the ith case
878 // should be at index i+1. Scale the cases from successor by
879 // PredDefaultWeight (Weights[0]).
880 Weights.push_back(Weights[0] * SuccWeights[i+1]);
881 ValidTotalSuccWeight += SuccWeights[i+1];
Andrew Trick3051aa12012-08-29 21:46:38 +0000882 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000883 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000884
Manman Ren571d9e42012-09-11 17:43:35 +0000885 if (SuccHasWeights || PredHasWeights) {
886 ValidTotalSuccWeight += SuccWeights[0];
887 // Scale the cases from predecessor by ValidTotalSuccWeight.
888 for (unsigned i = 1; i < CasesFromPred; ++i)
889 Weights[i] *= ValidTotalSuccWeight;
890 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
891 Weights[0] *= SuccWeights[0];
892 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000893 } else {
894 // If this is not the default destination from PSI, only the edges
895 // in SI that occur in PSI with a destination of BB will be
896 // activated.
Eric Christopherb65acc62012-07-02 23:22:21 +0000897 std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
Manman Rend81b8e82012-09-14 17:29:56 +0000898 std::map<ConstantInt*, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +0000899 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
900 if (PredCases[i].Dest == BB) {
901 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +0000902
903 if (PredHasWeights || SuccHasWeights) {
904 WeightsForHandled[PredCases[i].Value] = Weights[i+1];
905 std::swap(Weights[i+1], Weights.back());
906 Weights.pop_back();
907 }
908
Eric Christopherb65acc62012-07-02 23:22:21 +0000909 std::swap(PredCases[i], PredCases.back());
910 PredCases.pop_back();
911 --i; --e;
912 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000913
914 // Okay, now we know which constants were sent to BB from the
915 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +0000916 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
917 if (PTIHandled.count(BBCases[i].Value)) {
918 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +0000919 if (PredHasWeights || SuccHasWeights)
920 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000921 PredCases.push_back(BBCases[i]);
922 NewSuccessors.push_back(BBCases[i].Dest);
923 PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
924 }
925
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000926 // If there are any constants vectored to BB that TI doesn't handle,
927 // they must go to the default destination of TI.
Andrew Trickf3cf1932012-08-29 21:46:36 +0000928 for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
Eric Christopherb65acc62012-07-02 23:22:21 +0000929 PTIHandled.begin(),
930 E = PTIHandled.end(); I != E; ++I) {
Andrew Trick90f50292012-11-15 18:40:29 +0000931 if (PredHasWeights || SuccHasWeights)
932 Weights.push_back(WeightsForHandled[*I]);
Eric Christopherb65acc62012-07-02 23:22:21 +0000933 PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000934 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +0000935 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000936 }
937
938 // Okay, at this point, we know which new successor Pred will get. Make
939 // sure we update the number of entries in the PHI nodes for these
940 // successors.
941 for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
942 AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
943
Devang Patel58380552011-05-18 20:53:17 +0000944 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000945 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +0000946 if (CV->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000947 assert(DL && "Cannot switch on pointer without DataLayout");
948 CV = Builder.CreatePtrToInt(CV, DL->getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +0000949 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000950 }
951
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000952 // Now that the successors are updated, create the new Switch instruction.
Devang Patel58380552011-05-18 20:53:17 +0000953 SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
954 PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +0000955 NewSI->setDebugLoc(PTI->getDebugLoc());
Eric Christopherb65acc62012-07-02 23:22:21 +0000956 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
957 NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +0000958
Andrew Trick3051aa12012-08-29 21:46:38 +0000959 if (PredHasWeights || SuccHasWeights) {
960 // Halve the weights if any of them cannot fit in an uint32_t
961 FitWeights(Weights);
962
963 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
964
965 NewSI->setMetadata(LLVMContext::MD_prof,
966 MDBuilder(BB->getContext()).
967 createBranchWeights(MDWeights));
968 }
969
Eli Friedmancb61afb2008-12-16 20:54:32 +0000970 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +0000971
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000972 // Okay, last check. If BB is still a successor of PSI, then we must
973 // have an infinite loop case. If so, add an infinitely looping block
974 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +0000975 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000976 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
977 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000978 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +0000979 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000980 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +0000981 InfLoopBlock = BasicBlock::Create(BB->getContext(),
982 "infloop", BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +0000983 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000984 }
985 NewSI->setSuccessor(i, InfLoopBlock);
986 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000987
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000988 Changed = true;
989 }
990 }
991 return Changed;
992}
993
Dale Johannesen9df78ee2009-06-15 20:59:27 +0000994// isSafeToHoistInvoke - If we would need to insert a select that uses the
995// value of this invoke (comments in HoistThenElseCodeToIf explain why we
996// would need to do this), we can't hoist the invoke, as there is nowhere
997// to put the select in this case.
998static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
999 Instruction *I1, Instruction *I2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001000 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001001 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001002 for (BasicBlock::iterator BBI = SI->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001003 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1004 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1005 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1006 if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
1007 return false;
1008 }
1009 }
1010 }
1011 return true;
1012}
1013
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001014static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1015
Chris Lattnerd683bdd2005-08-03 17:59:45 +00001016/// HoistThenElseCodeToIf - Given a conditional branch that goes to BB1 and
Chris Lattner389cfac2004-11-30 00:29:14 +00001017/// BB2, hoist any common code in the two blocks up into the branch block. The
1018/// caller of this function guarantees that BI's block dominates BB1 and BB2.
Hal Finkela995f922014-07-10 14:41:31 +00001019static bool HoistThenElseCodeToIf(BranchInst *BI, const DataLayout *DL) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001020 // This does very trivial matching, with limited scanning, to find identical
1021 // instructions in the two blocks. In particular, we don't want to get into
1022 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1023 // such, we currently just scan for obviously identical instructions in an
1024 // identical order.
1025 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1026 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
1027
Devang Patelf10e2872009-02-04 00:03:08 +00001028 BasicBlock::iterator BB1_Itr = BB1->begin();
1029 BasicBlock::iterator BB2_Itr = BB2->begin();
1030
1031 Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001032 // Skip debug info if it is not identical.
1033 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1034 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1035 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1036 while (isa<DbgInfoIntrinsic>(I1))
1037 I1 = BB1_Itr++;
1038 while (isa<DbgInfoIntrinsic>(I2))
1039 I2 = BB2_Itr++;
1040 }
Devang Patele48ddf82011-04-07 00:30:15 +00001041 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001042 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001043 return false;
1044
Chris Lattner389cfac2004-11-30 00:29:14 +00001045 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001046
David Majnemerc82f27a2013-06-03 20:43:12 +00001047 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001048 do {
1049 // If we are hoisting the terminator instruction, don't move one (making a
1050 // broken BB), instead clone it, and remove BI.
1051 if (isa<TerminatorInst>(I1))
1052 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001053
Chris Lattner389cfac2004-11-30 00:29:14 +00001054 // For a normal instruction, we just move one to right before the branch,
1055 // then replace all uses of the other with the first. Finally, we remove
1056 // the now redundant second instruction.
1057 BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
1058 if (!I2->use_empty())
1059 I2->replaceAllUsesWith(I1);
Dan Gohmanc8a27f22009-08-25 22:11:20 +00001060 I1->intersectOptionalDataWith(I2);
Rafael Espindolaea46c322014-08-15 15:46:38 +00001061 unsigned KnownIDs[] = {
1062 LLVMContext::MD_tbaa,
1063 LLVMContext::MD_range,
1064 LLVMContext::MD_fpmath,
Philip Reamesd92c2a72014-10-22 16:37:13 +00001065 LLVMContext::MD_invariant_load,
1066 LLVMContext::MD_nonnull
Rafael Espindolaea46c322014-08-15 15:46:38 +00001067 };
1068 combineMetadata(I1, I2, KnownIDs);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001069 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001070 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001071
Devang Patelf10e2872009-02-04 00:03:08 +00001072 I1 = BB1_Itr++;
Devang Patelf10e2872009-02-04 00:03:08 +00001073 I2 = BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001074 // Skip debug info if it is not identical.
1075 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1076 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1077 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1078 while (isa<DbgInfoIntrinsic>(I1))
1079 I1 = BB1_Itr++;
1080 while (isa<DbgInfoIntrinsic>(I2))
1081 I2 = BB2_Itr++;
1082 }
Devang Patele48ddf82011-04-07 00:30:15 +00001083 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001084
1085 return true;
1086
1087HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001088 // It may not be possible to hoist an invoke.
1089 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001090 return Changed;
1091
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001092 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001093 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001094 for (BasicBlock::iterator BBI = SI->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001095 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1096 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1097 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1098 if (BB1V == BB2V)
1099 continue;
1100
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001101 // Check for passingValueIsAlwaysUndefined here because we would rather
1102 // eliminate undefined control flow then converting it to a select.
1103 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1104 passingValueIsAlwaysUndefined(BB2V, PN))
1105 return Changed;
1106
Hal Finkela995f922014-07-10 14:41:31 +00001107 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V, DL))
David Majnemerc82f27a2013-06-03 20:43:12 +00001108 return Changed;
Hal Finkela995f922014-07-10 14:41:31 +00001109 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V, DL))
David Majnemerc82f27a2013-06-03 20:43:12 +00001110 return Changed;
1111 }
1112 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001113
Chris Lattner389cfac2004-11-30 00:29:14 +00001114 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001115 Instruction *NT = I1->clone();
Chris Lattner389cfac2004-11-30 00:29:14 +00001116 BIParent->getInstList().insert(BI, NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001117 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001118 I1->replaceAllUsesWith(NT);
1119 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001120 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001121 }
1122
Devang Patel1407fb42011-05-19 20:52:46 +00001123 IRBuilder<true, NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001124 // Hoisting one of the terminators from our successor is a great thing.
1125 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1126 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1127 // nodes, so we insert select instruction to compute the final result.
1128 std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001129 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001130 PHINode *PN;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001131 for (BasicBlock::iterator BBI = SI->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001132 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001133 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1134 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001135 if (BB1V == BB2V) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001136
Chris Lattner4088e2b2010-12-13 01:47:07 +00001137 // These values do not agree. Insert a select instruction before NT
1138 // that determines the right value.
1139 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001140 if (!SI)
Devang Patel1407fb42011-05-19 20:52:46 +00001141 SI = cast<SelectInst>
1142 (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1143 BB1V->getName()+"."+BB2V->getName()));
1144
Chris Lattner4088e2b2010-12-13 01:47:07 +00001145 // Make the PHI node use the select for all incoming values for BB1/BB2
1146 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1147 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1148 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001149 }
1150 }
1151
1152 // Update any PHI nodes in our new successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001153 for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
1154 AddPredecessorToBlock(*SI, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001155
Eli Friedmancb61afb2008-12-16 20:54:32 +00001156 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001157 return true;
1158}
1159
Manman Ren93ab6492012-09-20 22:37:36 +00001160/// SinkThenElseCodeToEnd - Given an unconditional branch that goes to BBEnd,
1161/// check whether BBEnd has only two predecessors and the other predecessor
1162/// ends with an unconditional branch. If it is true, sink any common code
1163/// in the two predecessors to BBEnd.
1164static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1165 assert(BI1->isUnconditional());
1166 BasicBlock *BB1 = BI1->getParent();
1167 BasicBlock *BBEnd = BI1->getSuccessor(0);
1168
1169 // Check that BBEnd has two predecessors and the other predecessor ends with
1170 // an unconditional branch.
Benjamin Kramerf064b652012-09-30 21:03:56 +00001171 pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
1172 BasicBlock *Pred0 = *PI++;
1173 if (PI == PE) // Only one predecessor.
Manman Ren93ab6492012-09-20 22:37:36 +00001174 return false;
Benjamin Kramerf064b652012-09-30 21:03:56 +00001175 BasicBlock *Pred1 = *PI++;
1176 if (PI != PE) // More than two predecessors.
1177 return false;
1178 BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
Manman Ren93ab6492012-09-20 22:37:36 +00001179 BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
1180 if (!BI2 || !BI2->isUnconditional())
1181 return false;
1182
1183 // Gather the PHI nodes in BBEnd.
1184 std::map<Value*, std::pair<Value*, PHINode*> > MapValueFromBB1ToBB2;
Craig Topperf40110f2014-04-25 05:29:35 +00001185 Instruction *FirstNonPhiInBBEnd = nullptr;
Manman Ren93ab6492012-09-20 22:37:36 +00001186 for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end();
1187 I != E; ++I) {
1188 if (PHINode *PN = dyn_cast<PHINode>(I)) {
1189 Value *BB1V = PN->getIncomingValueForBlock(BB1);
Andrew Trick90f50292012-11-15 18:40:29 +00001190 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Manman Ren93ab6492012-09-20 22:37:36 +00001191 MapValueFromBB1ToBB2[BB1V] = std::make_pair(BB2V, PN);
1192 } else {
1193 FirstNonPhiInBBEnd = &*I;
1194 break;
1195 }
1196 }
1197 if (!FirstNonPhiInBBEnd)
1198 return false;
Andrew Trick90f50292012-11-15 18:40:29 +00001199
Manman Ren93ab6492012-09-20 22:37:36 +00001200
1201 // This does very trivial matching, with limited scanning, to find identical
1202 // instructions in the two blocks. We scan backward for obviously identical
1203 // instructions in an identical order.
1204 BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
1205 RE1 = BB1->getInstList().rend(), RI2 = BB2->getInstList().rbegin(),
1206 RE2 = BB2->getInstList().rend();
1207 // Skip debug info.
1208 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1209 if (RI1 == RE1)
1210 return false;
1211 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1212 if (RI2 == RE2)
1213 return false;
1214 // Skip the unconditional branches.
1215 ++RI1;
1216 ++RI2;
1217
1218 bool Changed = false;
1219 while (RI1 != RE1 && RI2 != RE2) {
1220 // Skip debug info.
1221 while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
1222 if (RI1 == RE1)
1223 return Changed;
1224 while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
1225 if (RI2 == RE2)
1226 return Changed;
1227
1228 Instruction *I1 = &*RI1, *I2 = &*RI2;
1229 // I1 and I2 should have a single use in the same PHI node, and they
1230 // perform the same operation.
1231 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1232 if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
1233 isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
1234 isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
1235 isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
1236 I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
1237 I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
1238 !I1->hasOneUse() || !I2->hasOneUse() ||
1239 MapValueFromBB1ToBB2.find(I1) == MapValueFromBB1ToBB2.end() ||
1240 MapValueFromBB1ToBB2[I1].first != I2)
1241 return Changed;
1242
1243 // Check whether we should swap the operands of ICmpInst.
1244 ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
1245 bool SwapOpnds = false;
1246 if (ICmp1 && ICmp2 &&
1247 ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
1248 ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
1249 (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
1250 ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
1251 ICmp2->swapOperands();
1252 SwapOpnds = true;
1253 }
1254 if (!I1->isSameOperationAs(I2)) {
1255 if (SwapOpnds)
1256 ICmp2->swapOperands();
1257 return Changed;
1258 }
1259
1260 // The operands should be either the same or they need to be generated
1261 // with a PHI node after sinking. We only handle the case where there is
1262 // a single pair of different operands.
Craig Topperf40110f2014-04-25 05:29:35 +00001263 Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
Manman Ren93ab6492012-09-20 22:37:36 +00001264 unsigned Op1Idx = 0;
1265 for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
1266 if (I1->getOperand(I) == I2->getOperand(I))
1267 continue;
1268 // Early exit if we have more-than one pair of different operands or
1269 // the different operand is already in MapValueFromBB1ToBB2.
1270 // Early exit if we need a PHI node to replace a constant.
1271 if (DifferentOp1 ||
1272 MapValueFromBB1ToBB2.find(I1->getOperand(I)) !=
1273 MapValueFromBB1ToBB2.end() ||
1274 isa<Constant>(I1->getOperand(I)) ||
1275 isa<Constant>(I2->getOperand(I))) {
1276 // If we can't sink the instructions, undo the swapping.
1277 if (SwapOpnds)
1278 ICmp2->swapOperands();
1279 return Changed;
1280 }
1281 DifferentOp1 = I1->getOperand(I);
1282 Op1Idx = I;
1283 DifferentOp2 = I2->getOperand(I);
1284 }
1285
1286 // We insert the pair of different operands to MapValueFromBB1ToBB2 and
1287 // remove (I1, I2) from MapValueFromBB1ToBB2.
1288 if (DifferentOp1) {
1289 PHINode *NewPN = PHINode::Create(DifferentOp1->getType(), 2,
1290 DifferentOp1->getName() + ".sink",
1291 BBEnd->begin());
1292 MapValueFromBB1ToBB2[DifferentOp1] = std::make_pair(DifferentOp2, NewPN);
1293 // I1 should use NewPN instead of DifferentOp1.
1294 I1->setOperand(Op1Idx, NewPN);
1295 NewPN->addIncoming(DifferentOp1, BB1);
1296 NewPN->addIncoming(DifferentOp2, BB2);
1297 DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
1298 }
1299 PHINode *OldPN = MapValueFromBB1ToBB2[I1].second;
1300 MapValueFromBB1ToBB2.erase(I1);
1301
1302 DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n";);
1303 DEBUG(dbgs() << " " << *I2 << "\n";);
1304 // We need to update RE1 and RE2 if we are going to sink the first
1305 // instruction in the basic block down.
1306 bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
1307 // Sink the instruction.
1308 BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
1309 if (!OldPN->use_empty())
1310 OldPN->replaceAllUsesWith(I1);
1311 OldPN->eraseFromParent();
1312
1313 if (!I2->use_empty())
1314 I2->replaceAllUsesWith(I1);
1315 I1->intersectOptionalDataWith(I2);
Philip Reamesd92c2a72014-10-22 16:37:13 +00001316 // TODO: Use combineMetadata here to preserve what metadata we can
1317 // (analogous to the hoisting case above).
Manman Ren93ab6492012-09-20 22:37:36 +00001318 I2->eraseFromParent();
1319
1320 if (UpdateRE1)
1321 RE1 = BB1->getInstList().rend();
1322 if (UpdateRE2)
1323 RE2 = BB2->getInstList().rend();
1324 FirstNonPhiInBBEnd = I1;
1325 NumSinkCommons++;
1326 Changed = true;
1327 }
1328 return Changed;
1329}
1330
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001331/// \brief Determine if we can hoist sink a sole store instruction out of a
1332/// conditional block.
1333///
1334/// We are looking for code like the following:
1335/// BrBB:
1336/// store i32 %add, i32* %arrayidx2
1337/// ... // No other stores or function calls (we could be calling a memory
1338/// ... // function).
1339/// %cmp = icmp ult %x, %y
1340/// br i1 %cmp, label %EndBB, label %ThenBB
1341/// ThenBB:
1342/// store i32 %add5, i32* %arrayidx2
1343/// br label EndBB
1344/// EndBB:
1345/// ...
1346/// We are going to transform this into:
1347/// BrBB:
1348/// store i32 %add, i32* %arrayidx2
1349/// ... //
1350/// %cmp = icmp ult %x, %y
1351/// %add.add5 = select i1 %cmp, i32 %add, %add5
1352/// store i32 %add.add5, i32* %arrayidx2
1353/// ...
1354///
1355/// \return The pointer to the value of the previous store if the store can be
1356/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001357static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1358 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001359 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1360 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001361 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001362
1363 // Volatile or atomic.
1364 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001365 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001366
1367 Value *StorePtr = StoreToHoist->getPointerOperand();
1368
1369 // Look for a store to the same pointer in BrBB.
1370 unsigned MaxNumInstToLookAt = 10;
1371 for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
1372 RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
1373 Instruction *CurI = &*RI;
1374
1375 // Could be calling an instruction that effects memory like free().
1376 if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001377 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001378
1379 StoreInst *SI = dyn_cast<StoreInst>(CurI);
1380 // Found the previous store make sure it stores to the same location.
1381 if (SI && SI->getPointerOperand() == StorePtr)
1382 // Found the previous store, return its value operand.
1383 return SI->getValueOperand();
1384 else if (SI)
Craig Topperf40110f2014-04-25 05:29:35 +00001385 return nullptr; // Unknown store.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001386 }
1387
Craig Topperf40110f2014-04-25 05:29:35 +00001388 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001389}
1390
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001391/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001392///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001393/// Note that this is a very risky transform currently. Speculating
1394/// instructions like this is most often not desirable. Instead, there is an MI
1395/// pass which can do it with full awareness of the resource constraints.
1396/// However, some cases are "obvious" and we should do directly. An example of
1397/// this is speculating a single, reasonably cheap instruction.
1398///
1399/// There is only one distinct advantage to flattening the CFG at the IR level:
1400/// it makes very common but simplistic optimizations such as are common in
1401/// instcombine and the DAG combiner more powerful by removing CFG edges and
1402/// modeling their effects with easier to reason about SSA value graphs.
1403///
1404///
1405/// An illustration of this transform is turning this IR:
1406/// \code
1407/// BB:
1408/// %cmp = icmp ult %x, %y
1409/// br i1 %cmp, label %EndBB, label %ThenBB
1410/// ThenBB:
1411/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001412/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001413/// EndBB:
1414/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1415/// ...
1416/// \endcode
1417///
1418/// Into this IR:
1419/// \code
1420/// BB:
1421/// %cmp = icmp ult %x, %y
1422/// %sub = sub %x, %y
1423/// %cond = select i1 %cmp, 0, %sub
1424/// ...
1425/// \endcode
1426///
1427/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001428static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
1429 const DataLayout *DL) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001430 // Be conservative for now. FP select instruction can often be expensive.
1431 Value *BrCond = BI->getCondition();
1432 if (isa<FCmpInst>(BrCond))
1433 return false;
1434
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001435 BasicBlock *BB = BI->getParent();
1436 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1437
1438 // If ThenBB is actually on the false edge of the conditional branch, remember
1439 // to swap the select operands later.
1440 bool Invert = false;
1441 if (ThenBB != BI->getSuccessor(0)) {
1442 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1443 Invert = true;
1444 }
1445 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1446
Chandler Carruthceff2222013-01-25 05:40:09 +00001447 // Keep a count of how many times instructions are used within CondBB when
1448 // they are candidates for sinking into CondBB. Specifically:
1449 // - They are defined in BB, and
1450 // - They have no side effects, and
1451 // - All of their uses are in CondBB.
1452 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1453
Chandler Carruth7481ca82013-01-24 11:52:58 +00001454 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001455 Value *SpeculatedStoreValue = nullptr;
1456 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001457 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001458 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001459 BBI != BBE; ++BBI) {
1460 Instruction *I = BBI;
1461 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001462 if (isa<DbgInfoIntrinsic>(I))
1463 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001464
Chandler Carruth7481ca82013-01-24 11:52:58 +00001465 // Only speculatively execution a single instruction (not counting the
1466 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001467 ++SpeculationCost;
1468 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001469 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001470
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001471 // Don't hoist the instruction if it's unsafe or expensive.
Hal Finkela995f922014-07-10 14:41:31 +00001472 if (!isSafeToSpeculativelyExecute(I, DL) &&
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001473 !(HoistCondStores &&
1474 (SpeculatedStoreValue = isSafeToSpeculateStore(I, BB, ThenBB,
1475 EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001476 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001477 if (!SpeculatedStoreValue &&
Hal Finkela995f922014-07-10 14:41:31 +00001478 ComputeSpeculationCost(I, DL) > PHINodeFoldingThreshold)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001479 return false;
1480
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001481 // Store the store speculation candidate.
1482 if (SpeculatedStoreValue)
1483 SpeculatedStore = cast<StoreInst>(I);
1484
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001485 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001486 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001487 // being sunk into the use block.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001488 for (User::op_iterator i = I->op_begin(), e = I->op_end();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001489 i != e; ++i) {
1490 Instruction *OpI = dyn_cast<Instruction>(*i);
Chandler Carruthceff2222013-01-25 05:40:09 +00001491 if (!OpI || OpI->getParent() != BB ||
1492 OpI->mayHaveSideEffects())
1493 continue; // Not a candidate for sinking.
1494
1495 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001496 }
1497 }
Evan Cheng89200c92008-06-07 08:52:29 +00001498
Chandler Carruthceff2222013-01-25 05:40:09 +00001499 // Consider any sink candidates which are only used in CondBB as costs for
1500 // speculation. Note, while we iterate over a DenseMap here, we are summing
1501 // and so iteration order isn't significant.
1502 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
1503 SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
1504 I != E; ++I)
1505 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001506 ++SpeculationCost;
1507 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001508 return false;
1509 }
1510
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001511 // Check that the PHI nodes can be converted to selects.
1512 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001513 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001514 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001515 Value *OrigV = PN->getIncomingValueForBlock(BB);
1516 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001517
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001518 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001519 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001520 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001521 continue;
1522
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001523 // Don't convert to selects if we could remove undefined behavior instead.
1524 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1525 passingValueIsAlwaysUndefined(ThenV, PN))
1526 return false;
1527
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001528 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001529 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1530 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1531 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001532 continue; // Known safe and cheap.
1533
Hal Finkela995f922014-07-10 14:41:31 +00001534 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE, DL)) ||
1535 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE, DL)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001536 return false;
Hal Finkela995f922014-07-10 14:41:31 +00001537 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, DL) : 0;
1538 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, DL) : 0;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001539 if (OrigCost + ThenCost > 2 * PHINodeFoldingThreshold)
Chandler Carruth8a210052013-01-24 11:53:01 +00001540 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001541
Chandler Carruth01bffaa2013-01-24 12:05:17 +00001542 // Account for the cost of an unfolded ConstantExpr which could end up
1543 // getting expanded into Instructions.
1544 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00001545 // constant expression.
1546 ++SpeculationCost;
1547 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001548 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00001549 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001550
1551 // If there are no PHIs to process, bail early. This helps ensure idempotence
1552 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001553 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001554 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001555
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001556 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001557 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00001558
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001559 // Insert a select of the value of the speculated store.
1560 if (SpeculatedStoreValue) {
1561 IRBuilder<true, NoFolder> Builder(BI);
1562 Value *TrueV = SpeculatedStore->getValueOperand();
1563 Value *FalseV = SpeculatedStoreValue;
1564 if (Invert)
1565 std::swap(TrueV, FalseV);
1566 Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
1567 "." + FalseV->getName());
1568 SpeculatedStore->setOperand(0, S);
1569 }
1570
Chandler Carruth7481ca82013-01-24 11:52:58 +00001571 // Hoist the instructions.
1572 BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001573 std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00001574
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001575 // Insert selects and rewrite the PHI operands.
Devang Patel1407fb42011-05-19 20:52:46 +00001576 IRBuilder<true, NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001577 for (BasicBlock::iterator I = EndBB->begin();
1578 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1579 unsigned OrigI = PN->getBasicBlockIndex(BB);
1580 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
1581 Value *OrigV = PN->getIncomingValue(OrigI);
1582 Value *ThenV = PN->getIncomingValue(ThenI);
1583
1584 // Skip PHIs which are trivial.
1585 if (OrigV == ThenV)
1586 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00001587
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001588 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001589 // false value is the preexisting value. Swap them if the branch
1590 // destinations were inverted.
1591 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001592 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001593 std::swap(TrueV, FalseV);
1594 Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
1595 TrueV->getName() + "." + FalseV->getName());
1596 PN->setIncomingValue(OrigI, V);
1597 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00001598 }
1599
Evan Cheng89553cc2008-06-12 21:15:59 +00001600 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00001601 return true;
1602}
1603
Tom Stellarde1631dd2013-10-21 20:07:30 +00001604/// \returns True if this block contains a CallInst with the NoDuplicate
1605/// attribute.
1606static bool HasNoDuplicateCall(const BasicBlock *BB) {
1607 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1608 const CallInst *CI = dyn_cast<CallInst>(I);
1609 if (!CI)
1610 continue;
1611 if (CI->cannotDuplicate())
1612 return true;
1613 }
1614 return false;
1615}
1616
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001617/// BlockIsSimpleEnoughToThreadThrough - Return true if we can thread a branch
1618/// across this block.
1619static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
1620 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00001621 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001622
Devang Patel84fceff2009-03-10 18:00:05 +00001623 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00001624 if (isa<DbgInfoIntrinsic>(BBI))
1625 continue;
Chris Lattner6c701062005-09-20 01:48:40 +00001626 if (Size > 10) return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00001627 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001628
Dale Johannesened6f5a82009-03-12 23:18:09 +00001629 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00001630 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001631 for (User *U : BBI->users()) {
1632 Instruction *UI = cast<Instruction>(U);
1633 if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
Chris Lattner6c701062005-09-20 01:48:40 +00001634 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001635
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001636 // Looks ok, continue checking.
1637 }
Chris Lattner6c701062005-09-20 01:48:40 +00001638
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001639 return true;
1640}
1641
Chris Lattner748f9032005-09-19 23:49:37 +00001642/// FoldCondBranchOnPHI - If we have a conditional branch on a PHI node value
1643/// that is defined in the same block as the branch and if any PHI entries are
1644/// constants, thread edges corresponding to that entry to be branches to their
1645/// ultimate destination.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001646static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout *DL) {
Chris Lattner748f9032005-09-19 23:49:37 +00001647 BasicBlock *BB = BI->getParent();
1648 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00001649 // NOTE: we currently cannot transform this case if the PHI node is used
1650 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001651 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
1652 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001653
Chris Lattner748f9032005-09-19 23:49:37 +00001654 // Degenerate case of a single entry PHI.
1655 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00001656 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001657 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00001658 }
1659
1660 // Now we know that this block has multiple preds and two succs.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00001661 if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001662
Tom Stellarde1631dd2013-10-21 20:07:30 +00001663 if (HasNoDuplicateCall(BB)) return false;
1664
Chris Lattner748f9032005-09-19 23:49:37 +00001665 // Okay, this is a simple enough basic block. See if any phi values are
1666 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00001667 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00001668 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Craig Topperf40110f2014-04-25 05:29:35 +00001669 if (!CB || !CB->getType()->isIntegerTy(1)) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001670
Chris Lattner4088e2b2010-12-13 01:47:07 +00001671 // Okay, we now know that all edges from PredBB should be revectored to
1672 // branch to RealDest.
1673 BasicBlock *PredBB = PN->getIncomingBlock(i);
1674 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001675
Chris Lattner4088e2b2010-12-13 01:47:07 +00001676 if (RealDest == BB) continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00001677 // Skip if the predecessor's terminator is an indirect branch.
1678 if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001679
Chris Lattner4088e2b2010-12-13 01:47:07 +00001680 // The dest block might have PHI nodes, other predecessors and other
1681 // difficult cases. Instead of being smart about this, just insert a new
1682 // block that jumps to the destination block, effectively splitting
1683 // the edge we are about to create.
1684 BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
1685 RealDest->getName()+".critedge",
1686 RealDest->getParent(), RealDest);
1687 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001688
Chris Lattner0f4d67b2010-12-14 07:09:42 +00001689 // Update PHI nodes.
1690 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00001691
1692 // BB may have instructions that are being threaded over. Clone these
1693 // instructions into EdgeBB. We know that there will be no uses of the
1694 // cloned instructions outside of EdgeBB.
1695 BasicBlock::iterator InsertPt = EdgeBB->begin();
1696 DenseMap<Value*, Value*> TranslateMap; // Track translated values.
1697 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
1698 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
1699 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
1700 continue;
1701 }
1702 // Clone the instruction.
1703 Instruction *N = BBI->clone();
1704 if (BBI->hasName()) N->setName(BBI->getName()+".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001705
Chris Lattner4088e2b2010-12-13 01:47:07 +00001706 // Update operands due to translation.
1707 for (User::op_iterator i = N->op_begin(), e = N->op_end();
1708 i != e; ++i) {
1709 DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
1710 if (PI != TranslateMap.end())
1711 *i = PI->second;
1712 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001713
Chris Lattner4088e2b2010-12-13 01:47:07 +00001714 // Check for trivial simplification.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001715 if (Value *V = SimplifyInstruction(N, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00001716 TranslateMap[BBI] = V;
1717 delete N; // Instruction folded away, don't need actual inst
Chris Lattner4088e2b2010-12-13 01:47:07 +00001718 } else {
1719 // Insert the new instruction into its new home.
1720 EdgeBB->getInstList().insert(InsertPt, N);
1721 if (!BBI->use_empty())
1722 TranslateMap[BBI] = N;
1723 }
1724 }
1725
1726 // Loop over all of the edges from PredBB to BB, changing them to branch
1727 // to EdgeBB instead.
1728 TerminatorInst *PredBBTI = PredBB->getTerminator();
1729 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
1730 if (PredBBTI->getSuccessor(i) == BB) {
1731 BB->removePredecessor(PredBB);
1732 PredBBTI->setSuccessor(i, EdgeBB);
1733 }
Bill Wendling4f163df2011-06-04 09:42:04 +00001734
Chris Lattner4088e2b2010-12-13 01:47:07 +00001735 // Recurse, simplifying any other constants.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001736 return FoldCondBranchOnPHI(BI, DL) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00001737 }
Chris Lattner748f9032005-09-19 23:49:37 +00001738
1739 return false;
1740}
1741
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001742/// FoldTwoEntryPHINode - Given a BB that starts with the specified two-entry
1743/// PHI node, see if we can eliminate it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001744static bool FoldTwoEntryPHINode(PHINode *PN, const DataLayout *DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001745 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
1746 // statement", which has a very simple dominance structure. Basically, we
1747 // are trying to find the condition that is being branched on, which
1748 // subsequently causes this merge to happen. We really want control
1749 // dependence information for this check, but simplifycfg can't keep it up
1750 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001751 BasicBlock *BB = PN->getParent();
1752 BasicBlock *IfTrue, *IfFalse;
1753 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00001754 if (!IfCond ||
1755 // Don't bother if the branch will be constant folded trivially.
1756 isa<ConstantInt>(IfCond))
1757 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001758
Chris Lattner95adf8f12006-11-18 19:19:36 +00001759 // Okay, we found that we can merge this two-entry phi node into a select.
1760 // Doing so would require us to fold *all* two entry phi nodes in this block.
1761 // At some point this becomes non-profitable (particularly if the target
1762 // doesn't support cmov's). Only do this transformation if there are two or
1763 // fewer PHI nodes in this block.
1764 unsigned NumPhis = 0;
1765 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
1766 if (NumPhis > 2)
1767 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001768
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001769 // Loop over the PHI's seeing if we can promote them all to select
1770 // instructions. While we are at it, keep track of the instructions
1771 // that need to be moved to the dominating block.
Chris Lattner9ac168d2010-12-14 07:41:39 +00001772 SmallPtrSet<Instruction*, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00001773 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
1774 MaxCostVal1 = PHINodeFoldingThreshold;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001775
Chris Lattner7499b452010-12-14 08:46:09 +00001776 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
1777 PHINode *PN = cast<PHINode>(II++);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001778 if (Value *V = SimplifyInstruction(PN, DL)) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00001779 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00001780 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00001781 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001782 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001783
Peter Collingbournee3511e12011-04-29 18:47:31 +00001784 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +00001785 MaxCostVal0, DL) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00001786 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +00001787 MaxCostVal1, DL))
Chris Lattnerb42d2932010-12-14 07:20:29 +00001788 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001789 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001790
Sylvestre Ledru35521e22012-07-23 08:51:15 +00001791 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00001792 // we ran out of PHIs then we simplified them all.
1793 PN = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +00001794 if (!PN) return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001795
Chris Lattner7499b452010-12-14 08:46:09 +00001796 // Don't fold i1 branches on PHIs which contain binary operators. These can
1797 // often be turned into switches and other things.
1798 if (PN->getType()->isIntegerTy(1) &&
1799 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
1800 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
1801 isa<BinaryOperator>(IfCond)))
1802 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001803
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001804 // If we all PHI nodes are promotable, check to make sure that all
1805 // instructions in the predecessor blocks can be promoted as well. If
1806 // not, we won't be able to get rid of the control flow, so it's not
1807 // worth promoting to select instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00001808 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001809 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
1810 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
1811 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001812 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001813 } else {
1814 DomBlock = *pred_begin(IfBlock1);
1815 for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001816 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001817 // This is not an aggressive instruction that we can promote.
1818 // Because of this, we won't be able to get rid of the control
1819 // flow, so the xform is not worth it.
1820 return false;
1821 }
1822 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001823
Chris Lattner9ac168d2010-12-14 07:41:39 +00001824 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001825 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00001826 } else {
1827 DomBlock = *pred_begin(IfBlock2);
1828 for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
Devang Patel2032cad2009-02-03 22:12:02 +00001829 if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001830 // This is not an aggressive instruction that we can promote.
1831 // Because of this, we won't be able to get rid of the control
1832 // flow, so the xform is not worth it.
1833 return false;
1834 }
1835 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001836
Chris Lattner9fd838d2010-12-14 07:23:10 +00001837 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00001838 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00001839
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001840 // If we can still promote the PHI nodes after this gauntlet of tests,
1841 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00001842 Instruction *InsertPt = DomBlock->getTerminator();
Devang Patel1407fb42011-05-19 20:52:46 +00001843 IRBuilder<true, NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001844
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001845 // Move all 'aggressive' instructions, which are defined in the
1846 // conditional parts of the if's up to the dominating block.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001847 if (IfBlock1)
Chris Lattner7499b452010-12-14 08:46:09 +00001848 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001849 IfBlock1->getInstList(), IfBlock1->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001850 IfBlock1->getTerminator());
Chris Lattner4088e2b2010-12-13 01:47:07 +00001851 if (IfBlock2)
Chris Lattner7499b452010-12-14 08:46:09 +00001852 DomBlock->getInstList().splice(InsertPt,
Chris Lattner4088e2b2010-12-13 01:47:07 +00001853 IfBlock2->getInstList(), IfBlock2->begin(),
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001854 IfBlock2->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001855
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001856 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
1857 // Change the PHI node into a select instruction.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001858 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
1859 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001860
1861 SelectInst *NV =
Devang Patel5c810ce2011-05-18 18:16:44 +00001862 cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001863 PN->replaceAllUsesWith(NV);
1864 NV->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00001865 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001866 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001867
Chris Lattner335f0e42010-12-14 08:01:53 +00001868 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
1869 // has been flattened. Change DomBlock to jump directly to our new block to
1870 // avoid other simplifycfg's kicking in on the diamond.
1871 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00001872 Builder.SetInsertPoint(OldTI);
1873 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00001874 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00001875 return true;
1876}
Chris Lattner748f9032005-09-19 23:49:37 +00001877
Chris Lattner86bbf332008-04-24 00:01:19 +00001878/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
1879/// to two returning blocks, try to merge them together into one return,
1880/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00001881static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00001882 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001883 assert(BI->isConditional() && "Must be a conditional branch");
1884 BasicBlock *TrueSucc = BI->getSuccessor(0);
1885 BasicBlock *FalseSucc = BI->getSuccessor(1);
1886 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
1887 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001888
Chris Lattner86bbf332008-04-24 00:01:19 +00001889 // Check to ensure both blocks are empty (just a return) or optionally empty
1890 // with PHI nodes. If there are other instructions, merging would cause extra
1891 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00001892 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001893 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00001894 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00001895 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00001896
Devang Pateldd14e0f2011-05-18 21:33:11 +00001897 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001898 // Okay, we found a branch that is going to two return nodes. If
1899 // there is no return value for this function, just change the
1900 // branch into a return.
1901 if (FalseRet->getNumOperands() == 0) {
1902 TrueSucc->removePredecessor(BI->getParent());
1903 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00001904 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00001905 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00001906 return true;
1907 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00001908
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001909 // Otherwise, figure out what the true and false return values are
1910 // so we can insert a new select instruction.
1911 Value *TrueValue = TrueRet->getReturnValue();
1912 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00001913
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001914 // Unwrap any PHI nodes in the return blocks.
1915 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
1916 if (TVPN->getParent() == TrueSucc)
1917 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
1918 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
1919 if (FVPN->getParent() == FalseSucc)
1920 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001921
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001922 // In order for this transformation to be safe, we must be able to
1923 // unconditionally execute both operands to the return. This is
1924 // normally the case, but we could have a potentially-trapping
1925 // constant expression that prevents this transformation from being
1926 // safe.
1927 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
1928 if (TCV->canTrap())
1929 return false;
1930 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
1931 if (FCV->canTrap())
1932 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001933
Chris Lattner86bbf332008-04-24 00:01:19 +00001934 // Okay, we collected all the mapped values and checked them for sanity, and
1935 // defined to really do this transformation. First, update the CFG.
1936 TrueSucc->removePredecessor(BI->getParent());
1937 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00001938
Chris Lattner86bbf332008-04-24 00:01:19 +00001939 // Insert select instructions where needed.
1940 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001941 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00001942 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00001943 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
1944 } else if (isa<UndefValue>(TrueValue)) {
1945 TrueValue = FalseValue;
1946 } else {
Devang Pateldd14e0f2011-05-18 21:33:11 +00001947 TrueValue = Builder.CreateSelect(BrCond, TrueValue,
1948 FalseValue, "retval");
Chris Lattner86bbf332008-04-24 00:01:19 +00001949 }
Chris Lattner86bbf332008-04-24 00:01:19 +00001950 }
1951
Andrew Trickf3cf1932012-08-29 21:46:36 +00001952 Value *RI = !TrueValue ?
Devang Pateldd14e0f2011-05-18 21:33:11 +00001953 Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
1954
Daniel Dunbar5e0a58b2009-08-23 10:29:55 +00001955 (void) RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001956
David Greene725c7c32010-01-05 01:26:52 +00001957 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00001958 << "\n " << *BI << "NewRet = " << *RI
1959 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00001960
Eli Friedmancb61afb2008-12-16 20:54:32 +00001961 EraseTerminatorInstAndDCECond(BI);
1962
Chris Lattner86bbf332008-04-24 00:01:19 +00001963 return true;
1964}
1965
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00001966/// ExtractBranchMetadata - Given a conditional BranchInstruction, retrieve the
1967/// probabilities of the branch taking each edge. Fills in the two APInt
1968/// parameters and return true, or returns false if no or invalid metadata was
1969/// found.
1970static bool ExtractBranchMetadata(BranchInst *BI,
Manman Renbfb9d432012-09-15 00:39:57 +00001971 uint64_t &ProbTrue, uint64_t &ProbFalse) {
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00001972 assert(BI->isConditional() &&
1973 "Looking for probabilities on unconditional branch?");
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +00001974 MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
Nick Lewycky398255e2011-12-27 18:27:22 +00001975 if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00001976 ConstantInt *CITrue = dyn_cast<ConstantInt>(ProfileData->getOperand(1));
1977 ConstantInt *CIFalse = dyn_cast<ConstantInt>(ProfileData->getOperand(2));
Nick Lewycky398255e2011-12-27 18:27:22 +00001978 if (!CITrue || !CIFalse) return false;
Manman Renbfb9d432012-09-15 00:39:57 +00001979 ProbTrue = CITrue->getValue().getZExtValue();
1980 ProbFalse = CIFalse->getValue().getZExtValue();
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00001981 return true;
1982}
1983
Manman Rend33f4ef2012-06-13 05:43:29 +00001984/// checkCSEInPredecessor - Return true if the given instruction is available
1985/// in its predecessor block. If yes, the instruction will be removed.
1986///
Benjamin Kramerabbfe692012-07-13 13:25:15 +00001987static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00001988 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
1989 return false;
1990 for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
1991 Instruction *PBI = &*I;
1992 // Check whether Inst and PBI generate the same value.
1993 if (Inst->isIdenticalTo(PBI)) {
1994 Inst->replaceAllUsesWith(PBI);
1995 Inst->eraseFromParent();
1996 return true;
1997 }
1998 }
1999 return false;
2000}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002001
Chris Lattner7d4cdae2011-04-11 23:24:57 +00002002/// FoldBranchToCommonDest - If this basic block is simple enough, and if a
2003/// predecessor branches to us and one of our successors, fold the block into
2004/// the predecessor and use logical operations to pick the right destination.
Jingyue Wufc029672014-09-30 22:23:38 +00002005bool llvm::FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL,
2006 unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002007 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002008
Craig Topperf40110f2014-04-25 05:29:35 +00002009 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002010 if (BI->isConditional())
2011 Cond = dyn_cast<Instruction>(BI->getCondition());
2012 else {
2013 // For unconditional branch, check for a simple CFG pattern, where
2014 // BB has a single predecessor and BB's successor is also its predecessor's
2015 // successor. If such pattern exisits, check for CSE between BB and its
2016 // predecessor.
2017 if (BasicBlock *PB = BB->getSinglePredecessor())
2018 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2019 if (PBI->isConditional() &&
2020 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2021 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
2022 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
2023 I != E; ) {
2024 Instruction *Curr = I++;
2025 if (isa<CmpInst>(Curr)) {
2026 Cond = Curr;
2027 break;
2028 }
2029 // Quit if we can't remove this instruction.
2030 if (!checkCSEInPredecessor(Curr, PB))
2031 return false;
2032 }
2033 }
2034
Craig Topperf40110f2014-04-25 05:29:35 +00002035 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002036 return false;
2037 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002038
Craig Topperf40110f2014-04-25 05:29:35 +00002039 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2040 Cond->getParent() != BB || !Cond->hasOneUse())
Owen Anderson2cfe9132010-07-14 19:52:16 +00002041 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002042
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002043 // Make sure the instruction after the condition is the cond branch.
2044 BasicBlock::iterator CondIt = Cond; ++CondIt;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002045
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002046 // Ignore dbg intrinsics.
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002047 while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002048
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002049 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002050 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002051
Jingyue Wufc029672014-09-30 22:23:38 +00002052 // Only allow this transformation if computing the condition doesn't involve
2053 // too many instructions and these involved instructions can be executed
2054 // unconditionally. We denote all involved instructions except the condition
2055 // as "bonus instructions", and only allow this transformation when the
2056 // number of the bonus instructions does not exceed a certain threshold.
2057 unsigned NumBonusInsts = 0;
2058 for (auto I = BB->begin(); Cond != I; ++I) {
2059 // Ignore dbg intrinsics.
2060 if (isa<DbgInfoIntrinsic>(I))
2061 continue;
2062 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I, DL))
2063 return false;
2064 // I has only one use and can be executed unconditionally.
2065 Instruction *User = dyn_cast<Instruction>(I->user_back());
2066 if (User == nullptr || User->getParent() != BB)
2067 return false;
2068 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2069 // to use any other instruction, User must be an instruction between next(I)
2070 // and Cond.
2071 ++NumBonusInsts;
2072 // Early exits once we reach the limit.
2073 if (NumBonusInsts > BonusInstThreshold)
2074 return false;
2075 }
2076
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002077 // Cond is known to be a compare or binary operator. Check to make sure that
2078 // neither operand is a potentially-trapping constant expression.
2079 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2080 if (CE->canTrap())
2081 return false;
2082 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2083 if (CE->canTrap())
2084 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002085
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002086 // Finally, don't infinitely unroll conditional loops.
2087 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002088 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002089 if (TrueDest == BB || FalseDest == BB)
2090 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002091
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002092 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2093 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002094 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002095
Chris Lattner80b03a12008-07-13 22:23:11 +00002096 // Check that we have two conditional branches. If there is a PHI node in
2097 // the common successor, verify that the same value flows in from both
2098 // blocks.
Manman Rend33f4ef2012-06-13 05:43:29 +00002099 SmallVector<PHINode*, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002100 if (!PBI || PBI->isUnconditional() ||
Andrew Trickf3cf1932012-08-29 21:46:36 +00002101 (BI->isConditional() &&
Manman Rend33f4ef2012-06-13 05:43:29 +00002102 !SafeToMergeTerminators(BI, PBI)) ||
2103 (!BI->isConditional() &&
2104 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002105 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002106
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002107 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002108 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002109 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002110
Manman Rend33f4ef2012-06-13 05:43:29 +00002111 if (BI->isConditional()) {
2112 if (PBI->getSuccessor(0) == TrueDest)
2113 Opc = Instruction::Or;
2114 else if (PBI->getSuccessor(1) == FalseDest)
2115 Opc = Instruction::And;
2116 else if (PBI->getSuccessor(0) == FalseDest)
2117 Opc = Instruction::And, InvertPredCond = true;
2118 else if (PBI->getSuccessor(1) == TrueDest)
2119 Opc = Instruction::Or, InvertPredCond = true;
2120 else
2121 continue;
2122 } else {
2123 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2124 continue;
2125 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002126
David Greene725c7c32010-01-05 01:26:52 +00002127 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002128 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002129
Chris Lattner55eaae12008-07-13 21:20:19 +00002130 // If we need to invert the condition in the pred block to match, do so now.
2131 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002132 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002133
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002134 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2135 CmpInst *CI = cast<CmpInst>(NewCond);
2136 CI->setPredicate(CI->getInversePredicate());
2137 } else {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002138 NewCond = Builder.CreateNot(NewCond,
Devang Patel1407fb42011-05-19 20:52:46 +00002139 PBI->getCondition()->getName()+".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002140 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002141
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002142 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002143 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002144 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002145
Jingyue Wufc029672014-09-30 22:23:38 +00002146 // If we have bonus instructions, clone them into the predecessor block.
2147 // Note that there may be mutliple predecessor blocks, so we cannot move
2148 // bonus instructions to a predecessor block.
2149 ValueToValueMapTy VMap; // maps original values to cloned values
2150 // We already make sure Cond is the last instruction before BI. Therefore,
2151 // every instructions before Cond other than DbgInfoIntrinsic are bonus
2152 // instructions.
2153 for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
2154 if (isa<DbgInfoIntrinsic>(BonusInst))
2155 continue;
2156 Instruction *NewBonusInst = BonusInst->clone();
2157 RemapInstruction(NewBonusInst, VMap,
2158 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
2159 VMap[BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002160
2161 // If we moved a load, we cannot any longer claim any knowledge about
2162 // its potential value. The previous information might have been valid
2163 // only given the branch precondition.
2164 // For an analogous reason, we must also drop all the metadata whose
2165 // semantics we don't understand.
Jingyue Wufc029672014-09-30 22:23:38 +00002166 NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
Rafael Espindolaab73c492014-01-28 16:56:46 +00002167
Jingyue Wufc029672014-09-30 22:23:38 +00002168 PredBlock->getInstList().insert(PBI, NewBonusInst);
2169 NewBonusInst->takeName(BonusInst);
2170 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002171 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002172
Chris Lattner55eaae12008-07-13 21:20:19 +00002173 // Clone Cond into the predecessor basic block, and or/and the
2174 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002175 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002176 RemapInstruction(New, VMap,
2177 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
Chris Lattner55eaae12008-07-13 21:20:19 +00002178 PredBlock->getInstList().insert(PBI, New);
2179 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002180 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002181
Manman Rend33f4ef2012-06-13 05:43:29 +00002182 if (BI->isConditional()) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00002183 Instruction *NewCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002184 cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
Devang Patel1407fb42011-05-19 20:52:46 +00002185 New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002186 PBI->setCondition(NewCond);
2187
Manman Renbfb9d432012-09-15 00:39:57 +00002188 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2189 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2190 PredFalseWeight);
2191 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2192 SuccFalseWeight);
2193 SmallVector<uint64_t, 8> NewWeights;
2194
Manman Rend33f4ef2012-06-13 05:43:29 +00002195 if (PBI->getSuccessor(0) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002196 if (PredHasWeights && SuccHasWeights) {
2197 // PBI: br i1 %x, BB, FalseDest
2198 // BI: br i1 %y, TrueDest, FalseDest
2199 //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
2200 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
2201 //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
2202 // TrueWeight for PBI * FalseWeight for BI.
2203 // We assume that total weights of a BranchInst can fit into 32 bits.
2204 // Therefore, we will not have overflow using 64-bit arithmetic.
2205 NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
2206 SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
2207 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002208 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2209 PBI->setSuccessor(0, TrueDest);
2210 }
2211 if (PBI->getSuccessor(1) == BB) {
Manman Renbfb9d432012-09-15 00:39:57 +00002212 if (PredHasWeights && SuccHasWeights) {
2213 // PBI: br i1 %x, TrueDest, BB
2214 // BI: br i1 %y, TrueDest, FalseDest
2215 //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
2216 // FalseWeight for PBI * TrueWeight for BI.
2217 NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
2218 SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
2219 //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
2220 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2221 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002222 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2223 PBI->setSuccessor(1, FalseDest);
2224 }
Manman Renbfb9d432012-09-15 00:39:57 +00002225 if (NewWeights.size() == 2) {
2226 // Halve the weights if any of them cannot fit in an uint32_t
2227 FitWeights(NewWeights);
2228
2229 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
2230 PBI->setMetadata(LLVMContext::MD_prof,
2231 MDBuilder(BI->getContext()).
2232 createBranchWeights(MDWeights));
2233 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002234 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002235 } else {
2236 // Update PHI nodes in the common successors.
2237 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002238 ConstantInt *PBI_C = cast<ConstantInt>(
Manman Rend33f4ef2012-06-13 05:43:29 +00002239 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
2240 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002241 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002242 if (PBI->getSuccessor(0) == TrueDest) {
2243 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2244 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2245 // is false: !PBI_Cond and BI_Value
2246 Instruction *NotCond =
2247 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2248 "not.cond"));
2249 MergedCond =
2250 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2251 NotCond, New,
2252 "and.cond"));
2253 if (PBI_C->isOne())
2254 MergedCond =
2255 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2256 PBI->getCondition(), MergedCond,
2257 "or.cond"));
2258 } else {
2259 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2260 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2261 // is false: PBI_Cond and BI_Value
Andrew Trickf3cf1932012-08-29 21:46:36 +00002262 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002263 cast<Instruction>(Builder.CreateBinOp(Instruction::And,
2264 PBI->getCondition(), New,
2265 "and.cond"));
2266 if (PBI_C->isOne()) {
2267 Instruction *NotCond =
2268 cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
2269 "not.cond"));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002270 MergedCond =
Manman Rend33f4ef2012-06-13 05:43:29 +00002271 cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
2272 NotCond, MergedCond,
2273 "or.cond"));
2274 }
2275 }
2276 // Update PHI Node.
2277 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2278 MergedCond);
2279 }
2280 // Change PBI from Conditional to Unconditional.
2281 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2282 EraseTerminatorInstAndDCECond(PBI);
2283 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002284 }
Devang Pateld715ec82011-04-06 22:37:20 +00002285
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002286 // TODO: If BB is reachable from all paths through PredBlock, then we
2287 // could replace PBI's branch probabilities with BI's.
2288
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002289 // Copy any debug value intrinsics into the end of PredBlock.
2290 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
2291 if (isa<DbgInfoIntrinsic>(*I))
2292 I->clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002293
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002294 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002295 }
2296 return false;
2297}
2298
Chris Lattner9aada1d2008-07-13 21:53:26 +00002299/// SimplifyCondBranchToCondBranch - If we have a conditional branch as a
2300/// predecessor of another block, this function tries to simplify it. We know
2301/// that PBI and BI are both conditional branches, and BI is in one of the
2302/// successor blocks of PBI - PBI branches to BI.
2303static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
2304 assert(PBI->isConditional() && BI->isConditional());
2305 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00002306
Chris Lattner9aada1d2008-07-13 21:53:26 +00002307 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00002308 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00002309 // this conditional branch redundant.
2310 if (PBI->getCondition() == BI->getCondition() &&
2311 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2312 // Okay, the outcome of this conditional branch is statically
2313 // knowable. If this block had a single pred, handle specially.
2314 if (BB->getSinglePredecessor()) {
2315 // Turn this into a branch on constant.
2316 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002317 BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Owen Anderson55f1c092009-08-13 21:58:54 +00002318 CondIsTrue));
Chris Lattner9aada1d2008-07-13 21:53:26 +00002319 return true; // Nuke the branch on constant.
2320 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002321
Chris Lattner9aada1d2008-07-13 21:53:26 +00002322 // Otherwise, if there are multiple predecessors, insert a PHI that merges
2323 // in the constant and simplify the block result. Subsequent passes of
2324 // simplifycfg will thread the block.
2325 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00002326 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Owen Anderson55f1c092009-08-13 21:58:54 +00002327 PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
Jay Foad52131342011-03-30 11:28:46 +00002328 std::distance(PB, PE),
Chris Lattner9aada1d2008-07-13 21:53:26 +00002329 BI->getCondition()->getName() + ".pr",
2330 BB->begin());
Chris Lattner5eed3722008-07-13 21:55:46 +00002331 // Okay, we're going to insert the PHI node. Since PBI is not the only
2332 // predecessor, compute the PHI'd conditional value for all of the preds.
2333 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00002334 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00002335 BasicBlock *P = *PI;
2336 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00002337 PBI != BI && PBI->isConditional() &&
2338 PBI->getCondition() == BI->getCondition() &&
2339 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
2340 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002341 NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
Gabor Greif8629f122010-07-12 10:59:23 +00002342 CondIsTrue), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002343 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00002344 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002345 }
Gabor Greif8629f122010-07-12 10:59:23 +00002346 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002347
Chris Lattner9aada1d2008-07-13 21:53:26 +00002348 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002349 return true;
2350 }
2351 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002352
Chris Lattner9aada1d2008-07-13 21:53:26 +00002353 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002354 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00002355 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00002356 BasicBlock::iterator BBI = BB->begin();
2357 // Ignore dbg intrinsics.
2358 while (isa<DbgInfoIntrinsic>(BBI))
2359 ++BBI;
2360 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00002361 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00002362
Andrew Trickf3cf1932012-08-29 21:46:36 +00002363
Chris Lattnerc59945b2009-01-20 01:15:41 +00002364 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
2365 if (CE->canTrap())
2366 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002367
Chris Lattner834ab4e2008-07-13 22:04:41 +00002368 int PBIOp, BIOp;
2369 if (PBI->getSuccessor(0) == BI->getSuccessor(0))
2370 PBIOp = BIOp = 0;
2371 else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
2372 PBIOp = 0, BIOp = 1;
2373 else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
2374 PBIOp = 1, BIOp = 0;
2375 else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
2376 PBIOp = BIOp = 1;
2377 else
2378 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002379
Chris Lattner834ab4e2008-07-13 22:04:41 +00002380 // Check to make sure that the other destination of this branch
2381 // isn't BB itself. If so, this is an infinite loop that will
2382 // keep getting unwound.
2383 if (PBI->getSuccessor(PBIOp) == BB)
2384 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002385
2386 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00002387 // insertion of a large number of select instructions. For targets
2388 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002389
Sanjay Patela932da82014-07-07 21:19:00 +00002390 // Also do not perform this transformation if any phi node in the common
2391 // destination block can trap when reached by BB or PBB (PR17073). In that
2392 // case, it would be unsafe to hoist the operation into a select instruction.
2393
2394 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002395 unsigned NumPhis = 0;
2396 for (BasicBlock::iterator II = CommonDest->begin();
Sanjay Patela932da82014-07-07 21:19:00 +00002397 isa<PHINode>(II); ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00002398 if (NumPhis > 2) // Disable this xform.
2399 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002400
Sanjay Patela932da82014-07-07 21:19:00 +00002401 PHINode *PN = cast<PHINode>(II);
2402 Value *BIV = PN->getIncomingValueForBlock(BB);
2403 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
2404 if (CE->canTrap())
2405 return false;
2406
2407 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2408 Value *PBIV = PN->getIncomingValue(PBBIdx);
2409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
2410 if (CE->canTrap())
2411 return false;
2412 }
2413
Chris Lattner834ab4e2008-07-13 22:04:41 +00002414 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00002415 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002416
David Greene725c7c32010-01-05 01:26:52 +00002417 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002418 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002419
2420
Chris Lattner80b03a12008-07-13 22:23:11 +00002421 // If OtherDest *is* BB, then BB is a basic block with a single conditional
2422 // branch in it, where one edge (OtherDest) goes back to itself but the other
2423 // exits. We don't *know* that the program avoids the infinite loop
2424 // (even though that seems likely). If we do this xform naively, we'll end up
2425 // recursively unpeeling the loop. Since we know that (after the xform is
2426 // done) that the block *is* infinite if reached, we just make it an obviously
2427 // infinite loop with no cond branch.
2428 if (OtherDest == BB) {
2429 // Insert it at the end of the function, because it's either code,
2430 // or it won't matter if it's hot. :)
Owen Anderson55f1c092009-08-13 21:58:54 +00002431 BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
2432 "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00002433 BranchInst::Create(InfLoopBlock, InfLoopBlock);
2434 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002435 }
2436
David Greene725c7c32010-01-05 01:26:52 +00002437 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00002438
Chris Lattner834ab4e2008-07-13 22:04:41 +00002439 // BI may have other predecessors. Because of this, we leave
2440 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002441
Chris Lattner834ab4e2008-07-13 22:04:41 +00002442 // Make sure we get to CommonDest on True&True directions.
2443 Value *PBICond = PBI->getCondition();
Devang Patel1407fb42011-05-19 20:52:46 +00002444 IRBuilder<true, NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00002445 if (PBIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002446 PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
2447
Chris Lattner834ab4e2008-07-13 22:04:41 +00002448 Value *BICond = BI->getCondition();
2449 if (BIOp)
Devang Patel1407fb42011-05-19 20:52:46 +00002450 BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
2451
Chris Lattner834ab4e2008-07-13 22:04:41 +00002452 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00002453 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002454
Chris Lattner834ab4e2008-07-13 22:04:41 +00002455 // Modify PBI to branch on the new condition to the new dests.
2456 PBI->setCondition(Cond);
2457 PBI->setSuccessor(0, CommonDest);
2458 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002459
Manman Ren2d4c10f2012-09-17 21:30:40 +00002460 // Update branch weight for PBI.
2461 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
2462 bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
2463 PredFalseWeight);
2464 bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
2465 SuccFalseWeight);
2466 if (PredHasWeights && SuccHasWeights) {
2467 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
2468 uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
2469 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
2470 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
2471 // The weight to CommonDest should be PredCommon * SuccTotal +
2472 // PredOther * SuccCommon.
2473 // The weight to OtherDest should be PredOther * SuccOther.
2474 SmallVector<uint64_t, 2> NewWeights;
2475 NewWeights.push_back(PredCommon * (SuccCommon + SuccOther) +
2476 PredOther * SuccCommon);
2477 NewWeights.push_back(PredOther * SuccOther);
2478 // Halve the weights if any of them cannot fit in an uint32_t
2479 FitWeights(NewWeights);
2480
2481 SmallVector<uint32_t, 2> MDWeights(NewWeights.begin(),NewWeights.end());
2482 PBI->setMetadata(LLVMContext::MD_prof,
2483 MDBuilder(BI->getContext()).
2484 createBranchWeights(MDWeights));
2485 }
2486
Chris Lattner834ab4e2008-07-13 22:04:41 +00002487 // OtherDest may have phi nodes. If so, add an entry from PBI's
2488 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002489 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002490
Chris Lattner834ab4e2008-07-13 22:04:41 +00002491 // We know that the CommonDest already had an edge from PBI to
2492 // it. If it has PHIs though, the PHIs may have different
2493 // entries for BB and PBI's BB. If so, insert a select to make
2494 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002495 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00002496 for (BasicBlock::iterator II = CommonDest->begin();
2497 (PN = dyn_cast<PHINode>(II)); ++II) {
2498 Value *BIV = PN->getIncomingValueForBlock(BB);
2499 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
2500 Value *PBIV = PN->getIncomingValue(PBBIdx);
2501 if (BIV != PBIV) {
2502 // Insert a select in PBI to pick the right value.
Devang Patel1407fb42011-05-19 20:52:46 +00002503 Value *NV = cast<SelectInst>
2504 (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00002505 PN->setIncomingValue(PBBIdx, NV);
Chris Lattner9aada1d2008-07-13 21:53:26 +00002506 }
2507 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002508
David Greene725c7c32010-01-05 01:26:52 +00002509 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
2510 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002511
Chris Lattner834ab4e2008-07-13 22:04:41 +00002512 // This basic block is probably dead. We know it has at least
2513 // one fewer predecessor.
2514 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00002515}
2516
Frits van Bommel8e158492011-01-11 12:52:11 +00002517// SimplifyTerminatorOnSelect - Simplifies a terminator by replacing it with a
2518// branch to TrueBB if Cond is true or to FalseBB if Cond is false.
2519// Takes care of updating the successors and removing the old terminator.
2520// Also makes sure not to introduce new successors by assuming that edges to
2521// non-successor TrueBBs and FalseBBs aren't reachable.
2522static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00002523 BasicBlock *TrueBB, BasicBlock *FalseBB,
2524 uint32_t TrueWeight,
2525 uint32_t FalseWeight){
Frits van Bommel8e158492011-01-11 12:52:11 +00002526 // Remove any superfluous successor edges from the CFG.
2527 // First, figure out which successors to preserve.
2528 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
2529 // successor.
2530 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00002531 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002532
2533 // Then remove the rest.
2534 for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
2535 BasicBlock *Succ = OldTerm->getSuccessor(I);
2536 // Make sure only to keep exactly one copy of each edge.
2537 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00002538 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002539 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00002540 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00002541 else
2542 Succ->removePredecessor(OldTerm->getParent());
2543 }
2544
Devang Patel2c2ea222011-05-18 18:43:31 +00002545 IRBuilder<> Builder(OldTerm);
2546 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
2547
Frits van Bommel8e158492011-01-11 12:52:11 +00002548 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00002549 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00002550 if (TrueBB == FalseBB)
2551 // We were only looking for one successor, and it was present.
2552 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00002553 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00002554 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00002555 // We found both of the successors we were looking for.
2556 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00002557 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
2558 if (TrueWeight != FalseWeight)
2559 NewBI->setMetadata(LLVMContext::MD_prof,
2560 MDBuilder(OldTerm->getContext()).
2561 createBranchWeights(TrueWeight, FalseWeight));
2562 }
Frits van Bommel8e158492011-01-11 12:52:11 +00002563 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
2564 // Neither of the selected blocks were successors, so this
2565 // terminator must be unreachable.
2566 new UnreachableInst(OldTerm->getContext(), OldTerm);
2567 } else {
2568 // One of the selected values was a successor, but the other wasn't.
2569 // Insert an unconditional branch to the one that was found;
2570 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00002571 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00002572 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002573 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002574 else
2575 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00002576 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00002577 }
2578
2579 EraseTerminatorInstAndDCECond(OldTerm);
2580 return true;
2581}
2582
Frits van Bommel8ae07992011-02-28 09:44:07 +00002583// SimplifySwitchOnSelect - Replaces
2584// (switch (select cond, X, Y)) on constant X, Y
2585// with a branch - conditional if X and Y lead to distinct BBs,
2586// unconditional otherwise.
2587static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
2588 // Check for constant integer values in the select.
2589 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
2590 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
2591 if (!TrueVal || !FalseVal)
2592 return false;
2593
2594 // Find the relevant condition and destinations.
2595 Value *Condition = Select->getCondition();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002596 BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
2597 BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00002598
Manman Ren774246a2012-09-17 22:28:55 +00002599 // Get weight for TrueBB and FalseBB.
2600 uint32_t TrueWeight = 0, FalseWeight = 0;
2601 SmallVector<uint64_t, 8> Weights;
2602 bool HasWeights = HasBranchWeights(SI);
2603 if (HasWeights) {
2604 GetBranchWeights(SI, Weights);
2605 if (Weights.size() == 1 + SI->getNumCases()) {
2606 TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
2607 getSuccessorIndex()];
2608 FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
2609 getSuccessorIndex()];
2610 }
2611 }
2612
Frits van Bommel8ae07992011-02-28 09:44:07 +00002613 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002614 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
2615 TrueWeight, FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00002616}
2617
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002618// SimplifyIndirectBrOnSelect - Replaces
2619// (indirectbr (select cond, blockaddress(@fn, BlockA),
2620// blockaddress(@fn, BlockB)))
2621// with
2622// (br cond, BlockA, BlockB).
2623static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
2624 // Check that both operands of the select are block addresses.
2625 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
2626 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
2627 if (!TBA || !FBA)
2628 return false;
2629
2630 // Extract the actual blocks.
2631 BasicBlock *TrueBB = TBA->getBasicBlock();
2632 BasicBlock *FalseBB = FBA->getBasicBlock();
2633
Frits van Bommel8e158492011-01-11 12:52:11 +00002634 // Perform the actual simplification.
Manman Ren774246a2012-09-17 22:28:55 +00002635 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
2636 0, 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00002637}
2638
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002639/// TryToSimplifyUncondBranchWithICmpInIt - This is called when we find an icmp
2640/// instruction (a seteq/setne with a constant) as the only instruction in a
2641/// block that ends with an uncond branch. We are looking for a very specific
2642/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
2643/// this case, we merge the first two "or's of icmp" into a switch, but then the
2644/// default value goes to an uncond block with a seteq in it, we get something
2645/// like:
2646///
2647/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
2648/// DEFAULT:
2649/// %tmp = icmp eq i8 %A, 92
2650/// br label %end
2651/// end:
2652/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00002653///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002654/// We prefer to split the edge to 'end' so that there is a true/false entry to
2655/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00002656static bool TryToSimplifyUncondBranchWithICmpInIt(
2657 ICmpInst *ICI, IRBuilder<> &Builder, const TargetTransformInfo &TTI,
Jingyue Wufc029672014-09-30 22:23:38 +00002658 unsigned BonusInstThreshold, const DataLayout *DL, AssumptionTracker *AT) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002659 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00002660
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002661 // If the block has any PHIs in it or the icmp has multiple uses, it is too
2662 // complex.
2663 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
2664
2665 Value *V = ICI->getOperand(0);
2666 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00002667
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002668 // The pattern we're looking for is where our only predecessor is a switch on
2669 // 'V' and this block is the default case for the switch. In this case we can
2670 // fold the compared value into the switch to simplify things.
2671 BasicBlock *Pred = BB->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +00002672 if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002673
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002674 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
2675 if (SI->getCondition() != V)
2676 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002677
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002678 // If BB is reachable on a non-default case, then we simply know the value of
2679 // V in this block. Substitute it and constant fold the icmp instruction
2680 // away.
2681 if (SI->getDefaultDest() != BB) {
2682 ConstantInt *VVal = SI->findCaseDest(BB);
2683 assert(VVal && "Should have a unique destination value");
2684 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002685
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002686 if (Value *V = SimplifyInstruction(ICI, DL)) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00002687 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002688 ICI->eraseFromParent();
2689 }
2690 // BB is now empty, so it is likely to simplify away.
Jingyue Wufc029672014-09-30 22:23:38 +00002691 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002692 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002693
Chris Lattner62cc76e2010-12-13 03:43:57 +00002694 // Ok, the block is reachable from the default dest. If the constant we're
2695 // comparing exists in one of the other edges, then we can constant fold ICI
2696 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002697 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00002698 Value *V;
2699 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2700 V = ConstantInt::getFalse(BB->getContext());
2701 else
2702 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002703
Chris Lattner62cc76e2010-12-13 03:43:57 +00002704 ICI->replaceAllUsesWith(V);
2705 ICI->eraseFromParent();
2706 // BB is now empty, so it is likely to simplify away.
Jingyue Wufc029672014-09-30 22:23:38 +00002707 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00002708 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002709
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002710 // The use of the icmp has to be in the 'end' block, by the only PHI node in
2711 // the block.
2712 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00002713 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00002714 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002715 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
2716 return false;
2717
2718 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
2719 // true in the PHI.
2720 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
2721 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
2722
2723 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
2724 std::swap(DefaultCst, NewCst);
2725
2726 // Replace ICI (which is used by the PHI for the default value) with true or
2727 // false depending on if it is EQ or NE.
2728 ICI->replaceAllUsesWith(DefaultCst);
2729 ICI->eraseFromParent();
2730
2731 // Okay, the switch goes to this block on a default value. Add an edge from
2732 // the switch to the merge point on the compared value.
2733 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
2734 BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00002735 SmallVector<uint64_t, 8> Weights;
2736 bool HasWeights = HasBranchWeights(SI);
2737 if (HasWeights) {
2738 GetBranchWeights(SI, Weights);
2739 if (Weights.size() == 1 + SI->getNumCases()) {
2740 // Split weight for default case to case for "Cst".
2741 Weights[0] = (Weights[0]+1) >> 1;
2742 Weights.push_back(Weights[0]);
2743
2744 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
2745 SI->setMetadata(LLVMContext::MD_prof,
2746 MDBuilder(SI->getContext()).
2747 createBranchWeights(MDWeights));
2748 }
2749 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002750 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002751
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002752 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00002753 Builder.SetInsertPoint(NewBB);
2754 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
2755 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00002756 PHIUse->addIncoming(NewCst, NewBB);
2757 return true;
2758}
2759
Chris Lattnera69c4432010-12-13 05:03:41 +00002760/// SimplifyBranchOnICmpChain - The specified branch is a conditional branch.
2761/// Check to see if it is branching on an or/and chain of icmp instructions, and
2762/// fold it into a switch instruction if so.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002763static bool SimplifyBranchOnICmpChain(BranchInst *BI, const DataLayout *DL,
Devang Patel7de6c4b2011-05-18 23:18:47 +00002764 IRBuilder<> &Builder) {
Chris Lattnera69c4432010-12-13 05:03:41 +00002765 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Craig Topperf40110f2014-04-25 05:29:35 +00002766 if (!Cond) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002767
2768
Chris Lattnera69c4432010-12-13 05:03:41 +00002769 // Change br (X == 0 | X == 1), T, F into a switch instruction.
2770 // If this is a bunch of seteq's or'd together, or if it's a bunch of
2771 // 'setne's and'ed together, collect them.
Craig Topperf40110f2014-04-25 05:29:35 +00002772 Value *CompVal = nullptr;
Chris Lattnera69c4432010-12-13 05:03:41 +00002773 std::vector<ConstantInt*> Values;
2774 bool TrueWhenEqual = true;
Craig Topperf40110f2014-04-25 05:29:35 +00002775 Value *ExtraCase = nullptr;
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002776 unsigned UsedICmps = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002777
Chris Lattnera69c4432010-12-13 05:03:41 +00002778 if (Cond->getOpcode() == Instruction::Or) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002779 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, true,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002780 UsedICmps);
Chris Lattnera69c4432010-12-13 05:03:41 +00002781 } else if (Cond->getOpcode() == Instruction::And) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002782 CompVal = GatherConstantCompares(Cond, Values, ExtraCase, DL, false,
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002783 UsedICmps);
Chris Lattnera69c4432010-12-13 05:03:41 +00002784 TrueWhenEqual = false;
2785 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002786
Chris Lattnera69c4432010-12-13 05:03:41 +00002787 // If we didn't have a multiply compared value, fail.
Craig Topperf40110f2014-04-25 05:29:35 +00002788 if (!CompVal) return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00002789
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00002790 // Avoid turning single icmps into a switch.
2791 if (UsedICmps <= 1)
2792 return false;
2793
Chris Lattnera69c4432010-12-13 05:03:41 +00002794 // There might be duplicate constants in the list, which the switch
2795 // instruction can't handle, remove them now.
2796 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
2797 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002798
Chris Lattnera69c4432010-12-13 05:03:41 +00002799 // If Extra was used, we require at least two switch values to do the
2800 // transformation. A switch with one value is just an cond branch.
2801 if (ExtraCase && Values.size() < 2) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002802
Andrew Trick3051aa12012-08-29 21:46:38 +00002803 // TODO: Preserve branch weight metadata, similarly to how
2804 // FoldValueComparisonIntoPredecessors preserves it.
2805
Chris Lattnera69c4432010-12-13 05:03:41 +00002806 // Figure out which block is which destination.
2807 BasicBlock *DefaultBB = BI->getSuccessor(1);
2808 BasicBlock *EdgeBB = BI->getSuccessor(0);
2809 if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002810
Chris Lattnera69c4432010-12-13 05:03:41 +00002811 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002812
Chris Lattnerd7beca32010-12-14 06:17:25 +00002813 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002814 << " cases into SWITCH. BB is:\n" << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002815
Chris Lattnera69c4432010-12-13 05:03:41 +00002816 // If there are any extra values that couldn't be folded into the switch
2817 // then we evaluate them with an explicit branch first. Split the block
2818 // right before the condbr to handle it.
2819 if (ExtraCase) {
2820 BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
2821 // Remove the uncond branch added to the old block.
2822 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00002823 Builder.SetInsertPoint(OldTI);
2824
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002825 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00002826 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002827 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00002828 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002829
Chris Lattnera69c4432010-12-13 05:03:41 +00002830 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002831
Chris Lattnercb570f82010-12-13 05:34:18 +00002832 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
2833 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002834 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002835
Chris Lattnerd7beca32010-12-14 06:17:25 +00002836 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
2837 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00002838 BB = NewBB;
2839 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00002840
2841 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00002842 // Convert pointer to int before we switch.
2843 if (CompVal->getType()->isPointerTy()) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002844 assert(DL && "Cannot switch on pointer without DataLayout");
Devang Patel7de6c4b2011-05-18 23:18:47 +00002845 CompVal = Builder.CreatePtrToInt(CompVal,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002846 DL->getIntPtrType(CompVal->getType()),
Devang Patel7de6c4b2011-05-18 23:18:47 +00002847 "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00002848 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002849
Chris Lattnera69c4432010-12-13 05:03:41 +00002850 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00002851 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00002852
Chris Lattnera69c4432010-12-13 05:03:41 +00002853 // Add all of the 'cases' to the switch instruction.
2854 for (unsigned i = 0, e = Values.size(); i != e; ++i)
2855 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002856
Chris Lattnera69c4432010-12-13 05:03:41 +00002857 // We added edges from PI to the EdgeBB. As such, if there were any
2858 // PHI nodes in EdgeBB, they need entries to be added corresponding to
2859 // the number of edges added.
2860 for (BasicBlock::iterator BBI = EdgeBB->begin();
2861 isa<PHINode>(BBI); ++BBI) {
2862 PHINode *PN = cast<PHINode>(BBI);
2863 Value *InVal = PN->getIncomingValueForBlock(BB);
2864 for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
2865 PN->addIncoming(InVal, BB);
2866 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002867
Chris Lattnera69c4432010-12-13 05:03:41 +00002868 // Erase the old branch instruction.
2869 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002870
Chris Lattnerd7beca32010-12-14 06:17:25 +00002871 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00002872 return true;
2873}
2874
Duncan Sands29192d02011-09-05 12:57:57 +00002875bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
2876 // If this is a trivial landing pad that just continues unwinding the caught
2877 // exception then zap the landing pad, turning its invokes into calls.
2878 BasicBlock *BB = RI->getParent();
2879 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
2880 if (RI->getValue() != LPInst)
2881 // Not a landing pad, or the resume is not unwinding the exception that
2882 // caused control to branch here.
2883 return false;
2884
2885 // Check that there are no other instructions except for debug intrinsics.
2886 BasicBlock::iterator I = LPInst, E = RI;
2887 while (++I != E)
2888 if (!isa<DbgInfoIntrinsic>(I))
2889 return false;
2890
2891 // Turn all invokes that unwind here into calls and delete the basic block.
Bill Wendling9534d882013-03-11 20:53:00 +00002892 bool InvokeRequiresTableEntry = false;
2893 bool Changed = false;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002894 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
2895 InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
Bill Wendling9534d882013-03-11 20:53:00 +00002896
2897 if (II->hasFnAttr(Attribute::UWTable)) {
2898 // Don't remove an `invoke' instruction if the ABI requires an entry into
2899 // the table.
2900 InvokeRequiresTableEntry = true;
2901 continue;
2902 }
2903
Duncan Sands29192d02011-09-05 12:57:57 +00002904 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
Bill Wendling9534d882013-03-11 20:53:00 +00002905
Duncan Sands29192d02011-09-05 12:57:57 +00002906 // Insert a call instruction before the invoke.
2907 CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
2908 Call->takeName(II);
2909 Call->setCallingConv(II->getCallingConv());
2910 Call->setAttributes(II->getAttributes());
2911 Call->setDebugLoc(II->getDebugLoc());
2912
2913 // Anything that used the value produced by the invoke instruction now uses
2914 // the value produced by the call instruction. Note that we do this even
2915 // for void functions and calls with no uses so that the callgraph edge is
2916 // updated.
2917 II->replaceAllUsesWith(Call);
2918 BB->removePredecessor(II->getParent());
2919
2920 // Insert a branch to the normal destination right before the invoke.
2921 BranchInst::Create(II->getNormalDest(), II);
2922
2923 // Finally, delete the invoke instruction!
2924 II->eraseFromParent();
Bill Wendling9534d882013-03-11 20:53:00 +00002925 Changed = true;
Duncan Sands29192d02011-09-05 12:57:57 +00002926 }
2927
Bill Wendling9534d882013-03-11 20:53:00 +00002928 if (!InvokeRequiresTableEntry)
2929 // The landingpad is now unreachable. Zap it.
2930 BB->eraseFromParent();
2931
2932 return Changed;
Duncan Sands29192d02011-09-05 12:57:57 +00002933}
2934
Devang Pateldd14e0f2011-05-18 21:33:11 +00002935bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002936 BasicBlock *BB = RI->getParent();
2937 if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002938
Chris Lattner25c3af32010-12-13 06:25:44 +00002939 // Find predecessors that end with branches.
2940 SmallVector<BasicBlock*, 8> UncondBranchPreds;
2941 SmallVector<BranchInst*, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002942 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2943 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00002944 TerminatorInst *PTI = P->getTerminator();
2945 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
2946 if (BI->isUnconditional())
2947 UncondBranchPreds.push_back(P);
2948 else
2949 CondBranchPreds.push_back(BI);
2950 }
2951 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002952
Chris Lattner25c3af32010-12-13 06:25:44 +00002953 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00002954 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00002955 while (!UncondBranchPreds.empty()) {
2956 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
2957 DEBUG(dbgs() << "FOLDING: " << *BB
2958 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00002959 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00002960 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002961
Chris Lattner25c3af32010-12-13 06:25:44 +00002962 // If we eliminated all predecessors of the block, delete the block now.
2963 if (pred_begin(BB) == pred_end(BB))
2964 // We know there are no successors, so just nuke the block.
2965 BB->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002966
Chris Lattner25c3af32010-12-13 06:25:44 +00002967 return true;
2968 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002969
Chris Lattner25c3af32010-12-13 06:25:44 +00002970 // Check out all of the conditional branches going to this return
2971 // instruction. If any of them just select between returns, change the
2972 // branch itself into a select/return pair.
2973 while (!CondBranchPreds.empty()) {
2974 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002975
Chris Lattner25c3af32010-12-13 06:25:44 +00002976 // Check to see if the non-BB successor is also a return block.
2977 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
2978 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00002979 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00002980 return true;
2981 }
2982 return false;
2983}
2984
Chris Lattner25c3af32010-12-13 06:25:44 +00002985bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
2986 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002987
Chris Lattner25c3af32010-12-13 06:25:44 +00002988 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002989
Chris Lattner25c3af32010-12-13 06:25:44 +00002990 // If there are any instructions immediately before the unreachable that can
2991 // be removed, do so.
2992 while (UI != BB->begin()) {
2993 BasicBlock::iterator BBI = UI;
2994 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00002995 // Do not delete instructions that can have side effects which might cause
2996 // the unreachable to not be reachable; specifically, calls and volatile
2997 // operations may have this effect.
Chris Lattner25c3af32010-12-13 06:25:44 +00002998 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00002999
3000 if (BBI->mayHaveSideEffects()) {
3001 if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
3002 if (SI->isVolatile())
3003 break;
3004 } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3005 if (LI->isVolatile())
3006 break;
3007 } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
3008 if (RMWI->isVolatile())
3009 break;
3010 } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
3011 if (CXI->isVolatile())
3012 break;
3013 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
3014 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003015 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003016 }
Bill Wendling55d875f2011-08-16 20:41:17 +00003017 // Note that deleting LandingPad's here is in fact okay, although it
3018 // involves a bit of subtle reasoning. If this inst is a LandingPad,
3019 // all the predecessors of this block will be the unwind edges of Invokes,
3020 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00003021 }
3022
Eli Friedmanaac35b32011-03-09 00:48:33 +00003023 // Delete this instruction (any uses are guaranteed to be dead)
3024 if (!BBI->use_empty())
3025 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00003026 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00003027 Changed = true;
3028 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003029
Chris Lattner25c3af32010-12-13 06:25:44 +00003030 // If the unreachable instruction is the first in the block, take a gander
3031 // at all of the predecessors of this instruction, and simplify them.
3032 if (&BB->front() != UI) return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003033
Chris Lattner25c3af32010-12-13 06:25:44 +00003034 SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
3035 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
3036 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00003037 IRBuilder<> Builder(TI);
Chris Lattner25c3af32010-12-13 06:25:44 +00003038 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3039 if (BI->isUnconditional()) {
3040 if (BI->getSuccessor(0) == BB) {
3041 new UnreachableInst(TI->getContext(), TI);
3042 TI->eraseFromParent();
3043 Changed = true;
3044 }
3045 } else {
3046 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003047 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00003048 EraseTerminatorInstAndDCECond(BI);
3049 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00003050 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00003051 EraseTerminatorInstAndDCECond(BI);
3052 Changed = true;
3053 }
3054 }
3055 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003056 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003057 i != e; ++i)
3058 if (i.getCaseSuccessor() == BB) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003059 BB->removePredecessor(SI->getParent());
3060 SI->removeCase(i);
3061 --i; --e;
3062 Changed = true;
3063 }
3064 // If the default value is unreachable, figure out the most popular
3065 // destination and make it the default.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003066 if (SI->getDefaultDest() == BB) {
Eli Friedmanc4414c62011-03-15 02:23:35 +00003067 std::map<BasicBlock*, std::pair<unsigned, unsigned> > Popularity;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003068 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003069 i != e; ++i) {
Nick Lewyckye87d54c2011-12-26 20:37:40 +00003070 std::pair<unsigned, unsigned> &entry =
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003071 Popularity[i.getCaseSuccessor()];
Eli Friedmanc4414c62011-03-15 02:23:35 +00003072 if (entry.first == 0) {
3073 entry.first = 1;
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003074 entry.second = i.getCaseIndex();
Eli Friedmanc4414c62011-03-15 02:23:35 +00003075 } else {
3076 entry.first++;
3077 }
3078 }
3079
Chris Lattner25c3af32010-12-13 06:25:44 +00003080 // Find the most popular block.
3081 unsigned MaxPop = 0;
Eli Friedmanc4414c62011-03-15 02:23:35 +00003082 unsigned MaxIndex = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00003083 BasicBlock *MaxBlock = nullptr;
Eli Friedmanc4414c62011-03-15 02:23:35 +00003084 for (std::map<BasicBlock*, std::pair<unsigned, unsigned> >::iterator
Chris Lattner25c3af32010-12-13 06:25:44 +00003085 I = Popularity.begin(), E = Popularity.end(); I != E; ++I) {
Andrew Trickf3cf1932012-08-29 21:46:36 +00003086 if (I->second.first > MaxPop ||
Eli Friedmanc4414c62011-03-15 02:23:35 +00003087 (I->second.first == MaxPop && MaxIndex > I->second.second)) {
3088 MaxPop = I->second.first;
3089 MaxIndex = I->second.second;
Chris Lattner25c3af32010-12-13 06:25:44 +00003090 MaxBlock = I->first;
3091 }
3092 }
3093 if (MaxBlock) {
3094 // Make this the new default, allowing us to delete any explicit
3095 // edges to it.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003096 SI->setDefaultDest(MaxBlock);
Chris Lattner25c3af32010-12-13 06:25:44 +00003097 Changed = true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003098
Chris Lattner25c3af32010-12-13 06:25:44 +00003099 // If MaxBlock has phinodes in it, remove MaxPop-1 entries from
3100 // it.
3101 if (isa<PHINode>(MaxBlock->begin()))
3102 for (unsigned i = 0; i != MaxPop-1; ++i)
3103 MaxBlock->removePredecessor(SI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003104
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003105 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003106 i != e; ++i)
3107 if (i.getCaseSuccessor() == MaxBlock) {
Chris Lattner25c3af32010-12-13 06:25:44 +00003108 SI->removeCase(i);
3109 --i; --e;
3110 }
3111 }
3112 }
3113 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
3114 if (II->getUnwindDest() == BB) {
3115 // Convert the invoke to a call instruction. This would be a good
3116 // place to note that the call does not throw though.
Devang Patel31458a02011-05-19 00:09:21 +00003117 BranchInst *BI = Builder.CreateBr(II->getNormalDest());
Chris Lattner25c3af32010-12-13 06:25:44 +00003118 II->removeFromParent(); // Take out of symbol table
Andrew Trickf3cf1932012-08-29 21:46:36 +00003119
Chris Lattner25c3af32010-12-13 06:25:44 +00003120 // Insert the call now...
3121 SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
Devang Patel31458a02011-05-19 00:09:21 +00003122 Builder.SetInsertPoint(BI);
3123 CallInst *CI = Builder.CreateCall(II->getCalledValue(),
Jay Foad5bd375a2011-07-15 08:37:34 +00003124 Args, II->getName());
Chris Lattner25c3af32010-12-13 06:25:44 +00003125 CI->setCallingConv(II->getCallingConv());
3126 CI->setAttributes(II->getAttributes());
3127 // If the invoke produced a value, the call does now instead.
3128 II->replaceAllUsesWith(CI);
3129 delete II;
3130 Changed = true;
3131 }
3132 }
3133 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003134
Chris Lattner25c3af32010-12-13 06:25:44 +00003135 // If this block is now dead, remove it.
3136 if (pred_begin(BB) == pred_end(BB) &&
3137 BB != &BB->getParent()->getEntryBlock()) {
3138 // We know there are no successors, so just nuke the block.
3139 BB->eraseFromParent();
3140 return true;
3141 }
3142
3143 return Changed;
3144}
3145
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003146/// TurnSwitchRangeIntoICmp - Turns a switch with that contains only a
3147/// integer range comparison into a sub, an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00003148static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003149 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003150
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003151 // Make sure all cases point to the same destination and gather the values.
3152 SmallVector<ConstantInt *, 16> Cases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003153 SwitchInst::CaseIt I = SI->case_begin();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003154 Cases.push_back(I.getCaseValue());
3155 SwitchInst::CaseIt PrevI = I++;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003156 for (SwitchInst::CaseIt E = SI->case_end(); I != E; PrevI = I++) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003157 if (PrevI.getCaseSuccessor() != I.getCaseSuccessor())
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003158 return false;
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003159 Cases.push_back(I.getCaseValue());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003160 }
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003161 assert(Cases.size() == SI->getNumCases() && "Not all cases gathered");
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00003162
3163 // Sort the case values, then check if they form a range we can transform.
3164 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
3165 for (unsigned I = 1, E = Cases.size(); I != E; ++I) {
3166 if (Cases[I-1]->getValue() != Cases[I]->getValue()+1)
3167 return false;
3168 }
3169
3170 Constant *Offset = ConstantExpr::getNeg(Cases.back());
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003171 Constant *NumCases = ConstantInt::get(Offset->getType(), SI->getNumCases());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003172
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003173 Value *Sub = SI->getCondition();
3174 if (!Offset->isNullValue())
Devang Patel3015a542011-05-19 00:13:33 +00003175 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName()+".off");
Hans Wennborgc9e1d992013-04-16 08:35:36 +00003176 Value *Cmp;
3177 // If NumCases overflowed, then all possible values jump to the successor.
3178 if (NumCases->isNullValue() && SI->getNumCases() != 0)
3179 Cmp = ConstantInt::getTrue(SI->getContext());
3180 else
3181 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Manman Ren56575552012-09-18 00:47:33 +00003182 BranchInst *NewBI = Builder.CreateCondBr(
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003183 Cmp, SI->case_begin().getCaseSuccessor(), SI->getDefaultDest());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003184
Manman Ren56575552012-09-18 00:47:33 +00003185 // Update weight for the newly-created conditional branch.
3186 SmallVector<uint64_t, 8> Weights;
3187 bool HasWeights = HasBranchWeights(SI);
3188 if (HasWeights) {
3189 GetBranchWeights(SI, Weights);
3190 if (Weights.size() == 1 + SI->getNumCases()) {
3191 // Combine all weights for the cases to be the true weight of NewBI.
3192 // We assume that the sum of all weights for a Terminator can fit into 32
3193 // bits.
3194 uint32_t NewTrueWeight = 0;
3195 for (unsigned I = 1, E = Weights.size(); I != E; ++I)
3196 NewTrueWeight += (uint32_t)Weights[I];
3197 NewBI->setMetadata(LLVMContext::MD_prof,
3198 MDBuilder(SI->getContext()).
3199 createBranchWeights(NewTrueWeight,
3200 (uint32_t)Weights[0]));
3201 }
3202 }
3203
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003204 // Prune obsolete incoming values off the successor's PHI nodes.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003205 for (BasicBlock::iterator BBI = SI->case_begin().getCaseSuccessor()->begin();
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003206 isa<PHINode>(BBI); ++BBI) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003207 for (unsigned I = 0, E = SI->getNumCases()-1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00003208 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
3209 }
3210 SI->eraseFromParent();
3211
3212 return true;
3213}
Chris Lattner25c3af32010-12-13 06:25:44 +00003214
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003215/// EliminateDeadSwitchCases - Compute masked bits for the condition of a switch
3216/// and use it to remove dead cases.
Hal Finkel60db0582014-09-07 18:57:58 +00003217static bool EliminateDeadSwitchCases(SwitchInst *SI, const DataLayout *DL,
3218 AssumptionTracker *AT) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003219 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00003220 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003221 APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00003222 computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AT, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003223
3224 // Gather dead cases.
3225 SmallVector<ConstantInt*, 8> DeadCases;
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003226 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003227 if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
3228 (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
3229 DeadCases.push_back(I.getCaseValue());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003230 DEBUG(dbgs() << "SimplifyCFG: switch case '"
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003231 << I.getCaseValue() << "' is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003232 }
3233 }
3234
Manman Ren56575552012-09-18 00:47:33 +00003235 SmallVector<uint64_t, 8> Weights;
3236 bool HasWeight = HasBranchWeights(SI);
3237 if (HasWeight) {
3238 GetBranchWeights(SI, Weights);
3239 HasWeight = (Weights.size() == 1 + SI->getNumCases());
3240 }
3241
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003242 // Remove dead cases from the switch.
3243 for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003244 SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003245 assert(Case != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00003246 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00003247 if (HasWeight) {
3248 std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
3249 Weights.pop_back();
3250 }
3251
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003252 // Prune unused values from PHI nodes.
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003253 Case.getCaseSuccessor()->removePredecessor(SI->getParent());
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003254 SI->removeCase(Case);
3255 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00003256 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00003257 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
3258 SI->setMetadata(LLVMContext::MD_prof,
3259 MDBuilder(SI->getParent()->getContext()).
3260 createBranchWeights(MDWeights));
3261 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00003262
3263 return !DeadCases.empty();
3264}
3265
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003266/// FindPHIForConditionForwarding - If BB would be eligible for simplification
3267/// by TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
3268/// by an unconditional branch), look at the phi node for BB in the successor
3269/// block and see if the incoming value is equal to CaseValue. If so, return
3270/// the phi node, and set PhiIndex to BB's index in the phi node.
3271static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
3272 BasicBlock *BB,
3273 int *PhiIndex) {
3274 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00003275 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003276 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00003277 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003278
3279 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
3280 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00003281 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003282
3283 BasicBlock *Succ = Branch->getSuccessor(0);
3284
3285 BasicBlock::iterator I = Succ->begin();
3286 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3287 int Idx = PHI->getBasicBlockIndex(BB);
3288 assert(Idx >= 0 && "PHI has no entry for predecessor?");
3289
3290 Value *InValue = PHI->getIncomingValue(Idx);
3291 if (InValue != CaseValue) continue;
3292
3293 *PhiIndex = Idx;
3294 return PHI;
3295 }
3296
Craig Topperf40110f2014-04-25 05:29:35 +00003297 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003298}
3299
3300/// ForwardSwitchConditionToPHI - Try to forward the condition of a switch
3301/// instruction to a phi node dominated by the switch, if that would mean that
3302/// some of the destination blocks of the switch can be folded away.
3303/// Returns true if a change is made.
3304static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
3305 typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
3306 ForwardingNodesMap ForwardingNodes;
3307
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003308 for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00003309 ConstantInt *CaseValue = I.getCaseValue();
3310 BasicBlock *CaseDest = I.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003311
3312 int PhiIndex;
3313 PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
3314 &PhiIndex);
3315 if (!PHI) continue;
3316
3317 ForwardingNodes[PHI].push_back(PhiIndex);
3318 }
3319
3320 bool Changed = false;
3321
3322 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
3323 E = ForwardingNodes.end(); I != E; ++I) {
3324 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00003325 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00003326
3327 if (Indexes.size() < 2) continue;
3328
3329 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
3330 Phi->setIncomingValue(Indexes[I], SI->getCondition());
3331 Changed = true;
3332 }
3333
3334 return Changed;
3335}
3336
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003337/// ValidLookupTableConstant - Return true if the backend will be able to handle
3338/// initializing an array of constants like C.
Hans Wennborg08238ad2012-09-07 08:22:57 +00003339static bool ValidLookupTableConstant(Constant *C) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00003340 if (C->isThreadDependent())
3341 return false;
3342 if (C->isDLLImportDependent())
3343 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003344
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00003345 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
3346 return CE->isGEPWithNoNotionalOverIndexing();
3347
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003348 return isa<ConstantFP>(C) ||
3349 isa<ConstantInt>(C) ||
3350 isa<ConstantPointerNull>(C) ||
3351 isa<GlobalValue>(C) ||
3352 isa<UndefValue>(C);
3353}
3354
Hans Wennborg09acdb92012-10-31 15:14:39 +00003355/// LookupConstant - If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003356/// its constant value in ConstantPool, returning 0 if it's not there.
Hans Wennborg09acdb92012-10-31 15:14:39 +00003357static Constant *LookupConstant(Value *V,
3358 const SmallDenseMap<Value*, Constant*>& ConstantPool) {
3359 if (Constant *C = dyn_cast<Constant>(V))
3360 return C;
3361 return ConstantPool.lookup(V);
3362}
3363
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003364/// ConstantFold - Try to fold instruction I into a constant. This works for
3365/// simple instructions such as binary operations where both operands are
3366/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003367/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00003368static Constant *
3369ConstantFold(Instruction *I,
3370 const SmallDenseMap<Value *, Constant *> &ConstantPool,
3371 const DataLayout *DL) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003372 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00003373 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
3374 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00003375 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00003376 if (A->isAllOnesValue())
3377 return LookupConstant(Select->getTrueValue(), ConstantPool);
3378 if (A->isNullValue())
3379 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00003380 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003381 }
3382
Benjamin Kramer7c302602013-11-12 12:24:36 +00003383 SmallVector<Constant *, 4> COps;
3384 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
3385 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
3386 COps.push_back(A);
3387 else
Craig Topperf40110f2014-04-25 05:29:35 +00003388 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003389 }
3390
Benjamin Kramer7c302602013-11-12 12:24:36 +00003391 if (CmpInst *Cmp = dyn_cast<CmpInst>(I))
3392 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
3393 COps[1], DL);
3394
3395 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003396}
3397
3398/// GetCaseResults - Try to determine the resulting constant values in phi nodes
3399/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00003400/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003401/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00003402static bool
3403GetCaseResults(SwitchInst *SI,
3404 ConstantInt *CaseVal,
3405 BasicBlock *CaseDest,
3406 BasicBlock **CommonDest,
Benjamin Kramer7c302602013-11-12 12:24:36 +00003407 SmallVectorImpl<std::pair<PHINode *, Constant *> > &Res,
3408 const DataLayout *DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003409 // The block from which we enter the common destination.
3410 BasicBlock *Pred = SI->getParent();
3411
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003412 // If CaseDest is empty except for some side-effect free instructions through
3413 // which we can constant-propagate the CaseVal, continue to its successor.
3414 SmallDenseMap<Value*, Constant*> ConstantPool;
3415 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
3416 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
3417 ++I) {
3418 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
3419 // If the terminator is a simple branch, continue to the next block.
3420 if (T->getNumSuccessors() != 1)
3421 return false;
3422 Pred = CaseDest;
3423 CaseDest = T->getSuccessor(0);
3424 } else if (isa<DbgInfoIntrinsic>(I)) {
3425 // Skip debug intrinsic.
3426 continue;
Benjamin Kramer7c302602013-11-12 12:24:36 +00003427 } else if (Constant *C = ConstantFold(I, ConstantPool, DL)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003428 // Instruction is side-effect free and constant.
3429 ConstantPool.insert(std::make_pair(I, C));
3430 } else {
3431 break;
3432 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003433 }
3434
3435 // If we did not have a CommonDest before, use the current one.
3436 if (!*CommonDest)
3437 *CommonDest = CaseDest;
3438 // If the destination isn't the common one, abort.
3439 if (CaseDest != *CommonDest)
3440 return false;
3441
3442 // Get the values for this case from phi nodes in the destination block.
3443 BasicBlock::iterator I = (*CommonDest)->begin();
3444 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
3445 int Idx = PHI->getBasicBlockIndex(Pred);
3446 if (Idx == -1)
3447 continue;
3448
Hans Wennborg09acdb92012-10-31 15:14:39 +00003449 Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
3450 ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003451 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003452 return false;
3453
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003454 // Note: If the constant comes from constant-propagating the case value
3455 // through the CaseDest basic block, it will be safe to remove the
3456 // instructions in that block. They cannot be used (except in the phi nodes
3457 // we visit) outside CaseDest, because that block does not dominate its
3458 // successor. If it did, we would not be in this phi node.
3459
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003460 // Be conservative about which kinds of constants we support.
3461 if (!ValidLookupTableConstant(ConstVal))
3462 return false;
3463
3464 Res.push_back(std::make_pair(PHI, ConstVal));
3465 }
3466
Hans Wennborgac114a32014-01-12 00:44:41 +00003467 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003468}
3469
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00003470// MapCaseToResult - Helper function used to
3471// add CaseVal to the list of cases that generate Result.
3472static void MapCaseToResult(ConstantInt *CaseVal,
3473 SwitchCaseResultVectorTy &UniqueResults,
3474 Constant *Result) {
3475 for (auto &I : UniqueResults) {
3476 if (I.first == Result) {
3477 I.second.push_back(CaseVal);
3478 return;
3479 }
3480 }
3481 UniqueResults.push_back(std::make_pair(Result,
3482 SmallVector<ConstantInt*, 4>(1, CaseVal)));
3483}
3484
3485// InitializeUniqueCases - Helper function that initializes a map containing
3486// results for the PHI node of the common destination block for a switch
3487// instruction. Returns false if multiple PHI nodes have been found or if
3488// there is not a common destination block for the switch.
3489static bool InitializeUniqueCases(
3490 SwitchInst *SI, const DataLayout *DL, PHINode *&PHI,
3491 BasicBlock *&CommonDest,
3492 SwitchCaseResultVectorTy &UniqueResults,
3493 Constant *&DefaultResult) {
3494 for (auto &I : SI->cases()) {
3495 ConstantInt *CaseVal = I.getCaseValue();
3496
3497 // Resulting value at phi nodes for this case value.
3498 SwitchCaseResultsTy Results;
3499 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
3500 DL))
3501 return false;
3502
3503 // Only one value per case is permitted
3504 if (Results.size() > 1)
3505 return false;
3506 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
3507
3508 // Check the PHI consistency.
3509 if (!PHI)
3510 PHI = Results[0].first;
3511 else if (PHI != Results[0].first)
3512 return false;
3513 }
3514 // Find the default result value.
3515 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
3516 BasicBlock *DefaultDest = SI->getDefaultDest();
3517 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
3518 DL);
3519 // If the default value is not found abort unless the default destination
3520 // is unreachable.
3521 DefaultResult =
3522 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
3523 if ((!DefaultResult &&
3524 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
3525 return false;
3526
3527 return true;
3528}
3529
3530// ConvertTwoCaseSwitch - Helper function that checks if it is possible to
3531// transform a switch with only two cases (or two cases + default)
3532// that produces a result into a value select.
3533// Example:
3534// switch (a) {
3535// case 10: %0 = icmp eq i32 %a, 10
3536// return 10; %1 = select i1 %0, i32 10, i32 4
3537// case 20: ----> %2 = icmp eq i32 %a, 20
3538// return 2; %3 = select i1 %2, i32 2, i32 %1
3539// default:
3540// return 4;
3541// }
3542static Value *
3543ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
3544 Constant *DefaultResult, Value *Condition,
3545 IRBuilder<> &Builder) {
3546 assert(ResultVector.size() == 2 &&
3547 "We should have exactly two unique results at this point");
3548 // If we are selecting between only two cases transform into a simple
3549 // select or a two-way select if default is possible.
3550 if (ResultVector[0].second.size() == 1 &&
3551 ResultVector[1].second.size() == 1) {
3552 ConstantInt *const FirstCase = ResultVector[0].second[0];
3553 ConstantInt *const SecondCase = ResultVector[1].second[0];
3554
3555 bool DefaultCanTrigger = DefaultResult;
3556 Value *SelectValue = ResultVector[1].first;
3557 if (DefaultCanTrigger) {
3558 Value *const ValueCompare =
3559 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
3560 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
3561 DefaultResult, "switch.select");
3562 }
3563 Value *const ValueCompare =
3564 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
3565 return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
3566 "switch.select");
3567 }
3568
3569 return nullptr;
3570}
3571
3572// RemoveSwitchAfterSelectConversion - Helper function to cleanup a switch
3573// instruction that has been converted into a select, fixing up PHI nodes and
3574// basic blocks.
3575static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
3576 Value *SelectValue,
3577 IRBuilder<> &Builder) {
3578 BasicBlock *SelectBB = SI->getParent();
3579 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
3580 PHI->removeIncomingValue(SelectBB);
3581 PHI->addIncoming(SelectValue, SelectBB);
3582
3583 Builder.CreateBr(PHI->getParent());
3584
3585 // Remove the switch.
3586 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
3587 BasicBlock *Succ = SI->getSuccessor(i);
3588
3589 if (Succ == PHI->getParent())
3590 continue;
3591 Succ->removePredecessor(SelectBB);
3592 }
3593 SI->eraseFromParent();
3594}
3595
3596/// SwitchToSelect - If the switch is only used to initialize one or more
3597/// phi nodes in a common successor block with only two different
3598/// constant values, replace the switch with select.
3599static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
3600 const DataLayout *DL, AssumptionTracker *AT) {
3601 Value *const Cond = SI->getCondition();
3602 PHINode *PHI = nullptr;
3603 BasicBlock *CommonDest = nullptr;
3604 Constant *DefaultResult;
3605 SwitchCaseResultVectorTy UniqueResults;
3606 // Collect all the cases that will deliver the same value from the switch.
3607 if (!InitializeUniqueCases(SI, DL, PHI, CommonDest, UniqueResults,
3608 DefaultResult))
3609 return false;
3610 // Selects choose between maximum two values.
3611 if (UniqueResults.size() != 2)
3612 return false;
3613 assert(PHI != nullptr && "PHI for value select not found");
3614
3615 Builder.SetInsertPoint(SI);
3616 Value *SelectValue = ConvertTwoCaseSwitch(
3617 UniqueResults,
3618 DefaultResult, Cond, Builder);
3619 if (SelectValue) {
3620 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
3621 return true;
3622 }
3623 // The switch couldn't be converted into a select.
3624 return false;
3625}
3626
Hans Wennborg776d7122012-09-26 09:34:53 +00003627namespace {
3628 /// SwitchLookupTable - This class represents a lookup table that can be used
3629 /// to replace a switch.
3630 class SwitchLookupTable {
3631 public:
3632 /// SwitchLookupTable - Create a lookup table to use as a switch replacement
3633 /// with the contents of Values, using DefaultValue to fill any holes in the
3634 /// table.
3635 SwitchLookupTable(Module &M,
3636 uint64_t TableSize,
3637 ConstantInt *Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00003638 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
Hans Wennborg39583b82012-09-26 09:44:49 +00003639 Constant *DefaultValue,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003640 const DataLayout *DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00003641
3642 /// BuildLookup - Build instructions with Builder to retrieve the value at
3643 /// the position given by Index in the lookup table.
Manman Ren4d189fb2014-07-24 21:13:20 +00003644 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00003645
Hans Wennborg39583b82012-09-26 09:44:49 +00003646 /// WouldFitInRegister - Return true if a table with TableSize elements of
3647 /// type ElementType would fit in a target-legal register.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003648 static bool WouldFitInRegister(const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003649 uint64_t TableSize,
3650 const Type *ElementType);
3651
Hans Wennborg776d7122012-09-26 09:34:53 +00003652 private:
3653 // Depending on the contents of the table, it can be represented in
3654 // different ways.
3655 enum {
3656 // For tables where each element contains the same value, we just have to
3657 // store that single value and return it for each lookup.
3658 SingleValueKind,
3659
Erik Eckstein105374f2014-11-17 09:13:57 +00003660 // For tables where there is a linear relationship between table index
3661 // and values. We calculate the result with a simple multiplication
3662 // and addition instead of a table lookup.
3663 LinearMapKind,
3664
Hans Wennborg39583b82012-09-26 09:44:49 +00003665 // For small tables with integer elements, we can pack them into a bitmap
3666 // that fits into a target-legal register. Values are retrieved by
3667 // shift and mask operations.
3668 BitMapKind,
3669
Hans Wennborg776d7122012-09-26 09:34:53 +00003670 // The table is stored as an array of values. Values are retrieved by load
3671 // instructions from the table.
3672 ArrayKind
3673 } Kind;
3674
3675 // For SingleValueKind, this is the single value.
3676 Constant *SingleValue;
3677
Hans Wennborg39583b82012-09-26 09:44:49 +00003678 // For BitMapKind, this is the bitmap.
3679 ConstantInt *BitMap;
3680 IntegerType *BitMapElementTy;
3681
Erik Eckstein105374f2014-11-17 09:13:57 +00003682 // For LinearMapKind, these are the constants used to derive the value.
3683 ConstantInt *LinearOffset;
3684 ConstantInt *LinearMultiplier;
3685
Hans Wennborg776d7122012-09-26 09:34:53 +00003686 // For ArrayKind, this is the array.
3687 GlobalVariable *Array;
3688 };
3689}
3690
3691SwitchLookupTable::SwitchLookupTable(Module &M,
3692 uint64_t TableSize,
3693 ConstantInt *Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00003694 const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values,
Hans Wennborg39583b82012-09-26 09:44:49 +00003695 Constant *DefaultValue,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003696 const DataLayout *DL)
Craig Topperf40110f2014-04-25 05:29:35 +00003697 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00003698 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003699 assert(Values.size() && "Can't build lookup table without values!");
3700 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003701
3702 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00003703 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003704
Hans Wennborgac114a32014-01-12 00:44:41 +00003705 Type *ValueType = Values.begin()->second->getType();
3706
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003707 // Build up the table contents.
Hans Wennborg776d7122012-09-26 09:34:53 +00003708 SmallVector<Constant*, 64> TableContents(TableSize);
3709 for (size_t I = 0, E = Values.size(); I != E; ++I) {
3710 ConstantInt *CaseVal = Values[I].first;
3711 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00003712 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003713
Hans Wennborg776d7122012-09-26 09:34:53 +00003714 uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
3715 .getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003716 TableContents[Idx] = CaseRes;
3717
Hans Wennborg776d7122012-09-26 09:34:53 +00003718 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003719 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003720 }
3721
3722 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00003723 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00003724 assert(DefaultValue &&
3725 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00003726 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00003727 for (uint64_t I = 0; I < TableSize; ++I) {
3728 if (!TableContents[I])
3729 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003730 }
3731
Hans Wennborg776d7122012-09-26 09:34:53 +00003732 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00003733 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003734 }
3735
Hans Wennborg776d7122012-09-26 09:34:53 +00003736 // If each element in the table contains the same value, we only need to store
3737 // that single value.
3738 if (SingleValue) {
3739 Kind = SingleValueKind;
3740 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003741 }
3742
Erik Eckstein105374f2014-11-17 09:13:57 +00003743 // Check if we can derive the value with a linear transformation from the
3744 // table index.
3745 if (isa<IntegerType>(ValueType)) {
3746 bool LinearMappingPossible = true;
3747 APInt PrevVal;
3748 APInt DistToPrev;
3749 assert(TableSize >= 2 && "Should be a SingleValue table.");
3750 // Check if there is the same distance between two consecutive values.
3751 for (uint64_t I = 0; I < TableSize; ++I) {
3752 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
3753 if (!ConstVal) {
3754 // This is an undef. We could deal with it, but undefs in lookup tables
3755 // are very seldom. It's probably not worth the additional complexity.
3756 LinearMappingPossible = false;
3757 break;
3758 }
3759 APInt Val = ConstVal->getValue();
3760 if (I != 0) {
3761 APInt Dist = Val - PrevVal;
3762 if (I == 1) {
3763 DistToPrev = Dist;
3764 } else if (Dist != DistToPrev) {
3765 LinearMappingPossible = false;
3766 break;
3767 }
3768 }
3769 PrevVal = Val;
3770 }
3771 if (LinearMappingPossible) {
3772 LinearOffset = cast<ConstantInt>(TableContents[0]);
3773 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
3774 Kind = LinearMapKind;
3775 ++NumLinearMaps;
3776 return;
3777 }
3778 }
3779
Hans Wennborg39583b82012-09-26 09:44:49 +00003780 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003781 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00003782 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00003783 APInt TableInt(TableSize * IT->getBitWidth(), 0);
3784 for (uint64_t I = TableSize; I > 0; --I) {
3785 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00003786 // Insert values into the bitmap. Undef values are set to zero.
3787 if (!isa<UndefValue>(TableContents[I - 1])) {
3788 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
3789 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
3790 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003791 }
3792 BitMap = ConstantInt::get(M.getContext(), TableInt);
3793 BitMapElementTy = IT;
3794 Kind = BitMapKind;
3795 ++NumBitMaps;
3796 return;
3797 }
3798
Hans Wennborg776d7122012-09-26 09:34:53 +00003799 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00003800 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003801 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
3802
Hans Wennborg776d7122012-09-26 09:34:53 +00003803 Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
3804 GlobalVariable::PrivateLinkage,
3805 Initializer,
3806 "switch.table");
3807 Array->setUnnamedAddr(true);
3808 Kind = ArrayKind;
3809}
3810
Manman Ren4d189fb2014-07-24 21:13:20 +00003811Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00003812 switch (Kind) {
3813 case SingleValueKind:
3814 return SingleValue;
Erik Eckstein105374f2014-11-17 09:13:57 +00003815 case LinearMapKind: {
3816 // Derive the result value from the input value.
3817 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
3818 false, "switch.idx.cast");
3819 if (!LinearMultiplier->isOne())
3820 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
3821 if (!LinearOffset->isZero())
3822 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
3823 return Result;
3824 }
Hans Wennborg39583b82012-09-26 09:44:49 +00003825 case BitMapKind: {
3826 // Type of the bitmap (e.g. i59).
3827 IntegerType *MapTy = BitMap->getType();
3828
3829 // Cast Index to the same type as the bitmap.
3830 // Note: The Index is <= the number of elements in the table, so
3831 // truncating it to the width of the bitmask is safe.
Hans Wennborgcd3a11f2012-09-26 14:01:53 +00003832 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00003833
3834 // Multiply the shift amount by the element width.
3835 ShiftAmt = Builder.CreateMul(ShiftAmt,
3836 ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
3837 "switch.shiftamt");
3838
3839 // Shift down.
3840 Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
3841 "switch.downshift");
3842 // Mask off.
3843 return Builder.CreateTrunc(DownShifted, BitMapElementTy,
3844 "switch.masked");
3845 }
Hans Wennborg776d7122012-09-26 09:34:53 +00003846 case ArrayKind: {
Manman Renedc60372014-07-23 23:13:23 +00003847 // Make sure the table index will not overflow when treated as signed.
Manman Ren4d189fb2014-07-24 21:13:20 +00003848 IntegerType *IT = cast<IntegerType>(Index->getType());
3849 uint64_t TableSize = Array->getInitializer()->getType()
3850 ->getArrayNumElements();
3851 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
3852 Index = Builder.CreateZExt(Index,
3853 IntegerType::get(IT->getContext(),
3854 IT->getBitWidth() + 1),
3855 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00003856
Hans Wennborg776d7122012-09-26 09:34:53 +00003857 Value *GEPIndices[] = { Builder.getInt32(0), Index };
3858 Value *GEP = Builder.CreateInBoundsGEP(Array, GEPIndices,
3859 "switch.gep");
3860 return Builder.CreateLoad(GEP, "switch.load");
3861 }
3862 }
3863 llvm_unreachable("Unknown lookup table kind!");
3864}
3865
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003866bool SwitchLookupTable::WouldFitInRegister(const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003867 uint64_t TableSize,
3868 const Type *ElementType) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003869 if (!DL)
Hans Wennborg39583b82012-09-26 09:44:49 +00003870 return false;
3871 const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
3872 if (!IT)
3873 return false;
3874 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
3875 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00003876
3877 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
3878 if (TableSize >= UINT_MAX/IT->getBitWidth())
3879 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003880 return DL->fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00003881}
3882
Hans Wennborg776d7122012-09-26 09:34:53 +00003883/// ShouldBuildLookupTable - Determine whether a lookup table should be built
Hans Wennborg5cf30be2013-06-04 11:22:30 +00003884/// for this switch, based on the number of cases, size of the table and the
Hans Wennborg776d7122012-09-26 09:34:53 +00003885/// types of the results.
3886static bool ShouldBuildLookupTable(SwitchInst *SI,
Hans Wennborg39583b82012-09-26 09:44:49 +00003887 uint64_t TableSize,
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003888 const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003889 const DataLayout *DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00003890 const SmallDenseMap<PHINode*, Type*>& ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00003891 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
3892 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00003893
Chandler Carruth77d433d2012-11-30 09:26:25 +00003894 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00003895 bool HasIllegalType = false;
Hans Wennborg39583b82012-09-26 09:44:49 +00003896 for (SmallDenseMap<PHINode*, Type*>::const_iterator I = ResultTypes.begin(),
3897 E = ResultTypes.end(); I != E; ++I) {
Evan Cheng65df8082012-11-30 02:02:42 +00003898 Type *Ty = I->second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003899
3900 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003901 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003902
3903 // Saturate this flag to false.
3904 AllTablesFitInRegister = AllTablesFitInRegister &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003905 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00003906
3907 // If both flags saturate, we're done. NOTE: This *only* works with
3908 // saturating flags, and all flags have to saturate first due to the
3909 // non-deterministic behavior of iterating over a dense map.
3910 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00003911 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00003912 }
Evan Cheng65df8082012-11-30 02:02:42 +00003913
Chandler Carruth77d433d2012-11-30 09:26:25 +00003914 // If each table would fit in a register, we should build it anyway.
3915 if (AllTablesFitInRegister)
3916 return true;
3917
3918 // Don't build a table that doesn't fit in-register if it has illegal types.
3919 if (HasIllegalType)
3920 return false;
3921
3922 // The table density should be at least 40%. This is the same criterion as for
3923 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
3924 // FIXME: Find the best cut-off.
3925 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003926}
3927
3928/// SwitchToLookupTable - If the switch is only used to initialize one or more
3929/// phi nodes in a common successor block with different constant values,
3930/// replace the switch with lookup tables.
3931static bool SwitchToLookupTable(SwitchInst *SI,
Hans Wennborg39583b82012-09-26 09:44:49 +00003932 IRBuilder<> &Builder,
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003933 const TargetTransformInfo &TTI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003934 const DataLayout* DL) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003935 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00003936
Hans Wennborgc3c8d952012-11-07 21:35:12 +00003937 // Only build lookup table when we have a target that supports it.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003938 if (!TTI.shouldBuildLookupTables())
Hans Wennborgf3254832012-10-30 11:23:25 +00003939 return false;
3940
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003941 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
3942 // split off a dense part and build a lookup table for that.
3943
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003944 // FIXME: This creates arrays of GEPs to constant strings, which means each
3945 // GEP needs a runtime relocation in PIC code. We should just build one big
3946 // string and lookup indices into that.
3947
Hans Wennborg4744ac12014-01-15 05:00:27 +00003948 // Ignore switches with less than three cases. Lookup tables will not make them
3949 // faster, so we don't analyze them.
3950 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003951 return false;
3952
3953 // Figure out the corresponding result for each case value and phi node in the
3954 // common destination, as well as the the min and max case values.
3955 assert(SI->case_begin() != SI->case_end());
3956 SwitchInst::CaseIt CI = SI->case_begin();
3957 ConstantInt *MinCaseVal = CI.getCaseValue();
3958 ConstantInt *MaxCaseVal = CI.getCaseValue();
3959
Craig Topperf40110f2014-04-25 05:29:35 +00003960 BasicBlock *CommonDest = nullptr;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00003961 typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003962 SmallDenseMap<PHINode*, ResultListTy> ResultLists;
3963 SmallDenseMap<PHINode*, Constant*> DefaultResults;
3964 SmallDenseMap<PHINode*, Type*> ResultTypes;
3965 SmallVector<PHINode*, 4> PHIs;
3966
3967 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
3968 ConstantInt *CaseVal = CI.getCaseValue();
3969 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
3970 MinCaseVal = CaseVal;
3971 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
3972 MaxCaseVal = CaseVal;
3973
3974 // Resulting value at phi nodes for this case value.
3975 typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
3976 ResultsTy Results;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00003977 if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003978 Results, DL))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00003979 return false;
3980
3981 // Append the result from this case to the list for each phi.
3982 for (ResultsTy::iterator I = Results.begin(), E = Results.end(); I!=E; ++I) {
3983 if (!ResultLists.count(I->first))
3984 PHIs.push_back(I->first);
3985 ResultLists[I->first].push_back(std::make_pair(CaseVal, I->second));
3986 }
3987 }
3988
Hans Wennborgac114a32014-01-12 00:44:41 +00003989 // Keep track of the result types.
3990 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
3991 PHINode *PHI = PHIs[I];
3992 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
3993 }
3994
3995 uint64_t NumResults = ResultLists[PHIs[0]].size();
3996 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
3997 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
3998 bool TableHasHoles = (NumResults < TableSize);
3999
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004000 // If the table has holes, we need a constant result for the default case
4001 // or a bitmask that fits in a register.
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004002 SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004003 bool HasDefaultResults = false;
4004 if (TableHasHoles) {
Craig Topperf40110f2014-04-25 05:29:35 +00004005 HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
4006 &CommonDest, DefaultResultsList, DL);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004007 }
4008 bool NeedMask = (TableHasHoles && !HasDefaultResults);
4009 if (NeedMask) {
4010 // As an extra penalty for the validity test we require more cases.
4011 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
4012 return false;
4013 if (!(DL && DL->fitsInLegalInteger(TableSize)))
4014 return false;
4015 }
Hans Wennborgac114a32014-01-12 00:44:41 +00004016
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00004017 for (size_t I = 0, E = DefaultResultsList.size(); I != E; ++I) {
4018 PHINode *PHI = DefaultResultsList[I].first;
4019 Constant *Result = DefaultResultsList[I].second;
4020 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004021 }
4022
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004023 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004024 return false;
4025
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004026 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00004027 Module &Mod = *CommonDest->getParent()->getParent();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004028 BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
4029 "switch.lookup",
4030 CommonDest->getParent(),
4031 CommonDest);
4032
Michael Gottesmanc024f322013-10-20 07:04:37 +00004033 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004034 Builder.SetInsertPoint(SI);
4035 Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
4036 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00004037
4038 // Compute the maximum table size representable by the integer type we are
4039 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004040 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00004041 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00004042 assert(MaxTableSize >= TableSize &&
4043 "It is impossible for a switch to have more entries than the max "
4044 "representable value of its input integer type's size.");
4045
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004046 // If we have a fully covered lookup table, unconditionally branch to the
4047 // lookup table BB. Otherwise, check if the condition value is within the case
4048 // range. If it is so, branch to the new BB. Otherwise branch to SI's default
4049 // destination.
Michael Gottesmanc024f322013-10-20 07:04:37 +00004050 const bool GeneratingCoveredLookupTable = MaxTableSize == TableSize;
4051 if (GeneratingCoveredLookupTable) {
4052 Builder.CreateBr(LookupBB);
Manman Ren062f58d2014-08-02 23:41:54 +00004053 // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
4054 // do not delete PHINodes here.
4055 SI->getDefaultDest()->removePredecessor(SI->getParent(),
4056 true/*DontDeleteUselessPHIs*/);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004057 } else {
4058 Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
Manman Renedc60372014-07-23 23:13:23 +00004059 MinCaseVal->getType(), TableSize));
Michael Gottesmanc024f322013-10-20 07:04:37 +00004060 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
4061 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004062
4063 // Populate the BB that does the lookups.
4064 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004065
4066 if (NeedMask) {
4067 // Before doing the lookup we do the hole check.
4068 // The LookupBB is therefore re-purposed to do the hole check
4069 // and we create a new LookupBB.
4070 BasicBlock *MaskBB = LookupBB;
4071 MaskBB->setName("switch.hole_check");
4072 LookupBB = BasicBlock::Create(Mod.getContext(),
4073 "switch.lookup",
4074 CommonDest->getParent(),
4075 CommonDest);
4076
Juergen Ributzkac9591e92014-11-17 19:39:56 +00004077 // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
4078 // unnecessary illegal types.
4079 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
4080 APInt MaskInt(TableSizePowOf2, 0);
4081 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004082 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004083 const ResultListTy &ResultList = ResultLists[PHIs[0]];
4084 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
4085 uint64_t Idx = (ResultList[I].first->getValue() -
4086 MinCaseVal->getValue()).getLimitedValue();
4087 MaskInt |= One << Idx;
4088 }
4089 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
4090
4091 // Get the TableIndex'th bit of the bitmask.
4092 // If this bit is 0 (meaning hole) jump to the default destination,
4093 // else continue with table lookup.
4094 IntegerType *MapTy = TableMask->getType();
4095 Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
4096 "switch.maskindex");
4097 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
4098 "switch.shifted");
4099 Value *LoBit = Builder.CreateTrunc(Shifted,
4100 Type::getInt1Ty(Mod.getContext()),
4101 "switch.lobit");
4102 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
4103
4104 Builder.SetInsertPoint(LookupBB);
4105 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
4106 }
4107
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004108 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00004109 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
4110 PHINode *PHI = PHIs[I];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004111
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004112 // If using a bitmask, use any value to fill the lookup table holes.
4113 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Hans Wennborg776d7122012-09-26 09:34:53 +00004114 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultLists[PHI],
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004115 DV, DL);
Hans Wennborg776d7122012-09-26 09:34:53 +00004116
Manman Ren4d189fb2014-07-24 21:13:20 +00004117 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004118
Hans Wennborgf744fa92012-09-19 14:24:21 +00004119 // If the result is used to return immediately from the function, we want to
4120 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004121 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
4122 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00004123 Builder.CreateRet(Result);
4124 ReturnedEarly = true;
4125 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004126 }
4127
Hans Wennborgf744fa92012-09-19 14:24:21 +00004128 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004129 }
4130
4131 if (!ReturnedEarly)
4132 Builder.CreateBr(CommonDest);
4133
4134 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004135 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004136 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00004137
Michael Gottesman63c63ac2013-10-21 05:20:11 +00004138 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00004139 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004140 Succ->removePredecessor(SI->getParent());
4141 }
4142 SI->eraseFromParent();
4143
4144 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00004145 if (NeedMask)
4146 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004147 return true;
4148}
4149
Devang Patela7ec47d2011-05-18 20:35:38 +00004150bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004151 BasicBlock *BB = SI->getParent();
4152
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004153 if (isValueEqualityComparison(SI)) {
4154 // If we only have one predecessor, and if it is a branch on this value,
4155 // see if that predecessor totally determines the outcome of this switch.
4156 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
4157 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004158 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004159
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004160 Value *Cond = SI->getCondition();
4161 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
4162 if (SimplifySwitchOnSelect(SI, Select))
Jingyue Wufc029672014-09-30 22:23:38 +00004163 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00004164
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004165 // If the block only contains the switch, see if we can fold the block
4166 // away into any preds.
4167 BasicBlock::iterator BBI = BB->begin();
4168 // Ignore dbg intrinsics.
4169 while (isa<DbgInfoIntrinsic>(BBI))
4170 ++BBI;
4171 if (SI == &*BBI)
4172 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004173 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00004174 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004175
4176 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004177 if (TurnSwitchRangeIntoICmp(SI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004178 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004179
4180 // Remove unreachable cases.
Hal Finkel60db0582014-09-07 18:57:58 +00004181 if (EliminateDeadSwitchCases(SI, DL, AT))
Jingyue Wufc029672014-09-30 22:23:38 +00004182 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004183
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004184 if (SwitchToSelect(SI, Builder, DL, AT))
4185 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
4186
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004187 if (ForwardSwitchConditionToPHI(SI))
Jingyue Wufc029672014-09-30 22:23:38 +00004188 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004189
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004190 if (SwitchToLookupTable(SI, Builder, TTI, DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004191 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004192
Chris Lattner25c3af32010-12-13 06:25:44 +00004193 return false;
4194}
4195
4196bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
4197 BasicBlock *BB = IBI->getParent();
4198 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004199
Chris Lattner25c3af32010-12-13 06:25:44 +00004200 // Eliminate redundant destinations.
4201 SmallPtrSet<Value *, 8> Succs;
4202 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
4203 BasicBlock *Dest = IBI->getDestination(i);
4204 if (!Dest->hasAddressTaken() || !Succs.insert(Dest)) {
4205 Dest->removePredecessor(BB);
4206 IBI->removeDestination(i);
4207 --i; --e;
4208 Changed = true;
4209 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004210 }
Chris Lattner25c3af32010-12-13 06:25:44 +00004211
4212 if (IBI->getNumDestinations() == 0) {
4213 // If the indirectbr has no successors, change it to unreachable.
4214 new UnreachableInst(IBI->getContext(), IBI);
4215 EraseTerminatorInstAndDCECond(IBI);
4216 return true;
4217 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004218
Chris Lattner25c3af32010-12-13 06:25:44 +00004219 if (IBI->getNumDestinations() == 1) {
4220 // If the indirectbr has one successor, change it to a direct branch.
4221 BranchInst::Create(IBI->getDestination(0), IBI);
4222 EraseTerminatorInstAndDCECond(IBI);
4223 return true;
4224 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004225
Chris Lattner25c3af32010-12-13 06:25:44 +00004226 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
4227 if (SimplifyIndirectBrOnSelect(IBI, SI))
Jingyue Wufc029672014-09-30 22:23:38 +00004228 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004229 }
4230 return Changed;
4231}
4232
Devang Patel767f6932011-05-18 18:28:48 +00004233bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
Chris Lattner25c3af32010-12-13 06:25:44 +00004234 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004235
Manman Ren93ab6492012-09-20 22:37:36 +00004236 if (SinkCommon && SinkThenElseCodeToEnd(BI))
4237 return true;
4238
Chris Lattner25c3af32010-12-13 06:25:44 +00004239 // If the Terminator is the only non-phi instruction, simplify the block.
Rafael Espindolad07cf402014-07-30 21:04:00 +00004240 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
Chris Lattner25c3af32010-12-13 06:25:44 +00004241 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
4242 TryToSimplifyUncondBranchFromEmptyBlock(BB))
4243 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004244
Chris Lattner25c3af32010-12-13 06:25:44 +00004245 // If the only instruction in the block is a seteq/setne comparison
4246 // against a constant, try to simplify the block.
4247 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
4248 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
4249 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
4250 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004251 if (I->isTerminator() &&
Jingyue Wufc029672014-09-30 22:23:38 +00004252 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, TTI,
4253 BonusInstThreshold, DL, AT))
Chris Lattner25c3af32010-12-13 06:25:44 +00004254 return true;
4255 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004256
Manman Rend33f4ef2012-06-13 05:43:29 +00004257 // If this basic block is ONLY a compare and a branch, and if a predecessor
4258 // branches to us and our successor, fold the comparison into the
4259 // predecessor and use logical operations to update the incoming value
4260 // for PHI nodes in common successor.
Jingyue Wufc029672014-09-30 22:23:38 +00004261 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4262 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004263 return false;
4264}
4265
4266
Devang Patela7ec47d2011-05-18 20:35:38 +00004267bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004268 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004269
Chris Lattner25c3af32010-12-13 06:25:44 +00004270 // Conditional branch
4271 if (isValueEqualityComparison(BI)) {
4272 // If we only have one predecessor, and if it is a branch on this value,
4273 // see if that predecessor totally determines the outcome of this
4274 // switch.
4275 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00004276 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004277 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004278
Chris Lattner25c3af32010-12-13 06:25:44 +00004279 // This block must be empty, except for the setcond inst, if it exists.
4280 // Ignore dbg intrinsics.
4281 BasicBlock::iterator I = BB->begin();
4282 // Ignore dbg intrinsics.
4283 while (isa<DbgInfoIntrinsic>(I))
4284 ++I;
4285 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00004286 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004287 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004288 } else if (&*I == cast<Instruction>(BI->getCondition())){
4289 ++I;
4290 // Ignore dbg intrinsics.
4291 while (isa<DbgInfoIntrinsic>(I))
4292 ++I;
Devang Patel58380552011-05-18 20:53:17 +00004293 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Jingyue Wufc029672014-09-30 22:23:38 +00004294 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004295 }
4296 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004297
Chris Lattner25c3af32010-12-13 06:25:44 +00004298 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004299 if (SimplifyBranchOnICmpChain(BI, DL, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00004300 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004301
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00004302 // If this basic block is ONLY a compare and a branch, and if a predecessor
4303 // branches to us and one of our successors, fold the comparison into the
4304 // predecessor and use logical operations to pick the right destination.
Jingyue Wufc029672014-09-30 22:23:38 +00004305 if (FoldBranchToCommonDest(BI, DL, BonusInstThreshold))
4306 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004307
Chris Lattner25c3af32010-12-13 06:25:44 +00004308 // We have a conditional branch to two blocks that are only reachable
4309 // from BI. We know that the condbr dominates the two blocks, so see if
4310 // there is any identical code in the "then" and "else" blocks. If so, we
4311 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00004312 if (BI->getSuccessor(0)->getSinglePredecessor()) {
4313 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Hal Finkela995f922014-07-10 14:41:31 +00004314 if (HoistThenElseCodeToIf(BI, DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004315 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004316 } else {
4317 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004318 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00004319 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
4320 if (Succ0TI->getNumSuccessors() == 1 &&
4321 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Hal Finkela995f922014-07-10 14:41:31 +00004322 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004323 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004324 }
Craig Topperf40110f2014-04-25 05:29:35 +00004325 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004326 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00004327 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00004328 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
4329 if (Succ1TI->getNumSuccessors() == 1 &&
4330 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Hal Finkela995f922014-07-10 14:41:31 +00004331 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004332 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004333 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004334
Chris Lattner25c3af32010-12-13 06:25:44 +00004335 // If this is a branch on a phi node in the current block, thread control
4336 // through this block if any PHI node entries are constants.
4337 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
4338 if (PN->getParent() == BI->getParent())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004339 if (FoldCondBranchOnPHI(BI, DL))
Jingyue Wufc029672014-09-30 22:23:38 +00004340 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004341
Chris Lattner25c3af32010-12-13 06:25:44 +00004342 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004343 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
4344 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00004345 if (PBI != BI && PBI->isConditional())
4346 if (SimplifyCondBranchToCondBranch(PBI, BI))
Jingyue Wufc029672014-09-30 22:23:38 +00004347 return SimplifyCFG(BB, TTI, BonusInstThreshold, DL, AT) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004348
4349 return false;
4350}
4351
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004352/// Check if passing a value to an instruction will cause undefined behavior.
4353static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
4354 Constant *C = dyn_cast<Constant>(V);
4355 if (!C)
4356 return false;
4357
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004358 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004359 return false;
4360
4361 if (C->isNullValue()) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00004362 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00004363 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004364
4365 // Now make sure that there are no instructions in between that can alter
4366 // control flow (eg. calls)
4367 for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00004368 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004369 return false;
4370
4371 // Look through GEPs. A load from a GEP derived from NULL is still undefined
4372 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
4373 if (GEP->getPointerOperand() == I)
4374 return passingValueIsAlwaysUndefined(V, GEP);
4375
4376 // Look through bitcasts.
4377 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
4378 return passingValueIsAlwaysUndefined(V, BC);
4379
Benjamin Kramer0655b782011-08-26 02:25:55 +00004380 // Load from null is undefined.
4381 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004382 if (!LI->isVolatile())
4383 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004384
Benjamin Kramer0655b782011-08-26 02:25:55 +00004385 // Store to null is undefined.
4386 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00004387 if (!SI->isVolatile())
4388 return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004389 }
4390 return false;
4391}
4392
4393/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00004394/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004395static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
4396 for (BasicBlock::iterator i = BB->begin();
4397 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
4398 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4399 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
4400 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
4401 IRBuilder<> Builder(T);
4402 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
4403 BB->removePredecessor(PHI->getIncomingBlock(i));
4404 // Turn uncoditional branches into unreachables and remove the dead
4405 // destination from conditional branches.
4406 if (BI->isUnconditional())
4407 Builder.CreateUnreachable();
4408 else
4409 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
4410 BI->getSuccessor(0));
4411 BI->eraseFromParent();
4412 return true;
4413 }
4414 // TODO: SwitchInst.
4415 }
4416
4417 return false;
4418}
4419
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004420bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00004421 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00004422
Chris Lattnerd7beca32010-12-14 06:17:25 +00004423 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00004424 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00004425
Dan Gohman4a63fad2010-08-14 00:29:42 +00004426 // Remove basic blocks that have no predecessors (except the entry block)...
4427 // or that just have themself as a predecessor. These are unreachable.
Chris Lattnerd7beca32010-12-14 06:17:25 +00004428 if ((pred_begin(BB) == pred_end(BB) &&
4429 BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00004430 BB->getSinglePredecessor() == BB) {
David Greene725c7c32010-01-05 01:26:52 +00004431 DEBUG(dbgs() << "Removing BB: \n" << *BB);
Chris Lattner7eb270e2008-12-03 06:40:52 +00004432 DeleteDeadBlock(BB);
Chris Lattner466a0492002-05-21 20:50:24 +00004433 return true;
4434 }
4435
Chris Lattner031340a2003-08-17 19:41:53 +00004436 // Check to see if we can constant propagate this terminator instruction
4437 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00004438 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00004439
Dan Gohman1a951062009-10-30 22:39:04 +00004440 // Check for and eliminate duplicate PHI nodes in this block.
4441 Changed |= EliminateDuplicatePHINodes(BB);
4442
Benjamin Kramerfb212a62011-08-26 01:22:29 +00004443 // Check for and remove branches that will always cause undefined behavior.
4444 Changed |= removeUndefIntroducingPredecessor(BB);
4445
Chris Lattner2e3832d2010-12-13 05:10:48 +00004446 // Merge basic blocks into their predecessor if there is only one distinct
4447 // pred, and if there is only one distinct successor of the predecessor, and
4448 // if there are no PHI nodes.
4449 //
4450 if (MergeBlockIntoPredecessor(BB))
4451 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004452
Devang Patel15ad6762011-05-18 18:01:27 +00004453 IRBuilder<> Builder(BB);
4454
Dan Gohman20af5a02008-03-11 21:53:06 +00004455 // If there is a trivial two-entry PHI node in this basic block, and we can
4456 // eliminate it, do so now.
4457 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
4458 if (PN->getNumIncomingValues() == 2)
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004459 Changed |= FoldTwoEntryPHINode(PN, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00004460
Devang Patela7ec47d2011-05-18 20:35:38 +00004461 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00004462 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00004463 if (BI->isUnconditional()) {
Devang Patel767f6932011-05-18 18:28:48 +00004464 if (SimplifyUncondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004465 } else {
Devang Patela7ec47d2011-05-18 20:35:38 +00004466 if (SimplifyCondBranch(BI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004467 }
4468 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Devang Pateldd14e0f2011-05-18 21:33:11 +00004469 if (SimplifyReturn(RI, Builder)) return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00004470 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
4471 if (SimplifyResume(RI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004472 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Devang Patela7ec47d2011-05-18 20:35:38 +00004473 if (SimplifySwitch(SI, Builder)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004474 } else if (UnreachableInst *UI =
4475 dyn_cast<UnreachableInst>(BB->getTerminator())) {
4476 if (SimplifyUnreachable(UI)) return true;
Chris Lattner1d057612010-12-13 06:36:51 +00004477 } else if (IndirectBrInst *IBI =
4478 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
4479 if (SimplifyIndirectBr(IBI)) return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00004480 }
4481
Chris Lattner031340a2003-08-17 19:41:53 +00004482 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00004483}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004484
4485/// SimplifyCFG - This function is used to do simplification of a CFG. For
4486/// example, it adjusts branches to branches to eliminate the extra hop, it
4487/// eliminates unreachable basic blocks, and does other "peephole" optimization
4488/// of the CFG. It returns true if a modification was made.
4489///
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00004490bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Jingyue Wufc029672014-09-30 22:23:38 +00004491 unsigned BonusInstThreshold,
Hal Finkel60db0582014-09-07 18:57:58 +00004492 const DataLayout *DL, AssumptionTracker *AT) {
Jingyue Wufc029672014-09-30 22:23:38 +00004493 return SimplifyCFGOpt(TTI, BonusInstThreshold, DL, AT).run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00004494}