blob: d3e7d70b1a9f6a7d89082806d00da5de2f3c1c5f [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
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000014#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/DenseMap.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000017#include "llvm/ADT/Optional.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/ADT/STLExtras.h"
James Molloy4de84dd2015-11-04 15:28:04 +000019#include "llvm/ADT/SetOperations.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000022#include "llvm/ADT/SmallSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/Statistic.h"
Peter Collingbourne0609acc2017-02-15 03:01:11 +000025#include "llvm/Analysis/AssumptionCache.h"
Benjamin Kramer7c302602013-11-12 12:24:36 +000026#include "llvm/Analysis/ConstantFolding.h"
Joseph Tremoulet0d808882016-01-05 02:37:41 +000027#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd3e73552013-01-07 03:08:10 +000029#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000031#include "llvm/IR/BasicBlock.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000032#include "llvm/IR/CFG.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000033#include "llvm/IR/CallSite.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000034#include "llvm/IR/Constant.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000035#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Constants.h"
37#include "llvm/IR/DataLayout.h"
Andrea Di Biagiof20c57e2016-12-15 20:01:26 +000038#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DerivedTypes.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000040#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/GlobalVariable.h"
42#include "llvm/IR/IRBuilder.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000043#include "llvm/IR/InstrTypes.h"
44#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000045#include "llvm/IR/Instructions.h"
46#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000047#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/LLVMContext.h"
49#include "llvm/IR/MDBuilder.h"
50#include "llvm/IR/Metadata.h"
51#include "llvm/IR/Module.h"
Chandler Carruth64396b02014-03-04 12:05:47 +000052#include "llvm/IR/NoFolder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000054#include "llvm/IR/PatternMatch.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/Type.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000056#include "llvm/IR/User.h"
57#include "llvm/IR/Value.h"
58#include "llvm/Support/Casting.h"
Evan Chengd983eba2011-01-29 04:46:23 +000059#include "llvm/Support/CommandLine.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000060#include "llvm/Support/Debug.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000061#include "llvm/Support/ErrorHandling.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000062#include "llvm/Support/KnownBits.h"
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000063#include "llvm/Support/MathExtras.h"
Chris Lattnerd7beca32010-12-14 06:17:25 +000064#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000065#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Dehao Chenf6c00832016-05-18 19:44:21 +000066#include "llvm/Transforms/Utils/Local.h"
Jingyue Wufc029672014-09-30 22:23:38 +000067#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattner466a0492002-05-21 20:50:24 +000068#include <algorithm>
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000069#include <cassert>
70#include <climits>
71#include <cstddef>
72#include <cstdint>
73#include <iterator>
Chris Lattner5edb2f32004-10-18 04:07:22 +000074#include <map>
Chandler Carruthed0881b2012-12-03 16:50:05 +000075#include <set>
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +000076#include <utility>
77#include <vector>
78
Chris Lattnerdf3c3422004-01-09 06:12:26 +000079using namespace llvm;
Benjamin Kramer37172222013-07-04 14:22:02 +000080using namespace PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000081
Chandler Carruth964daaa2014-04-22 02:55:47 +000082#define DEBUG_TYPE "simplifycfg"
83
James Molloy1b6207e2015-02-13 10:48:30 +000084// Chosen as 2 so as to be cheap, but still to have enough power to fold
85// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
86// To catch this, we need to fold a compare and a select, hence '2' being the
87// minimum reasonable default.
Dehao Chenf6c00832016-05-18 19:44:21 +000088static cl::opt<unsigned> PHINodeFoldingThreshold(
89 "phi-node-folding-threshold", cl::Hidden, cl::init(2),
90 cl::desc(
91 "Control the amount of phi node folding to perform (default = 2)"));
92
93static cl::opt<bool> DupRet(
94 "simplifycfg-dup-ret", cl::Hidden, cl::init(false),
95 cl::desc("Duplicate return instructions into unconditional branches"));
Peter Collingbourne616044a2011-04-29 18:47:38 +000096
Evan Chengd983eba2011-01-29 04:46:23 +000097static cl::opt<bool>
Dehao Chenf6c00832016-05-18 19:44:21 +000098 SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
99 cl::desc("Sink common instructions down to the end block"));
Manman Ren93ab6492012-09-20 22:37:36 +0000100
Alp Tokercb402912014-01-24 17:20:08 +0000101static cl::opt<bool> HoistCondStores(
102 "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
103 cl::desc("Hoist conditional stores if an unconditional store precedes"));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +0000104
James Molloy4de84dd2015-11-04 15:28:04 +0000105static cl::opt<bool> MergeCondStores(
106 "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
107 cl::desc("Hoist conditional stores even if an unconditional store does not "
108 "precede - hoist multiple conditional stores into a single "
109 "predicated store"));
110
111static cl::opt<bool> MergeCondStoresAggressively(
112 "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
113 cl::desc("When merging conditional stores, do so even if the resultant "
114 "basic blocks are unlikely to be if-converted as a result"));
115
David Majnemerfccf5c62016-01-27 02:59:41 +0000116static cl::opt<bool> SpeculateOneExpensiveInst(
117 "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
118 cl::desc("Allow exactly one expensive instruction to be speculatively "
119 "executed"));
120
Sanjay Patel5264cc72016-01-27 19:22:45 +0000121static cl::opt<unsigned> MaxSpeculationDepth(
122 "max-speculation-depth", cl::Hidden, cl::init(10),
123 cl::desc("Limit maximum recursion depth when calculating costs of "
124 "speculatively executed instructions"));
125
Hans Wennborg39583b82012-09-26 09:44:49 +0000126STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
Dehao Chenf6c00832016-05-18 19:44:21 +0000127STATISTIC(NumLinearMaps,
128 "Number of switch instructions turned into linear mapping");
129STATISTIC(NumLookupTables,
130 "Number of switch instructions turned into lookup tables");
131STATISTIC(
132 NumLookupTablesHoles,
133 "Number of switch instructions turned into lookup tables (holes checked)");
Erik Eckstein0d86c762014-11-27 15:13:14 +0000134STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
Dehao Chenf6c00832016-05-18 19:44:21 +0000135STATISTIC(NumSinkCommons,
136 "Number of common instructions sunk down to the end block");
Hans Wennborgcd3a11f2012-09-26 14:01:53 +0000137STATISTIC(NumSpeculations, "Number of speculative executed instructions");
Evan Cheng89553cc2008-06-12 21:15:59 +0000138
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000139namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000140
Dehao Chenf6c00832016-05-18 19:44:21 +0000141// The first field contains the value that the switch produces when a certain
142// case group is selected, and the second field is a vector containing the
143// cases composing the case group.
144typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000145 SwitchCaseResultVectorTy;
Dehao Chenf6c00832016-05-18 19:44:21 +0000146// The first field contains the phi node that generates a result of the switch
147// and the second field contains the value generated for a certain case in the
148// switch for that PHI.
149typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +0000150
Dehao Chenf6c00832016-05-18 19:44:21 +0000151/// ValueEqualityComparisonCase - Represents a case of a switch.
152struct ValueEqualityComparisonCase {
153 ConstantInt *Value;
154 BasicBlock *Dest;
Eric Christopherb65acc62012-07-02 23:22:21 +0000155
Dehao Chenf6c00832016-05-18 19:44:21 +0000156 ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
Eric Christopherb65acc62012-07-02 23:22:21 +0000157 : Value(Value), Dest(Dest) {}
158
Dehao Chenf6c00832016-05-18 19:44:21 +0000159 bool operator<(ValueEqualityComparisonCase RHS) const {
160 // Comparing pointers is ok as we only rely on the order for uniquing.
161 return Value < RHS.Value;
162 }
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000163
Dehao Chenf6c00832016-05-18 19:44:21 +0000164 bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
165};
Eric Christopherb65acc62012-07-02 23:22:21 +0000166
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000167class SimplifyCFGOpt {
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +0000168 const TargetTransformInfo &TTI;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000169 const DataLayout &DL;
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000170 AssumptionCache *AC;
Hyojin Sung4673f102016-03-29 04:08:57 +0000171 SmallPtrSetImpl<BasicBlock *> *LoopHeaders;
Sanjay Patel0f9b4772017-09-27 14:54:16 +0000172 const SimplifyCFGOptions &Options;
173
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000174 Value *isValueEqualityComparison(TerminatorInst *TI);
Dehao Chenf6c00832016-05-18 19:44:21 +0000175 BasicBlock *GetValueEqualityComparisonCases(
176 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000177 bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
Devang Patela7ec47d2011-05-18 20:35:38 +0000178 BasicBlock *Pred,
179 IRBuilder<> &Builder);
Devang Patel58380552011-05-18 20:53:17 +0000180 bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
181 IRBuilder<> &Builder);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000182
Devang Pateldd14e0f2011-05-18 21:33:11 +0000183 bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000184 bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
Chen Li1689c2f2016-01-10 05:48:01 +0000185 bool SimplifySingleResume(ResumeInst *RI);
186 bool SimplifyCommonResume(ResumeInst *RI);
Andrew Kaylor50e4e862015-09-04 23:39:40 +0000187 bool SimplifyCleanupReturn(CleanupReturnInst *RI);
Chris Lattner25c3af32010-12-13 06:25:44 +0000188 bool SimplifyUnreachable(UnreachableInst *UI);
Devang Patela7ec47d2011-05-18 20:35:38 +0000189 bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000190 bool SimplifyIndirectBr(IndirectBrInst *IBI);
Dehao Chenf6c00832016-05-18 19:44:21 +0000191 bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
192 bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
Chris Lattner25c3af32010-12-13 06:25:44 +0000193
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000194public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000195 SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
Sanjay Patel0f9b4772017-09-27 14:54:16 +0000196 AssumptionCache *AC,
Joerg Sonnenbergerfa736742017-03-26 06:44:08 +0000197 SmallPtrSetImpl<BasicBlock *> *LoopHeaders,
Sanjay Patel0f9b4772017-09-27 14:54:16 +0000198 const SimplifyCFGOptions &Opts)
199 : TTI(TTI), DL(DL), AC(AC), LoopHeaders(LoopHeaders), Options(Opts) {}
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000200
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000201 bool run(BasicBlock *BB);
202};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000203
204} // end anonymous namespace
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000205
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000206/// Return true if it is safe to merge these two
Chris Lattner76dc2042005-08-03 00:19:45 +0000207/// terminator instructions together.
James Molloye6566422016-09-01 07:45:25 +0000208static bool
209SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2,
James Molloy21744682016-09-01 09:01:34 +0000210 SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000211 if (SI1 == SI2)
212 return false; // Can't merge with self!
Andrew Trickf3cf1932012-08-29 21:46:36 +0000213
Chris Lattner76dc2042005-08-03 00:19:45 +0000214 // It is not safe to merge these two switch instructions if they have a common
215 // successor, and if that successor has a PHI node, and if *that* PHI node has
216 // conflicting incoming values from the two switch blocks.
217 BasicBlock *SI1BB = SI1->getParent();
218 BasicBlock *SI2BB = SI2->getParent();
James Molloy3c1137c2016-08-31 13:32:28 +0000219
James Molloye6566422016-09-01 07:45:25 +0000220 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
221 bool Fail = false;
Sanjay Patel5781d842016-03-12 16:52:17 +0000222 for (BasicBlock *Succ : successors(SI2BB))
223 if (SI1Succs.count(Succ))
224 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
Chris Lattner76dc2042005-08-03 00:19:45 +0000225 PHINode *PN = cast<PHINode>(BBI);
226 if (PN->getIncomingValueForBlock(SI1BB) !=
James Molloye6566422016-09-01 07:45:25 +0000227 PN->getIncomingValueForBlock(SI2BB)) {
228 if (FailBlocks)
229 FailBlocks->insert(Succ);
230 Fail = true;
231 }
Chris Lattner76dc2042005-08-03 00:19:45 +0000232 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000233
James Molloye6566422016-09-01 07:45:25 +0000234 return !Fail;
Chris Lattner76dc2042005-08-03 00:19:45 +0000235}
236
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000237/// Return true if it is safe and profitable to merge these two terminator
238/// instructions together, where SI1 is an unconditional branch. PhiNodes will
239/// store all PHI nodes in common successors.
Dehao Chenf6c00832016-05-18 19:44:21 +0000240static bool
241isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2,
242 Instruction *Cond,
243 SmallVectorImpl<PHINode *> &PhiNodes) {
244 if (SI1 == SI2)
245 return false; // Can't merge with self!
Manman Rend33f4ef2012-06-13 05:43:29 +0000246 assert(SI1->isUnconditional() && SI2->isConditional());
247
248 // We fold the unconditional branch if we can easily update all PHI nodes in
Andrew Trickf3cf1932012-08-29 21:46:36 +0000249 // common successors:
Manman Rend33f4ef2012-06-13 05:43:29 +0000250 // 1> We have a constant incoming value for the conditional branch;
251 // 2> We have "Cond" as the incoming value for the unconditional branch;
252 // 3> SI2->getCondition() and Cond have same operands.
253 CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
Dehao Chenf6c00832016-05-18 19:44:21 +0000254 if (!Ci2)
255 return false;
Manman Rend33f4ef2012-06-13 05:43:29 +0000256 if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
257 Cond->getOperand(1) == Ci2->getOperand(1)) &&
258 !(Cond->getOperand(0) == Ci2->getOperand(1) &&
259 Cond->getOperand(1) == Ci2->getOperand(0)))
260 return false;
261
262 BasicBlock *SI1BB = SI1->getParent();
263 BasicBlock *SI2BB = SI2->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000264 SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
Sanjay Patel5781d842016-03-12 16:52:17 +0000265 for (BasicBlock *Succ : successors(SI2BB))
266 if (SI1Succs.count(Succ))
267 for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
Manman Rend33f4ef2012-06-13 05:43:29 +0000268 PHINode *PN = cast<PHINode>(BBI);
269 if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
Nick Lewycky0a045bb2012-06-24 10:15:42 +0000270 !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
Manman Rend33f4ef2012-06-13 05:43:29 +0000271 return false;
272 PhiNodes.push_back(PN);
273 }
274 return true;
275}
276
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000277/// Update PHI nodes in Succ to indicate that there will now be entries in it
278/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
279/// will be the same as those coming in from ExistPred, an existing predecessor
280/// of Succ.
Chris Lattner76dc2042005-08-03 00:19:45 +0000281static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
282 BasicBlock *ExistPred) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000283 if (!isa<PHINode>(Succ->begin()))
284 return; // Quick exit if nothing to do
Andrew Trickf3cf1932012-08-29 21:46:36 +0000285
Chris Lattner80b03a12008-07-13 22:23:11 +0000286 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +0000287 for (BasicBlock::iterator I = Succ->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
Chris Lattner80b03a12008-07-13 22:23:11 +0000288 PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
Chris Lattner76dc2042005-08-03 00:19:45 +0000289}
290
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000291/// Compute an abstract "cost" of speculating the given instruction,
292/// which is assumed to be safe to speculate. TCC_Free means cheap,
293/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
James Molloy7c336572015-02-11 12:15:41 +0000294/// expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000295static unsigned ComputeSpeculationCost(const User *I,
James Molloy7c336572015-02-11 12:15:41 +0000296 const TargetTransformInfo &TTI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000297 assert(isSafeToSpeculativelyExecute(I) &&
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000298 "Instruction is not safe to speculatively execute!");
James Molloy7c336572015-02-11 12:15:41 +0000299 return TTI.getUserCost(I);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +0000300}
Sanjay Patelf9b77632015-09-15 15:24:42 +0000301
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000302/// If we have a merge point of an "if condition" as accepted above,
303/// return true if the specified value dominates the block. We
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000304/// don't handle the true generality of domination here, just a special case
305/// which works well enough for us.
306///
307/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
Peter Collingbournee3511e12011-04-29 18:47:31 +0000308/// see if V (which must be an instruction) and its recursive operands
309/// that do not dominate BB have a combined cost lower than CostRemaining and
310/// are non-trapping. If both are true, the instruction is inserted into the
311/// set and true is returned.
312///
313/// The cost for most non-trapping instructions is defined as 1 except for
314/// Select whose cost is 2.
315///
316/// After this function returns, CostRemaining is decreased by the cost of
317/// V plus its non-dominating operands. If that cost is greater than
318/// CostRemaining, false is returned and CostRemaining is undefined.
Chris Lattner45c35b12004-10-14 05:13:36 +0000319static bool DominatesMergePoint(Value *V, BasicBlock *BB,
Dehao Chenf6c00832016-05-18 19:44:21 +0000320 SmallPtrSetImpl<Instruction *> *AggressiveInsts,
Hal Finkela995f922014-07-10 14:41:31 +0000321 unsigned &CostRemaining,
David Majnemerfccf5c62016-01-27 02:59:41 +0000322 const TargetTransformInfo &TTI,
323 unsigned Depth = 0) {
Sanjay Patel5264cc72016-01-27 19:22:45 +0000324 // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
325 // so limit the recursion depth.
326 // TODO: While this recursion limit does prevent pathological behavior, it
327 // would be better to track visited instructions to avoid cycles.
328 if (Depth == MaxSpeculationDepth)
329 return false;
330
Chris Lattner0aa56562004-04-09 22:50:22 +0000331 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerb8b11592006-10-20 00:42:07 +0000332 if (!I) {
333 // Non-instructions all dominate instructions, but not all constantexprs
334 // can be executed unconditionally.
335 if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
336 if (C->canTrap())
337 return false;
338 return true;
339 }
Chris Lattner0aa56562004-04-09 22:50:22 +0000340 BasicBlock *PBB = I->getParent();
Chris Lattner18d1f192004-02-11 03:36:04 +0000341
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000342 // We don't want to allow weird loops that might have the "if condition" in
Chris Lattner0aa56562004-04-09 22:50:22 +0000343 // the bottom of this block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000344 if (PBB == BB)
345 return false;
Chris Lattner18d1f192004-02-11 03:36:04 +0000346
Chris Lattner0aa56562004-04-09 22:50:22 +0000347 // If this instruction is defined in a block that contains an unconditional
348 // branch to BB, then it must be in the 'conditional' part of the "if
Chris Lattner9ac168d2010-12-14 07:41:39 +0000349 // statement". If not, it definitely dominates the region.
350 BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000351 if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
Chris Lattner9ac168d2010-12-14 07:41:39 +0000352 return true;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000353
Chris Lattner9ac168d2010-12-14 07:41:39 +0000354 // If we aren't allowing aggressive promotion anymore, then don't consider
355 // instructions in the 'if region'.
Dehao Chenf6c00832016-05-18 19:44:21 +0000356 if (!AggressiveInsts)
357 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000358
Peter Collingbournee3511e12011-04-29 18:47:31 +0000359 // If we have seen this instruction before, don't count it again.
Dehao Chenf6c00832016-05-18 19:44:21 +0000360 if (AggressiveInsts->count(I))
361 return true;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000362
Chris Lattner9ac168d2010-12-14 07:41:39 +0000363 // Okay, it looks like the instruction IS in the "condition". Check to
364 // see if it's a cheap instruction to unconditionally compute, and if it
365 // only uses stuff defined outside of the condition. If so, hoist it out.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000366 if (!isSafeToSpeculativelyExecute(I))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000367 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000368
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000369 unsigned Cost = ComputeSpeculationCost(I, TTI);
Chris Lattner0aa56562004-04-09 22:50:22 +0000370
David Majnemerfccf5c62016-01-27 02:59:41 +0000371 // Allow exactly one instruction to be speculated regardless of its cost
372 // (as long as it is safe to do so).
373 // This is intended to flatten the CFG even if the instruction is a division
374 // or other expensive operation. The speculation of an expensive instruction
375 // is expected to be undone in CodeGenPrepare if the speculation has not
376 // enabled further IR optimizations.
377 if (Cost > CostRemaining &&
378 (!SpeculateOneExpensiveInst || !AggressiveInsts->empty() || Depth > 0))
Peter Collingbournee3511e12011-04-29 18:47:31 +0000379 return false;
380
David Majnemerfccf5c62016-01-27 02:59:41 +0000381 // Avoid unsigned wrap.
382 CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
Peter Collingbournee3511e12011-04-29 18:47:31 +0000383
384 // Okay, we can only really hoist these out if their operands do
385 // not take us over the cost threshold.
Chris Lattner9ac168d2010-12-14 07:41:39 +0000386 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
David Majnemerfccf5c62016-01-27 02:59:41 +0000387 if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
388 Depth + 1))
Chris Lattner9ac168d2010-12-14 07:41:39 +0000389 return false;
390 // Okay, it's safe to do this! Remember this instruction.
391 AggressiveInsts->insert(I);
Chris Lattner18d1f192004-02-11 03:36:04 +0000392 return true;
393}
Chris Lattner466a0492002-05-21 20:50:24 +0000394
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000395/// Extract ConstantInt from value, looking through IntToPtr
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000396/// and PointerNullValue. Return NULL if value is not a constant int.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000397static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000398 // Normal constant int.
399 ConstantInt *CI = dyn_cast<ConstantInt>(V);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000400 if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000401 return CI;
402
403 // This is some kind of pointer constant. Turn it into a pointer-sized
404 // ConstantInt if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000405 IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000406
407 // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
408 if (isa<ConstantPointerNull>(V))
409 return ConstantInt::get(PtrTy, 0);
410
411 // IntToPtr const int.
412 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
413 if (CE->getOpcode() == Instruction::IntToPtr)
414 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
415 // The constant is very likely to have the right type already.
416 if (CI->getType() == PtrTy)
417 return CI;
418 else
Dehao Chenf6c00832016-05-18 19:44:21 +0000419 return cast<ConstantInt>(
420 ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000421 }
Craig Topperf40110f2014-04-25 05:29:35 +0000422 return nullptr;
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000423}
424
Mehdi Aminiffd01002014-11-20 22:40:25 +0000425namespace {
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000426
Mehdi Aminiffd01002014-11-20 22:40:25 +0000427/// Given a chain of or (||) or and (&&) comparison of a value against a
428/// constant, this will try to recover the information required for a switch
429/// structure.
430/// It will depth-first traverse the chain of comparison, seeking for patterns
431/// like %a == 12 or %a < 4 and combine them to produce a set of integer
432/// representing the different cases for the switch.
433/// Note that if the chain is composed of '||' it will build the set of elements
434/// that matches the comparisons (i.e. any of this value validate the chain)
435/// while for a chain of '&&' it will build the set elements that make the test
436/// fail.
437struct ConstantComparesGatherer {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000438 const DataLayout &DL;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000439 Value *CompValue; /// Value found for the switch comparison
440 Value *Extra; /// Extra clause to be checked before the switch
441 SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
442 unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000443
Mehdi Aminiffd01002014-11-20 22:40:25 +0000444 /// Construct and compute the result for the comparison instruction Cond
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000445 ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
446 : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
447 gather(Cond);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000448 }
449
Mehdi Aminiffd01002014-11-20 22:40:25 +0000450 /// Prevent copy
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000451 ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000452 ConstantComparesGatherer &
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000453 operator=(const ConstantComparesGatherer &) = delete;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000454
Mehdi Aminiffd01002014-11-20 22:40:25 +0000455private:
Mehdi Aminiffd01002014-11-20 22:40:25 +0000456 /// Try to set the current value used for the comparison, it succeeds only if
457 /// it wasn't set before or if the new value is the same as the old one
458 bool setValueOnce(Value *NewVal) {
Dehao Chenf6c00832016-05-18 19:44:21 +0000459 if (CompValue && CompValue != NewVal)
460 return false;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000461 CompValue = NewVal;
462 return (CompValue != nullptr);
463 }
464
465 /// Try to match Instruction "I" as a comparison against a constant and
466 /// populates the array Vals with the set of values that match (or do not
467 /// match depending on isEQ).
468 /// Return false on failure. On success, the Value the comparison matched
469 /// against is placed in CompValue.
470 /// If CompValue is already set, the function is expected to fail if a match
471 /// is found but the value compared to is different.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000472 bool matchInstruction(Instruction *I, bool isEQ) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000473 // If this is an icmp against a constant, handle this as one of the cases.
474 ICmpInst *ICI;
475 ConstantInt *C;
476 if (!((ICI = dyn_cast<ICmpInst>(I)) &&
Dehao Chenf6c00832016-05-18 19:44:21 +0000477 (C = GetConstantInt(I->getOperand(1), DL)))) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000478 return false;
479 }
480
481 Value *RHSVal;
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000482 const APInt *RHSC;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000483
484 // Pattern match a special case
David Majnemerc761afd2016-01-27 02:43:28 +0000485 // (x & ~2^z) == y --> x == y || x == y|2^z
Mehdi Aminiffd01002014-11-20 22:40:25 +0000486 // This undoes a transformation done by instcombine to fuse 2 compares.
Dehao Chenf6c00832016-05-18 19:44:21 +0000487 if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000488
489 // It's a little bit hard to see why the following transformations are
490 // correct. Here is a CVC3 program to verify them for 64-bit values:
491
492 /*
493 ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
494 x : BITVECTOR(64);
495 y : BITVECTOR(64);
496 z : BITVECTOR(64);
497 mask : BITVECTOR(64) = BVSHL(ONE, z);
498 QUERY( (y & ~mask = y) =>
499 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
500 );
Chuang-Yu Cheng68f7f1c2016-06-24 01:59:00 +0000501 QUERY( (y | mask = y) =>
502 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
503 );
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000504 */
505
506 // Please note that each pattern must be a dual implication (<--> or
507 // iff). One directional implication can create spurious matches. If the
508 // implication is only one-way, an unsatisfiable condition on the left
509 // side can imply a satisfiable condition on the right side. Dual
510 // implication ensures that satisfiable conditions are transformed to
511 // other satisfiable conditions and unsatisfiable conditions are
512 // transformed to other unsatisfiable conditions.
513
514 // Here is a concrete example of a unsatisfiable condition on the left
515 // implying a satisfiable condition on the right:
516 //
517 // mask = (1 << z)
518 // (x & ~mask) == y --> (x == y || x == (y | mask))
519 //
520 // Substituting y = 3, z = 0 yields:
521 // (x & -2) == 3 --> (x == 3 || x == 2)
522
523 // Pattern match a special case:
524 /*
525 QUERY( (y & ~mask = y) =>
526 ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
527 );
528 */
Mehdi Aminiffd01002014-11-20 22:40:25 +0000529 if (match(ICI->getOperand(0),
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000530 m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
531 APInt Mask = ~*RHSC;
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000532 if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000533 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000534 if (!setValueOnce(RHSVal))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000535 return false;
536
537 Vals.push_back(C);
Dehao Chenf6c00832016-05-18 19:44:21 +0000538 Vals.push_back(
Chuang-Yu Chengdbe00d52016-06-16 04:44:25 +0000539 ConstantInt::get(C->getContext(),
540 C->getValue() | Mask));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000541 UsedICmps++;
542 return true;
543 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000544 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000545
Chuang-Yu Cheng68f7f1c2016-06-24 01:59:00 +0000546 // Pattern match a special case:
547 /*
548 QUERY( (y | mask = y) =>
549 ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
550 );
551 */
552 if (match(ICI->getOperand(0),
553 m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
554 APInt Mask = *RHSC;
555 if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
556 // If we already have a value for the switch, it has to match!
557 if (!setValueOnce(RHSVal))
558 return false;
559
560 Vals.push_back(C);
561 Vals.push_back(ConstantInt::get(C->getContext(),
562 C->getValue() & ~Mask));
563 UsedICmps++;
564 return true;
565 }
566 }
567
Mehdi Aminiffd01002014-11-20 22:40:25 +0000568 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000569 if (!setValueOnce(ICI->getOperand(0)))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000570 return false;
571
572 UsedICmps++;
573 Vals.push_back(C);
574 return ICI->getOperand(0);
575 }
576
577 // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
Sanjoy Das7182d362015-03-18 00:41:24 +0000578 ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
579 ICI->getPredicate(), C->getValue());
Mehdi Aminiffd01002014-11-20 22:40:25 +0000580
581 // Shift the range if the compare is fed by an add. This is the range
582 // compare idiom as emitted by instcombine.
583 Value *CandidateVal = I->getOperand(0);
Chuang-Yu Cheng5078f942016-06-17 00:04:39 +0000584 if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
585 Span = Span.subtract(*RHSC);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000586 CandidateVal = RHSVal;
587 }
588
589 // If this is an and/!= check, then we are looking to build the set of
590 // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
591 // x != 0 && x != 1.
592 if (!isEQ)
593 Span = Span.inverse();
594
595 // If there are a ton of values, we don't want to make a ginormous switch.
Craig Topper7e3e7af2017-05-07 22:22:11 +0000596 if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000597 return false;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000598 }
599
600 // If we already have a value for the switch, it has to match!
Dehao Chenf6c00832016-05-18 19:44:21 +0000601 if (!setValueOnce(CandidateVal))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000602 return false;
603
604 // Add all values from the range to the set
605 for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
606 Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000607
608 UsedICmps++;
Mehdi Aminiffd01002014-11-20 22:40:25 +0000609 return true;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000610 }
611
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000612 /// Given a potentially 'or'd or 'and'd together collection of icmp
Mehdi Aminiffd01002014-11-20 22:40:25 +0000613 /// eq/ne/lt/gt instructions that compare a value against a constant, extract
614 /// the value being compared, and stick the list constants into the Vals
615 /// vector.
616 /// One "Extra" case is allowed to differ from the other.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000617 void gather(Value *V) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000618 Instruction *I = dyn_cast<Instruction>(V);
619 bool isEQ = (I->getOpcode() == Instruction::Or);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000620
Mehdi Aminiffd01002014-11-20 22:40:25 +0000621 // Keep a stack (SmallVector for efficiency) for depth-first traversal
622 SmallVector<Value *, 8> DFT;
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000623 SmallPtrSet<Value *, 8> Visited;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000624
Mehdi Aminiffd01002014-11-20 22:40:25 +0000625 // Initialize
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000626 Visited.insert(V);
Mehdi Aminiffd01002014-11-20 22:40:25 +0000627 DFT.push_back(V);
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000628
Dehao Chenf6c00832016-05-18 19:44:21 +0000629 while (!DFT.empty()) {
Mehdi Aminiffd01002014-11-20 22:40:25 +0000630 V = DFT.pop_back_val();
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000631
Mehdi Aminiffd01002014-11-20 22:40:25 +0000632 if (Instruction *I = dyn_cast<Instruction>(V)) {
633 // If it is a || (or && depending on isEQ), process the operands.
634 if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
Gerolf Hoflehner2432bd02016-02-03 23:54:25 +0000635 if (Visited.insert(I->getOperand(1)).second)
636 DFT.push_back(I->getOperand(1));
637 if (Visited.insert(I->getOperand(0)).second)
638 DFT.push_back(I->getOperand(0));
Mehdi Aminiffd01002014-11-20 22:40:25 +0000639 continue;
640 }
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000641
Mehdi Aminiffd01002014-11-20 22:40:25 +0000642 // Try to match the current instruction
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000643 if (matchInstruction(I, isEQ))
Mehdi Aminiffd01002014-11-20 22:40:25 +0000644 // Match succeed, continue the loop
645 continue;
Mehdi Amini9a25cb82014-11-19 20:09:11 +0000646 }
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000647
Mehdi Aminiffd01002014-11-20 22:40:25 +0000648 // One element of the sequence of || (or &&) could not be match as a
649 // comparison against the same value as the others.
650 // We allow only one "Extra" case to be checked before the switch
651 if (!Extra) {
652 Extra = V;
Timur Iskhodzhanov71526a32014-11-20 12:36:43 +0000653 continue;
654 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000655 // Failed to parse a proper sequence, abort now
656 CompValue = nullptr;
657 break;
Chris Lattner5a177e62010-12-13 04:26:26 +0000658 }
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000659 }
Mehdi Aminiffd01002014-11-20 22:40:25 +0000660};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000661
662} // end anonymous namespace
Nick Lewyckye87d54c2011-12-26 20:37:40 +0000663
Eli Friedmancb61afb2008-12-16 20:54:32 +0000664static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000665 Instruction *Cond = nullptr;
Eli Friedmancb61afb2008-12-16 20:54:32 +0000666 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
667 Cond = dyn_cast<Instruction>(SI->getCondition());
668 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
669 if (BI->isConditional())
670 Cond = dyn_cast<Instruction>(BI->getCondition());
Frits van Bommel8fb69ee2010-12-05 18:29:03 +0000671 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
672 Cond = dyn_cast<Instruction>(IBI->getAddress());
Eli Friedmancb61afb2008-12-16 20:54:32 +0000673 }
674
675 TI->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000676 if (Cond)
677 RecursivelyDeleteTriviallyDeadInstructions(Cond);
Eli Friedmancb61afb2008-12-16 20:54:32 +0000678}
679
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000680/// Return true if the specified terminator checks
Chris Lattner8e84c122008-11-27 23:25:44 +0000681/// to see if a value is equal to constant integer value.
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000682Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000683 Value *CV = nullptr;
Chris Lattnera64923a2004-03-16 19:45:22 +0000684 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
685 // Do not permit merging of large switch instructions into their
686 // predecessors unless there is only one predecessor.
Dehao Chenf6c00832016-05-18 19:44:21 +0000687 if (SI->getNumSuccessors() * std::distance(pred_begin(SI->getParent()),
688 pred_end(SI->getParent())) <=
689 128)
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000690 CV = SI->getCondition();
691 } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000692 if (BI->isConditional() && BI->getCondition()->hasOneUse())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000693 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000694 if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000695 CV = ICI->getOperand(0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000696 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000697
698 // Unwrap any lossless ptrtoint cast.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000699 if (CV) {
Matt Arsenaultfa646592013-10-21 18:55:08 +0000700 if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
701 Value *Ptr = PTII->getPointerOperand();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000702 if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
Matt Arsenaultfa646592013-10-21 18:55:08 +0000703 CV = Ptr;
704 }
705 }
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +0000706 return CV;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000707}
708
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000709/// Given a value comparison instruction,
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000710/// decode all of the 'cases' that it represents and return the 'default' block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000711BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
712 TerminatorInst *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000713 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000714 Cases.reserve(SI->getNumCases());
Chandler Carruth927d8e62017-04-12 07:27:28 +0000715 for (auto Case : SI->cases())
716 Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
717 Case.getCaseSuccessor()));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000718 return SI->getDefaultDest();
719 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000720
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000721 BranchInst *BI = cast<BranchInst>(TI);
Reid Spencer266e42b2006-12-23 06:05:41 +0000722 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
Eric Christopherb65acc62012-07-02 23:22:21 +0000723 BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
Dehao Chenf6c00832016-05-18 19:44:21 +0000724 Cases.push_back(ValueEqualityComparisonCase(
725 GetConstantInt(ICI->getOperand(1), DL), Succ));
Reid Spencer266e42b2006-12-23 06:05:41 +0000726 return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000727}
728
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000729/// Given a vector of bb/value pairs, remove any entries
Eric Christopherb65acc62012-07-02 23:22:21 +0000730/// in the list that match the specified block.
Dehao Chenf6c00832016-05-18 19:44:21 +0000731static void
732EliminateBlockCases(BasicBlock *BB,
733 std::vector<ValueEqualityComparisonCase> &Cases) {
Benjamin Kramerc5b06782012-10-14 11:15:42 +0000734 Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
Eric Christopherb65acc62012-07-02 23:22:21 +0000735}
736
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000737/// Return true if there are any keys in C1 that exist in C2 as well.
Dehao Chenf6c00832016-05-18 19:44:21 +0000738static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
739 std::vector<ValueEqualityComparisonCase> &C2) {
Eric Christopherb65acc62012-07-02 23:22:21 +0000740 std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
741
742 // Make V1 be smaller than V2.
743 if (V1->size() > V2->size())
744 std::swap(V1, V2);
745
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000746 if (V1->empty())
Dehao Chenf6c00832016-05-18 19:44:21 +0000747 return false;
Eric Christopherb65acc62012-07-02 23:22:21 +0000748 if (V1->size() == 1) {
749 // Just scan V2.
750 ConstantInt *TheVal = (*V1)[0].Value;
751 for (unsigned i = 0, e = V2->size(); i != e; ++i)
752 if (TheVal == (*V2)[i].Value)
753 return true;
754 }
755
756 // Otherwise, just sort both lists and compare element by element.
757 array_pod_sort(V1->begin(), V1->end());
758 array_pod_sort(V2->begin(), V2->end());
759 unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
760 while (i1 != e1 && i2 != e2) {
761 if ((*V1)[i1].Value == (*V2)[i2].Value)
762 return true;
763 if ((*V1)[i1].Value < (*V2)[i2].Value)
764 ++i1;
765 else
766 ++i2;
767 }
768 return false;
769}
770
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000771/// If TI is known to be a terminator instruction and its block is known to
772/// only have a single predecessor block, check to see if that predecessor is
773/// also a value comparison with the same value, and if that comparison
774/// determines the outcome of this comparison. If so, simplify TI. This does a
775/// very limited form of jump threading.
Dehao Chenf6c00832016-05-18 19:44:21 +0000776bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
777 TerminatorInst *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
Chris Lattner1cca9592005-02-24 06:17:52 +0000778 Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
Dehao Chenf6c00832016-05-18 19:44:21 +0000779 if (!PredVal)
780 return false; // Not a value comparison in predecessor.
Chris Lattner1cca9592005-02-24 06:17:52 +0000781
782 Value *ThisVal = isValueEqualityComparison(TI);
783 assert(ThisVal && "This isn't a value comparison!!");
Dehao Chenf6c00832016-05-18 19:44:21 +0000784 if (ThisVal != PredVal)
785 return false; // Different predicates.
Chris Lattner1cca9592005-02-24 06:17:52 +0000786
Andrew Trick3051aa12012-08-29 21:46:38 +0000787 // TODO: Preserve branch weight metadata, similarly to how
788 // FoldValueComparisonIntoPredecessors preserves it.
789
Chris Lattner1cca9592005-02-24 06:17:52 +0000790 // Find out information about when control will move from Pred to TI's block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000791 std::vector<ValueEqualityComparisonCase> PredCases;
Dehao Chenf6c00832016-05-18 19:44:21 +0000792 BasicBlock *PredDef =
793 GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
794 EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000795
Chris Lattner1cca9592005-02-24 06:17:52 +0000796 // Find information about how control leaves this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000797 std::vector<ValueEqualityComparisonCase> ThisCases;
Chris Lattner1cca9592005-02-24 06:17:52 +0000798 BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
Dehao Chenf6c00832016-05-18 19:44:21 +0000799 EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
Chris Lattner1cca9592005-02-24 06:17:52 +0000800
801 // If TI's block is the default block from Pred's comparison, potentially
802 // simplify TI based on this knowledge.
803 if (PredDef == TI->getParent()) {
804 // If we are here, we know that the value is none of those cases listed in
805 // PredCases. If there are any cases in ThisCases that are in PredCases, we
806 // can simplify TI.
Eric Christopherb65acc62012-07-02 23:22:21 +0000807 if (!ValuesOverlap(PredCases, ThisCases))
Chris Lattner4088e2b2010-12-13 01:47:07 +0000808 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +0000809
Chris Lattner4088e2b2010-12-13 01:47:07 +0000810 if (isa<BranchInst>(TI)) {
811 // Okay, one of the successors of this condbr is dead. Convert it to a
812 // uncond br.
813 assert(ThisCases.size() == 1 && "Branch can only have one case!");
814 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000815 Instruction *NI = Builder.CreateBr(ThisDef);
Dehao Chenf6c00832016-05-18 19:44:21 +0000816 (void)NI;
Chris Lattner1cca9592005-02-24 06:17:52 +0000817
Chris Lattner4088e2b2010-12-13 01:47:07 +0000818 // Remove PHI node entries for the dead edge.
Eric Christopherb65acc62012-07-02 23:22:21 +0000819 ThisCases[0].Dest->removePredecessor(TI->getParent());
Chris Lattner1cca9592005-02-24 06:17:52 +0000820
Chris Lattner4088e2b2010-12-13 01:47:07 +0000821 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Dehao Chenf6c00832016-05-18 19:44:21 +0000822 << "Through successor TI: " << *TI << "Leaving: " << *NI
823 << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000824
Chris Lattner4088e2b2010-12-13 01:47:07 +0000825 EraseTerminatorInstAndDCECond(TI);
826 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000827 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000828
Chris Lattner4088e2b2010-12-13 01:47:07 +0000829 SwitchInst *SI = cast<SwitchInst>(TI);
830 // Okay, TI has cases that are statically dead, prune them away.
Dehao Chenf6c00832016-05-18 19:44:21 +0000831 SmallPtrSet<Constant *, 16> DeadCases;
Eric Christopherb65acc62012-07-02 23:22:21 +0000832 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
833 DeadCases.insert(PredCases[i].Value);
Chris Lattner1cca9592005-02-24 06:17:52 +0000834
David Greene725c7c32010-01-05 01:26:52 +0000835 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Chris Lattner4088e2b2010-12-13 01:47:07 +0000836 << "Through successor TI: " << *TI);
Chris Lattner1cca9592005-02-24 06:17:52 +0000837
Manman Ren8691e522012-09-14 21:53:06 +0000838 // Collect branch weights into a vector.
839 SmallVector<uint32_t, 8> Weights;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000840 MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
Manman Ren8691e522012-09-14 21:53:06 +0000841 bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
842 if (HasWeight)
843 for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
844 ++MD_i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000845 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Manman Ren8691e522012-09-14 21:53:06 +0000846 Weights.push_back(CI->getValue().getZExtValue());
847 }
Eric Christopherb65acc62012-07-02 23:22:21 +0000848 for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
849 --i;
Chandler Carruth927d8e62017-04-12 07:27:28 +0000850 if (DeadCases.count(i->getCaseValue())) {
Manman Ren8691e522012-09-14 21:53:06 +0000851 if (HasWeight) {
Chandler Carruth927d8e62017-04-12 07:27:28 +0000852 std::swap(Weights[i->getCaseIndex() + 1], Weights.back());
Manman Ren8691e522012-09-14 21:53:06 +0000853 Weights.pop_back();
854 }
Chandler Carruth927d8e62017-04-12 07:27:28 +0000855 i->getCaseSuccessor()->removePredecessor(TI->getParent());
Eric Christopherb65acc62012-07-02 23:22:21 +0000856 SI->removeCase(i);
857 }
858 }
Manman Ren97c18762012-10-11 22:28:34 +0000859 if (HasWeight && Weights.size() >= 2)
Manman Ren8691e522012-09-14 21:53:06 +0000860 SI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +0000861 MDBuilder(SI->getParent()->getContext())
862 .createBranchWeights(Weights));
Eric Christopherb65acc62012-07-02 23:22:21 +0000863
864 DEBUG(dbgs() << "Leaving: " << *TI << "\n");
Chris Lattner1cca9592005-02-24 06:17:52 +0000865 return true;
866 }
Andrew Trickf3cf1932012-08-29 21:46:36 +0000867
Chris Lattner4088e2b2010-12-13 01:47:07 +0000868 // Otherwise, TI's block must correspond to some matched value. Find out
869 // which value (or set of values) this is.
Craig Topperf40110f2014-04-25 05:29:35 +0000870 ConstantInt *TIV = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000871 BasicBlock *TIBB = TI->getParent();
Eric Christopherb65acc62012-07-02 23:22:21 +0000872 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
873 if (PredCases[i].Dest == TIBB) {
Craig Topperf40110f2014-04-25 05:29:35 +0000874 if (TIV)
Dehao Chenf6c00832016-05-18 19:44:21 +0000875 return false; // Cannot handle multiple values coming to this block.
Eric Christopherb65acc62012-07-02 23:22:21 +0000876 TIV = PredCases[i].Value;
877 }
878 assert(TIV && "No edge from pred to succ?");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000879
880 // Okay, we found the one constant that our value can be if we get into TI's
881 // BB. Find out which successor will unconditionally be branched to.
Craig Topperf40110f2014-04-25 05:29:35 +0000882 BasicBlock *TheRealDest = nullptr;
Eric Christopherb65acc62012-07-02 23:22:21 +0000883 for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
884 if (ThisCases[i].Value == TIV) {
885 TheRealDest = ThisCases[i].Dest;
886 break;
887 }
Chris Lattner4088e2b2010-12-13 01:47:07 +0000888
889 // If not handled by any explicit cases, it is handled by the default case.
Dehao Chenf6c00832016-05-18 19:44:21 +0000890 if (!TheRealDest)
891 TheRealDest = ThisDef;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000892
893 // Remove PHI node entries for dead edges.
894 BasicBlock *CheckEdge = TheRealDest;
Sanjay Patel5781d842016-03-12 16:52:17 +0000895 for (BasicBlock *Succ : successors(TIBB))
896 if (Succ != CheckEdge)
897 Succ->removePredecessor(TIBB);
Chris Lattner4088e2b2010-12-13 01:47:07 +0000898 else
Craig Topperf40110f2014-04-25 05:29:35 +0000899 CheckEdge = nullptr;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000900
901 // Insert the new branch.
Devang Patela7ec47d2011-05-18 20:35:38 +0000902 Instruction *NI = Builder.CreateBr(TheRealDest);
Dehao Chenf6c00832016-05-18 19:44:21 +0000903 (void)NI;
Chris Lattner4088e2b2010-12-13 01:47:07 +0000904
905 DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
Dehao Chenf6c00832016-05-18 19:44:21 +0000906 << "Through successor TI: " << *TI << "Leaving: " << *NI
907 << "\n");
Chris Lattner4088e2b2010-12-13 01:47:07 +0000908
909 EraseTerminatorInstAndDCECond(TI);
910 return true;
Chris Lattner1cca9592005-02-24 06:17:52 +0000911}
912
Dale Johannesen7f99d222009-03-12 21:01:11 +0000913namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000914
Dehao Chenf6c00832016-05-18 19:44:21 +0000915/// This class implements a stable ordering of constant
916/// integers that does not depend on their address. This is important for
917/// applications that sort ConstantInt's to ensure uniqueness.
918struct ConstantIntOrdering {
919 bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
920 return LHS->getValue().ult(RHS->getValue());
921 }
922};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +0000923
924} // end anonymous namespace
Dale Johannesen5a41b2d2009-03-12 01:00:26 +0000925
Benjamin Kramer8817cca2013-09-22 14:09:50 +0000926static int ConstantIntSortPredicate(ConstantInt *const *P1,
927 ConstantInt *const *P2) {
928 const ConstantInt *LHS = *P1;
929 const ConstantInt *RHS = *P2;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000930 if (LHS == RHS)
Chris Lattnere893e262010-12-15 04:52:41 +0000931 return 0;
Benjamin Kramer7d537ae2016-02-20 10:40:42 +0000932 return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
Chris Lattner7c8e6042010-12-13 02:00:58 +0000933}
934
Dehao Chenf6c00832016-05-18 19:44:21 +0000935static inline bool HasBranchWeights(const Instruction *I) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000936 MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
Andrew Trick3051aa12012-08-29 21:46:38 +0000937 if (ProfMD && ProfMD->getOperand(0))
Dehao Chenf6c00832016-05-18 19:44:21 +0000938 if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
Andrew Trick3051aa12012-08-29 21:46:38 +0000939 return MDS->getString().equals("branch_weights");
940
941 return false;
942}
943
Manman Ren571d9e42012-09-11 17:43:35 +0000944/// Get Weights of a given TerminatorInst, the default weight is at the front
945/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
946/// metadata.
947static void GetBranchWeights(TerminatorInst *TI,
948 SmallVectorImpl<uint64_t> &Weights) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000949 MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
Manman Ren571d9e42012-09-11 17:43:35 +0000950 assert(MD);
951 for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000952 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Manman Ren571d9e42012-09-11 17:43:35 +0000953 Weights.push_back(CI->getValue().getZExtValue());
Andrew Trick3051aa12012-08-29 21:46:38 +0000954 }
955
Manman Ren571d9e42012-09-11 17:43:35 +0000956 // If TI is a conditional eq, the default case is the false case,
957 // and the corresponding branch-weight data is at index 2. We swap the
958 // default weight to be the first entry.
Dehao Chenf6c00832016-05-18 19:44:21 +0000959 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
Manman Ren571d9e42012-09-11 17:43:35 +0000960 assert(Weights.size() == 2);
961 ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
962 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
963 std::swap(Weights.front(), Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +0000964 }
965}
966
Sanjay Patel84a0bf62016-05-06 17:51:37 +0000967/// Keep halving the weights until all can fit in uint32_t.
Andrew Trick3051aa12012-08-29 21:46:38 +0000968static void FitWeights(MutableArrayRef<uint64_t> Weights) {
Benjamin Kramer79da9412014-03-09 14:42:55 +0000969 uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
970 if (Max > UINT_MAX) {
971 unsigned Offset = 32 - countLeadingZeros(Max);
972 for (uint64_t &I : Weights)
973 I >>= Offset;
Manman Renf1cb16e2014-01-27 23:39:03 +0000974 }
Andrew Trick3051aa12012-08-29 21:46:38 +0000975}
976
Sanjay Patel09159b8f2015-06-24 20:40:57 +0000977/// The specified terminator is a value equality comparison instruction
978/// (either a switch or a branch on "X == c").
Bill Wendlingcaf1d222009-01-19 23:43:56 +0000979/// See if any of the predecessors of the terminator block are value comparisons
980/// on the same value. If so, and if safe to do so, fold them together.
Devang Patel58380552011-05-18 20:53:17 +0000981bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
982 IRBuilder<> &Builder) {
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000983 BasicBlock *BB = TI->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +0000984 Value *CV = isValueEqualityComparison(TI); // CondVal
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000985 assert(CV && "Not a comparison?");
986 bool Changed = false;
987
Dehao Chenf6c00832016-05-18 19:44:21 +0000988 SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000989 while (!Preds.empty()) {
Dan Gohman9a6fef02009-05-06 17:22:41 +0000990 BasicBlock *Pred = Preds.pop_back_val();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000991
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000992 // See if the predecessor is a comparison with the same value.
993 TerminatorInst *PTI = Pred->getTerminator();
Dehao Chenf6c00832016-05-18 19:44:21 +0000994 Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
Chris Lattnerd3e6ae22004-02-28 21:28:10 +0000995
James Molloye6566422016-09-01 07:45:25 +0000996 if (PCV == CV && TI != PTI) {
James Molloy21744682016-09-01 09:01:34 +0000997 SmallSetVector<BasicBlock*, 4> FailBlocks;
James Molloye6566422016-09-01 07:45:25 +0000998 if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
999 for (auto *Succ : FailBlocks) {
Benjamin Kramer46f5e2c2017-03-24 14:15:35 +00001000 if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split"))
James Molloye6566422016-09-01 07:45:25 +00001001 return false;
1002 }
1003 }
1004
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001005 // Figure out which 'cases' to copy from SI to PSI.
Eric Christopherb65acc62012-07-02 23:22:21 +00001006 std::vector<ValueEqualityComparisonCase> BBCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001007 BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
1008
Eric Christopherb65acc62012-07-02 23:22:21 +00001009 std::vector<ValueEqualityComparisonCase> PredCases;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001010 BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
1011
1012 // Based on whether the default edge from PTI goes to BB or not, fill in
1013 // PredCases and PredDefault with the new switch cases we would like to
1014 // build.
Dehao Chenf6c00832016-05-18 19:44:21 +00001015 SmallVector<BasicBlock *, 8> NewSuccessors;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001016
Andrew Trick3051aa12012-08-29 21:46:38 +00001017 // Update the branch weight metadata along the way
1018 SmallVector<uint64_t, 8> Weights;
Andrew Trick3051aa12012-08-29 21:46:38 +00001019 bool PredHasWeights = HasBranchWeights(PTI);
1020 bool SuccHasWeights = HasBranchWeights(TI);
1021
Manman Ren5e5049d2012-09-14 19:05:19 +00001022 if (PredHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +00001023 GetBranchWeights(PTI, Weights);
Andrew Trick7656f6d2012-11-15 18:40:31 +00001024 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +00001025 if (Weights.size() != 1 + PredCases.size())
1026 PredHasWeights = SuccHasWeights = false;
1027 } else if (SuccHasWeights)
Andrew Trick3051aa12012-08-29 21:46:38 +00001028 // If there are no predecessor weights but there are successor weights,
1029 // populate Weights with 1, which will later be scaled to the sum of
1030 // successor's weights
1031 Weights.assign(1 + PredCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +00001032
Manman Ren571d9e42012-09-11 17:43:35 +00001033 SmallVector<uint64_t, 8> SuccWeights;
Manman Ren5e5049d2012-09-14 19:05:19 +00001034 if (SuccHasWeights) {
Manman Ren571d9e42012-09-11 17:43:35 +00001035 GetBranchWeights(TI, SuccWeights);
Andrew Trick7656f6d2012-11-15 18:40:31 +00001036 // branch-weight metadata is inconsistent here.
Manman Ren5e5049d2012-09-14 19:05:19 +00001037 if (SuccWeights.size() != 1 + BBCases.size())
1038 PredHasWeights = SuccHasWeights = false;
1039 } else if (PredHasWeights)
Manman Ren571d9e42012-09-11 17:43:35 +00001040 SuccWeights.assign(1 + BBCases.size(), 1);
Andrew Trick3051aa12012-08-29 21:46:38 +00001041
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001042 if (PredDefault == BB) {
1043 // If this is the default destination from PTI, only the edges in TI
1044 // that don't occur in PTI, or that branch to BB will be activated.
Dehao Chenf6c00832016-05-18 19:44:21 +00001045 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +00001046 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1047 if (PredCases[i].Dest != BB)
1048 PTIHandled.insert(PredCases[i].Value);
1049 else {
1050 // The default destination is BB, we don't need explicit targets.
1051 std::swap(PredCases[i], PredCases.back());
Andrew Trick3051aa12012-08-29 21:46:38 +00001052
Manman Ren571d9e42012-09-11 17:43:35 +00001053 if (PredHasWeights || SuccHasWeights) {
1054 // Increase weight for the default case.
Dehao Chenf6c00832016-05-18 19:44:21 +00001055 Weights[0] += Weights[i + 1];
1056 std::swap(Weights[i + 1], Weights.back());
Andrew Trick3051aa12012-08-29 21:46:38 +00001057 Weights.pop_back();
1058 }
1059
Eric Christopherb65acc62012-07-02 23:22:21 +00001060 PredCases.pop_back();
Dehao Chenf6c00832016-05-18 19:44:21 +00001061 --i;
1062 --e;
Eric Christopherb65acc62012-07-02 23:22:21 +00001063 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001064
Eric Christopherb65acc62012-07-02 23:22:21 +00001065 // Reconstruct the new switch statement we will be building.
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001066 if (PredDefault != BBDefault) {
1067 PredDefault->removePredecessor(Pred);
1068 PredDefault = BBDefault;
1069 NewSuccessors.push_back(BBDefault);
1070 }
Andrew Trick3051aa12012-08-29 21:46:38 +00001071
Manman Ren571d9e42012-09-11 17:43:35 +00001072 unsigned CasesFromPred = Weights.size();
1073 uint64_t ValidTotalSuccWeight = 0;
Eric Christopherb65acc62012-07-02 23:22:21 +00001074 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1075 if (!PTIHandled.count(BBCases[i].Value) &&
1076 BBCases[i].Dest != BBDefault) {
1077 PredCases.push_back(BBCases[i]);
1078 NewSuccessors.push_back(BBCases[i].Dest);
Manman Ren571d9e42012-09-11 17:43:35 +00001079 if (SuccHasWeights || PredHasWeights) {
1080 // The default weight is at index 0, so weight for the ith case
1081 // should be at index i+1. Scale the cases from successor by
1082 // PredDefaultWeight (Weights[0]).
Dehao Chenf6c00832016-05-18 19:44:21 +00001083 Weights.push_back(Weights[0] * SuccWeights[i + 1]);
1084 ValidTotalSuccWeight += SuccWeights[i + 1];
Andrew Trick3051aa12012-08-29 21:46:38 +00001085 }
Eric Christopherb65acc62012-07-02 23:22:21 +00001086 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001087
Manman Ren571d9e42012-09-11 17:43:35 +00001088 if (SuccHasWeights || PredHasWeights) {
1089 ValidTotalSuccWeight += SuccWeights[0];
1090 // Scale the cases from predecessor by ValidTotalSuccWeight.
1091 for (unsigned i = 1; i < CasesFromPred; ++i)
1092 Weights[i] *= ValidTotalSuccWeight;
1093 // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
1094 Weights[0] *= SuccWeights[0];
1095 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001096 } else {
1097 // If this is not the default destination from PSI, only the edges
1098 // in SI that occur in PSI with a destination of BB will be
1099 // activated.
Dehao Chenf6c00832016-05-18 19:44:21 +00001100 std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
1101 std::map<ConstantInt *, uint64_t> WeightsForHandled;
Eric Christopherb65acc62012-07-02 23:22:21 +00001102 for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
1103 if (PredCases[i].Dest == BB) {
1104 PTIHandled.insert(PredCases[i].Value);
Manman Rend81b8e82012-09-14 17:29:56 +00001105
1106 if (PredHasWeights || SuccHasWeights) {
Dehao Chenf6c00832016-05-18 19:44:21 +00001107 WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
1108 std::swap(Weights[i + 1], Weights.back());
Manman Rend81b8e82012-09-14 17:29:56 +00001109 Weights.pop_back();
1110 }
1111
Eric Christopherb65acc62012-07-02 23:22:21 +00001112 std::swap(PredCases[i], PredCases.back());
1113 PredCases.pop_back();
Dehao Chenf6c00832016-05-18 19:44:21 +00001114 --i;
1115 --e;
Eric Christopherb65acc62012-07-02 23:22:21 +00001116 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001117
1118 // Okay, now we know which constants were sent to BB from the
1119 // predecessor. Figure out where they will all go now.
Eric Christopherb65acc62012-07-02 23:22:21 +00001120 for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
1121 if (PTIHandled.count(BBCases[i].Value)) {
1122 // If this is one we are capable of getting...
Manman Rend81b8e82012-09-14 17:29:56 +00001123 if (PredHasWeights || SuccHasWeights)
1124 Weights.push_back(WeightsForHandled[BBCases[i].Value]);
Eric Christopherb65acc62012-07-02 23:22:21 +00001125 PredCases.push_back(BBCases[i]);
1126 NewSuccessors.push_back(BBCases[i].Dest);
Dehao Chenf6c00832016-05-18 19:44:21 +00001127 PTIHandled.erase(
1128 BBCases[i].Value); // This constant is taken care of
Eric Christopherb65acc62012-07-02 23:22:21 +00001129 }
1130
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001131 // If there are any constants vectored to BB that TI doesn't handle,
1132 // they must go to the default destination of TI.
Benjamin Kramer135f7352016-06-26 12:28:59 +00001133 for (ConstantInt *I : PTIHandled) {
Andrew Trick90f50292012-11-15 18:40:29 +00001134 if (PredHasWeights || SuccHasWeights)
Benjamin Kramer135f7352016-06-26 12:28:59 +00001135 Weights.push_back(WeightsForHandled[I]);
1136 PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001137 NewSuccessors.push_back(BBDefault);
Eric Christopherb65acc62012-07-02 23:22:21 +00001138 }
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001139 }
1140
1141 // Okay, at this point, we know which new successor Pred will get. Make
1142 // sure we update the number of entries in the PHI nodes for these
1143 // successors.
Sanjay Patelf4b34b72015-09-10 16:25:38 +00001144 for (BasicBlock *NewSuccessor : NewSuccessors)
1145 AddPredecessorToBlock(NewSuccessor, Pred, BB);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001146
Devang Patel58380552011-05-18 20:53:17 +00001147 Builder.SetInsertPoint(PTI);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001148 // Convert pointer to int before we switch.
Duncan Sands19d0b472010-02-16 11:11:14 +00001149 if (CV->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001150 CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
Devang Patel58380552011-05-18 20:53:17 +00001151 "magicptr");
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00001152 }
1153
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001154 // Now that the successors are updated, create the new Switch instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00001155 SwitchInst *NewSI =
1156 Builder.CreateSwitch(CV, PredDefault, PredCases.size());
Devang Patelb849cd52011-05-17 23:29:05 +00001157 NewSI->setDebugLoc(PTI->getDebugLoc());
Sanjay Patel5e7bd912015-09-10 16:15:21 +00001158 for (ValueEqualityComparisonCase &V : PredCases)
1159 NewSI->addCase(V.Value, V.Dest);
Chris Lattner3215bb62005-01-01 16:02:12 +00001160
Andrew Trick3051aa12012-08-29 21:46:38 +00001161 if (PredHasWeights || SuccHasWeights) {
1162 // Halve the weights if any of them cannot fit in an uint32_t
1163 FitWeights(Weights);
1164
1165 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
1166
Dehao Chenf6c00832016-05-18 19:44:21 +00001167 NewSI->setMetadata(
1168 LLVMContext::MD_prof,
1169 MDBuilder(BB->getContext()).createBranchWeights(MDWeights));
Andrew Trick3051aa12012-08-29 21:46:38 +00001170 }
1171
Eli Friedmancb61afb2008-12-16 20:54:32 +00001172 EraseTerminatorInstAndDCECond(PTI);
Chris Lattner3215bb62005-01-01 16:02:12 +00001173
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001174 // Okay, last check. If BB is still a successor of PSI, then we must
1175 // have an infinite loop case. If so, add an infinitely looping block
1176 // to handle the case to preserve the behavior of the code.
Craig Topperf40110f2014-04-25 05:29:35 +00001177 BasicBlock *InfLoopBlock = nullptr;
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001178 for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
1179 if (NewSI->getSuccessor(i) == BB) {
Craig Topperf40110f2014-04-25 05:29:35 +00001180 if (!InfLoopBlock) {
Chris Lattner80b03a12008-07-13 22:23:11 +00001181 // Insert it at the end of the function, because it's either code,
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001182 // or it won't matter if it's hot. :)
Dehao Chenf6c00832016-05-18 19:44:21 +00001183 InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop",
1184 BB->getParent());
Gabor Greife9ecc682008-04-06 20:25:17 +00001185 BranchInst::Create(InfLoopBlock, InfLoopBlock);
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001186 }
1187 NewSI->setSuccessor(i, InfLoopBlock);
1188 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001189
Chris Lattnerd3e6ae22004-02-28 21:28:10 +00001190 Changed = true;
1191 }
1192 }
1193 return Changed;
1194}
1195
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001196// If we would need to insert a select that uses the value of this invoke
1197// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
1198// can't hoist the invoke, as there is nowhere to put the select in this case.
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001199static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
1200 Instruction *I1, Instruction *I2) {
Sanjay Patel5781d842016-03-12 16:52:17 +00001201 for (BasicBlock *Succ : successors(BB1)) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001202 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001203 for (BasicBlock::iterator BBI = Succ->begin();
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001204 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1205 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1206 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001207 if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001208 return false;
1209 }
1210 }
1211 }
1212 return true;
1213}
1214
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001215static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
1216
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001217/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
1218/// in the two blocks up into the branch block. The caller of this function
1219/// guarantees that BI's block dominates BB1 and BB2.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001220static bool HoistThenElseCodeToIf(BranchInst *BI,
Chad Rosier54390052015-02-23 19:15:16 +00001221 const TargetTransformInfo &TTI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001222 // This does very trivial matching, with limited scanning, to find identical
1223 // instructions in the two blocks. In particular, we don't want to get into
1224 // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
1225 // such, we currently just scan for obviously identical instructions in an
1226 // identical order.
Dehao Chenf6c00832016-05-18 19:44:21 +00001227 BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
1228 BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
Chris Lattner389cfac2004-11-30 00:29:14 +00001229
Devang Patelf10e2872009-02-04 00:03:08 +00001230 BasicBlock::iterator BB1_Itr = BB1->begin();
1231 BasicBlock::iterator BB2_Itr = BB2->begin();
1232
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001233 Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001234 // Skip debug info if it is not identical.
1235 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1236 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1237 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1238 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001239 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001240 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001241 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001242 }
Devang Patele48ddf82011-04-07 00:30:15 +00001243 if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001244 (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
Chris Lattner389cfac2004-11-30 00:29:14 +00001245 return false;
1246
Chris Lattner389cfac2004-11-30 00:29:14 +00001247 BasicBlock *BIParent = BI->getParent();
Chris Lattner389cfac2004-11-30 00:29:14 +00001248
David Majnemerc82f27a2013-06-03 20:43:12 +00001249 bool Changed = false;
Chris Lattner389cfac2004-11-30 00:29:14 +00001250 do {
1251 // If we are hoisting the terminator instruction, don't move one (making a
1252 // broken BB), instead clone it, and remove BI.
1253 if (isa<TerminatorInst>(I1))
1254 goto HoistTerminator;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001255
Chad Rosier54390052015-02-23 19:15:16 +00001256 if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
1257 return Changed;
1258
Chris Lattner389cfac2004-11-30 00:29:14 +00001259 // For a normal instruction, we just move one to right before the branch,
1260 // then replace all uses of the other with the first. Finally, we remove
1261 // the now redundant second instruction.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001262 BIParent->getInstList().splice(BI->getIterator(), BB1->getInstList(), I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001263 if (!I2->use_empty())
1264 I2->replaceAllUsesWith(I1);
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +00001265 I1->andIRFlags(I2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001266 unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
1267 LLVMContext::MD_range,
1268 LLVMContext::MD_fpmath,
1269 LLVMContext::MD_invariant_load,
1270 LLVMContext::MD_nonnull,
1271 LLVMContext::MD_invariant_group,
1272 LLVMContext::MD_align,
1273 LLVMContext::MD_dereferenceable,
1274 LLVMContext::MD_dereferenceable_or_null,
1275 LLVMContext::MD_mem_parallel_loop_access};
Rafael Espindolaea46c322014-08-15 15:46:38 +00001276 combineMetadata(I1, I2, KnownIDs);
Dehao Chen87823f82016-09-08 21:53:33 +00001277
Robert Lougherb0124c12017-01-12 21:11:09 +00001278 // I1 and I2 are being combined into a single instruction. Its debug
1279 // location is the merged locations of the original instructions.
1280 if (!isa<CallInst>(I1))
Andrea Di Biagiof20c57e2016-12-15 20:01:26 +00001281 I1->setDebugLoc(
1282 DILocation::getMergedLocation(I1->getDebugLoc(), I2->getDebugLoc()));
Taewook Oh505a25a2017-01-28 07:05:43 +00001283
Chris Lattnerd7beca32010-12-14 06:17:25 +00001284 I2->eraseFromParent();
David Majnemerc82f27a2013-06-03 20:43:12 +00001285 Changed = true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001286
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001287 I1 = &*BB1_Itr++;
1288 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001289 // Skip debug info if it is not identical.
1290 DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
1291 DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
1292 if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
1293 while (isa<DbgInfoIntrinsic>(I1))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001294 I1 = &*BB1_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001295 while (isa<DbgInfoIntrinsic>(I2))
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001296 I2 = &*BB2_Itr++;
Devang Patel197c3522011-04-07 17:27:36 +00001297 }
Devang Patele48ddf82011-04-07 00:30:15 +00001298 } while (I1->isIdenticalToWhenDefined(I2));
Chris Lattner389cfac2004-11-30 00:29:14 +00001299
1300 return true;
1301
1302HoistTerminator:
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001303 // It may not be possible to hoist an invoke.
1304 if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
David Majnemerc82f27a2013-06-03 20:43:12 +00001305 return Changed;
1306
Sanjay Patel5781d842016-03-12 16:52:17 +00001307 for (BasicBlock *Succ : successors(BB1)) {
David Majnemerc82f27a2013-06-03 20:43:12 +00001308 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001309 for (BasicBlock::iterator BBI = Succ->begin();
David Majnemerc82f27a2013-06-03 20:43:12 +00001310 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
1311 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1312 Value *BB2V = PN->getIncomingValueForBlock(BB2);
1313 if (BB1V == BB2V)
1314 continue;
1315
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001316 // Check for passingValueIsAlwaysUndefined here because we would rather
1317 // eliminate undefined control flow then converting it to a select.
1318 if (passingValueIsAlwaysUndefined(BB1V, PN) ||
1319 passingValueIsAlwaysUndefined(BB2V, PN))
Dehao Chenf6c00832016-05-18 19:44:21 +00001320 return Changed;
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001321
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001322 if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001323 return Changed;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001324 if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
David Majnemerc82f27a2013-06-03 20:43:12 +00001325 return Changed;
1326 }
1327 }
Dale Johannesen9df78ee2009-06-15 20:59:27 +00001328
Chris Lattner389cfac2004-11-30 00:29:14 +00001329 // Okay, it is safe to hoist the terminator.
Nick Lewycky42fb7452009-09-27 07:38:41 +00001330 Instruction *NT = I1->clone();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001331 BIParent->getInstList().insert(BI->getIterator(), NT);
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00001332 if (!NT->getType()->isVoidTy()) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001333 I1->replaceAllUsesWith(NT);
1334 I2->replaceAllUsesWith(NT);
Chris Lattner8dd4cae2007-02-11 01:37:51 +00001335 NT->takeName(I1);
Chris Lattner389cfac2004-11-30 00:29:14 +00001336 }
1337
Mehdi Aminiba9fba82016-03-13 21:05:13 +00001338 IRBuilder<NoFolder> Builder(NT);
Chris Lattner389cfac2004-11-30 00:29:14 +00001339 // Hoisting one of the terminators from our successor is a great thing.
1340 // Unfortunately, the successors of the if/else blocks may have PHI nodes in
1341 // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
1342 // nodes, so we insert select instruction to compute the final result.
Dehao Chenf6c00832016-05-18 19:44:21 +00001343 std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
Sanjay Patel5781d842016-03-12 16:52:17 +00001344 for (BasicBlock *Succ : successors(BB1)) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001345 PHINode *PN;
Sanjay Patel5781d842016-03-12 16:52:17 +00001346 for (BasicBlock::iterator BBI = Succ->begin();
Chris Lattner01944572004-11-30 07:47:34 +00001347 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Chris Lattner389cfac2004-11-30 00:29:14 +00001348 Value *BB1V = PN->getIncomingValueForBlock(BB1);
1349 Value *BB2V = PN->getIncomingValueForBlock(BB2);
Dehao Chenf6c00832016-05-18 19:44:21 +00001350 if (BB1V == BB2V)
1351 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00001352
Chris Lattner4088e2b2010-12-13 01:47:07 +00001353 // These values do not agree. Insert a select instruction before NT
1354 // that determines the right value.
1355 SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
Craig Topperf40110f2014-04-25 05:29:35 +00001356 if (!SI)
Dehao Chenf6c00832016-05-18 19:44:21 +00001357 SI = cast<SelectInst>(
1358 Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
1359 BB1V->getName() + "." + BB2V->getName(), BI));
Devang Patel1407fb42011-05-19 20:52:46 +00001360
Chris Lattner4088e2b2010-12-13 01:47:07 +00001361 // Make the PHI node use the select for all incoming values for BB1/BB2
1362 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1363 if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
1364 PN->setIncomingValue(i, SI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001365 }
1366 }
1367
1368 // Update any PHI nodes in our new successors.
Sanjay Patel5781d842016-03-12 16:52:17 +00001369 for (BasicBlock *Succ : successors(BB1))
1370 AddPredecessorToBlock(Succ, BIParent, BB1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001371
Eli Friedmancb61afb2008-12-16 20:54:32 +00001372 EraseTerminatorInstAndDCECond(BI);
Chris Lattner389cfac2004-11-30 00:29:14 +00001373 return true;
1374}
1375
James Molloyeec6df32016-09-01 10:44:35 +00001376// All instructions in Insts belong to different blocks that all unconditionally
1377// branch to a common successor. Analyze each instruction and return true if it
1378// would be possible to sink them into their successor, creating one common
1379// instruction instead. For every value that would be required to be provided by
1380// PHI node (because an operand varies in each input block), add to PHIOperands.
1381static bool canSinkInstructions(
1382 ArrayRef<Instruction *> Insts,
1383 DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
James Molloy5bf21142016-08-22 19:07:15 +00001384 // Prune out obviously bad instructions to move. Any non-store instruction
1385 // must have exactly one use, and we check later that use is by a single,
1386 // common PHI instruction in the successor.
1387 for (auto *I : Insts) {
1388 // These instructions may change or break semantics if moved.
1389 if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
1390 I->getType()->isTokenTy())
1391 return false;
Akira Hatanaka4ec7b202017-01-25 06:21:51 +00001392
1393 // Conservatively return false if I is an inline-asm instruction. Sinking
1394 // and merging inline-asm instructions can potentially create arguments
1395 // that cannot satisfy the inline-asm constraints.
1396 if (const auto *C = dyn_cast<CallInst>(I))
1397 if (C->isInlineAsm())
1398 return false;
1399
James Molloy5bf21142016-08-22 19:07:15 +00001400 // Everything must have only one use too, apart from stores which
1401 // have no uses.
1402 if (!isa<StoreInst>(I) && !I->hasOneUse())
1403 return false;
1404 }
1405
1406 const Instruction *I0 = Insts.front();
1407 for (auto *I : Insts)
1408 if (!I->isSameOperationAs(I0))
1409 return false;
1410
James Molloyeec6df32016-09-01 10:44:35 +00001411 // All instructions in Insts are known to be the same opcode. If they aren't
1412 // stores, check the only user of each is a PHI or in the same block as the
1413 // instruction, because if a user is in the same block as an instruction
1414 // we're contemplating sinking, it must already be determined to be sinkable.
James Molloy5bf21142016-08-22 19:07:15 +00001415 if (!isa<StoreInst>(I0)) {
1416 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
James Molloy6c009c12016-09-07 09:01:22 +00001417 auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
Eric Liu8c7d28b2017-03-15 15:29:42 +00001418 if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
James Molloyeec6df32016-09-01 10:44:35 +00001419 auto *U = cast<Instruction>(*I->user_begin());
Eric Liu8c7d28b2017-03-15 15:29:42 +00001420 return (PNUse &&
1421 PNUse->getParent() == Succ &&
1422 PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
1423 U->getParent() == I->getParent();
James Molloy5bf21142016-08-22 19:07:15 +00001424 }))
1425 return false;
1426 }
1427
Aditya Kumar24f6ad512017-03-16 14:09:18 +00001428 // Because SROA can't handle speculating stores of selects, try not
1429 // to sink loads or stores of allocas when we'd have to create a PHI for
1430 // the address operand. Also, because it is likely that loads or stores
1431 // of allocas will disappear when Mem2Reg/SROA is run, don't sink them.
1432 // This can cause code churn which can have unintended consequences down
1433 // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
1434 // FIXME: This is a workaround for a deficiency in SROA - see
1435 // https://llvm.org/bugs/show_bug.cgi?id=30188
1436 if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
1437 return isa<AllocaInst>(I->getOperand(1));
1438 }))
1439 return false;
1440 if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
1441 return isa<AllocaInst>(I->getOperand(0));
1442 }))
1443 return false;
1444
James Molloy5bf21142016-08-22 19:07:15 +00001445 for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
1446 if (I0->getOperand(OI)->getType()->isTokenTy())
1447 // Don't touch any operand of token type.
1448 return false;
James Molloy104370a2016-09-11 09:00:03 +00001449
James Molloy5bf21142016-08-22 19:07:15 +00001450 auto SameAsI0 = [&I0, OI](const Instruction *I) {
James Molloyeec6df32016-09-01 10:44:35 +00001451 assert(I->getNumOperands() == I0->getNumOperands());
1452 return I->getOperand(OI) == I0->getOperand(OI);
James Molloy5bf21142016-08-22 19:07:15 +00001453 };
1454 if (!all_of(Insts, SameAsI0)) {
1455 if (!canReplaceOperandWithVariable(I0, OI))
1456 // We can't create a PHI from this GEP.
1457 return false;
James Molloy923e98c2016-08-31 10:46:16 +00001458 // Don't create indirect calls! The called value is the final operand.
1459 if ((isa<CallInst>(I0) || isa<InvokeInst>(I0)) && OI == OE - 1) {
James Molloy5bf21142016-08-22 19:07:15 +00001460 // FIXME: if the call was *already* indirect, we should do this.
1461 return false;
James Molloy923e98c2016-08-31 10:46:16 +00001462 }
James Molloyeec6df32016-09-01 10:44:35 +00001463 for (auto *I : Insts)
1464 PHIOperands[I].push_back(I->getOperand(OI));
James Molloy5bf21142016-08-22 19:07:15 +00001465 }
1466 }
1467 return true;
1468}
1469
1470// Assuming canSinkLastInstruction(Blocks) has returned true, sink the last
1471// instruction of every block in Blocks to their common successor, commoning
1472// into one instruction.
James Molloyeec6df32016-09-01 10:44:35 +00001473static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
James Molloy5bf21142016-08-22 19:07:15 +00001474 auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
1475
1476 // canSinkLastInstruction returning true guarantees that every block has at
1477 // least one non-terminator instruction.
1478 SmallVector<Instruction*,4> Insts;
Dehao Chen018a3af2016-10-17 19:28:44 +00001479 for (auto *BB : Blocks) {
1480 Instruction *I = BB->getTerminator();
1481 do {
1482 I = I->getPrevNode();
1483 } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
1484 if (!isa<DbgInfoIntrinsic>(I))
1485 Insts.push_back(I);
1486 }
James Molloy5bf21142016-08-22 19:07:15 +00001487
James Molloyeec6df32016-09-01 10:44:35 +00001488 // The only checking we need to do now is that all users of all instructions
1489 // are the same PHI node. canSinkLastInstruction should have checked this but
1490 // it is slightly over-aggressive - it gets confused by commutative instructions
1491 // so double-check it here.
James Molloy5bf21142016-08-22 19:07:15 +00001492 Instruction *I0 = Insts.front();
James Molloyeec6df32016-09-01 10:44:35 +00001493 if (!isa<StoreInst>(I0)) {
1494 auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
1495 if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
1496 auto *U = cast<Instruction>(*I->user_begin());
1497 return U == PNUse;
1498 }))
1499 return false;
1500 }
Taewook Oh505a25a2017-01-28 07:05:43 +00001501
James Molloyeec6df32016-09-01 10:44:35 +00001502 // We don't need to do any more checking here; canSinkLastInstruction should
1503 // have done it all for us.
James Molloy5bf21142016-08-22 19:07:15 +00001504 SmallVector<Value*, 4> NewOperands;
1505 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
1506 // This check is different to that in canSinkLastInstruction. There, we
1507 // cared about the global view once simplifycfg (and instcombine) have
1508 // completed - it takes into account PHIs that become trivially
1509 // simplifiable. However here we need a more local view; if an operand
1510 // differs we create a PHI and rely on instcombine to clean up the very
1511 // small mess we may make.
1512 bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
1513 return I->getOperand(O) != I0->getOperand(O);
1514 });
1515 if (!NeedPHI) {
1516 NewOperands.push_back(I0->getOperand(O));
1517 continue;
1518 }
1519
1520 // Create a new PHI in the successor block and populate it.
1521 auto *Op = I0->getOperand(O);
1522 assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
1523 auto *PN = PHINode::Create(Op->getType(), Insts.size(),
1524 Op->getName() + ".sink", &BBEnd->front());
1525 for (auto *I : Insts)
1526 PN->addIncoming(I->getOperand(O), I->getParent());
1527 NewOperands.push_back(PN);
1528 }
1529
1530 // Arbitrarily use I0 as the new "common" instruction; remap its operands
1531 // and move it to the start of the successor block.
1532 for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
1533 I0->getOperandUse(O).set(NewOperands[O]);
1534 I0->moveBefore(&*BBEnd->getFirstInsertionPt());
1535
Robert Lougher5bf04162017-01-04 17:40:32 +00001536 // The debug location for the "common" instruction is the merged locations of
1537 // all the commoned instructions. We start with the original location of the
1538 // "common" instruction and iteratively merge each location in the loop below.
Robert Lougher6717a6f2017-01-12 18:33:49 +00001539 const DILocation *Loc = I0->getDebugLoc();
Robert Lougher5bf04162017-01-04 17:40:32 +00001540
1541 // Update metadata and IR flags, and merge debug locations.
James Molloyd13b1232016-08-30 10:56:08 +00001542 for (auto *I : Insts)
James Molloy0efb96a2016-09-19 08:23:08 +00001543 if (I != I0) {
Robert Lougher5bf04162017-01-04 17:40:32 +00001544 Loc = DILocation::getMergedLocation(Loc, I->getDebugLoc());
James Molloyd13b1232016-08-30 10:56:08 +00001545 combineMetadataForCSE(I0, I);
James Molloy0efb96a2016-09-19 08:23:08 +00001546 I0->andIRFlags(I);
1547 }
Robert Lougher5bf04162017-01-04 17:40:32 +00001548 if (!isa<CallInst>(I0))
1549 I0->setDebugLoc(Loc);
James Molloyd13b1232016-08-30 10:56:08 +00001550
James Molloy5bf21142016-08-22 19:07:15 +00001551 if (!isa<StoreInst>(I0)) {
1552 // canSinkLastInstruction checked that all instructions were used by
1553 // one and only one PHI node. Find that now, RAUW it to our common
1554 // instruction and nuke it.
1555 assert(I0->hasOneUse());
1556 auto *PN = cast<PHINode>(*I0->user_begin());
1557 PN->replaceAllUsesWith(I0);
1558 PN->eraseFromParent();
1559 }
1560
1561 // Finally nuke all instructions apart from the common instruction.
1562 for (auto *I : Insts)
1563 if (I != I0)
1564 I->eraseFromParent();
James Molloyeec6df32016-09-01 10:44:35 +00001565
1566 return true;
1567}
1568
1569namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001570
James Molloyeec6df32016-09-01 10:44:35 +00001571 // LockstepReverseIterator - Iterates through instructions
1572 // in a set of blocks in reverse order from the first non-terminator.
1573 // For example (assume all blocks have size n):
1574 // LockstepReverseIterator I([B1, B2, B3]);
1575 // *I-- = [B1[n], B2[n], B3[n]];
1576 // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
1577 // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
1578 // ...
1579 class LockstepReverseIterator {
1580 ArrayRef<BasicBlock*> Blocks;
1581 SmallVector<Instruction*,4> Insts;
1582 bool Fail;
1583 public:
1584 LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) :
1585 Blocks(Blocks) {
1586 reset();
1587 }
1588
1589 void reset() {
1590 Fail = false;
1591 Insts.clear();
1592 for (auto *BB : Blocks) {
Dehao Chen018a3af2016-10-17 19:28:44 +00001593 Instruction *Inst = BB->getTerminator();
1594 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1595 Inst = Inst->getPrevNode();
1596 if (!Inst) {
1597 // Block wasn't big enough.
1598 Fail = true;
1599 return;
James Molloyeec6df32016-09-01 10:44:35 +00001600 }
Dehao Chen018a3af2016-10-17 19:28:44 +00001601 Insts.push_back(Inst);
James Molloyeec6df32016-09-01 10:44:35 +00001602 }
1603 }
1604
1605 bool isValid() const {
1606 return !Fail;
1607 }
Taewook Oh505a25a2017-01-28 07:05:43 +00001608
James Molloyeec6df32016-09-01 10:44:35 +00001609 void operator -- () {
1610 if (Fail)
1611 return;
1612 for (auto *&Inst : Insts) {
Dehao Chen018a3af2016-10-17 19:28:44 +00001613 for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
1614 Inst = Inst->getPrevNode();
Benjamin Kramerd8b07972016-10-15 13:15:05 +00001615 // Already at beginning of block.
1616 if (!Inst) {
James Molloyeec6df32016-09-01 10:44:35 +00001617 Fail = true;
1618 return;
1619 }
James Molloyeec6df32016-09-01 10:44:35 +00001620 }
1621 }
1622
1623 ArrayRef<Instruction*> operator * () const {
1624 return Insts;
1625 }
1626 };
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00001627
1628} // end anonymous namespace
James Molloy5bf21142016-08-22 19:07:15 +00001629
Sanjay Patel09159b8f2015-06-24 20:40:57 +00001630/// Given an unconditional branch that goes to BBEnd,
Manman Ren93ab6492012-09-20 22:37:36 +00001631/// check whether BBEnd has only two predecessors and the other predecessor
1632/// ends with an unconditional branch. If it is true, sink any common code
1633/// in the two predecessors to BBEnd.
1634static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
1635 assert(BI1->isUnconditional());
Manman Ren93ab6492012-09-20 22:37:36 +00001636 BasicBlock *BBEnd = BI1->getSuccessor(0);
1637
James Molloy88cad7e2016-09-01 12:58:13 +00001638 // We support two situations:
1639 // (1) all incoming arcs are unconditional
1640 // (2) one incoming arc is conditional
1641 //
1642 // (2) is very common in switch defaults and
1643 // else-if patterns;
1644 //
1645 // if (a) f(1);
1646 // else if (b) f(2);
1647 //
1648 // produces:
1649 //
1650 // [if]
1651 // / \
1652 // [f(1)] [if]
1653 // | | \
Amaury Sechet2fec7e42017-01-23 15:13:01 +00001654 // | | |
James Molloy88cad7e2016-09-01 12:58:13 +00001655 // | [f(2)]|
1656 // \ | /
1657 // [ end ]
1658 //
1659 // [end] has two unconditional predecessor arcs and one conditional. The
1660 // conditional refers to the implicit empty 'else' arc. This conditional
1661 // arc can also be caused by an empty default block in a switch.
1662 //
1663 // In this case, we attempt to sink code from all *unconditional* arcs.
1664 // If we can sink instructions from these arcs (determined during the scan
1665 // phase below) we insert a common successor for all unconditional arcs and
1666 // connect that to [end], to enable sinking:
1667 //
1668 // [if]
1669 // / \
1670 // [x(1)] [if]
1671 // | | \
1672 // | | \
1673 // | [x(2)] |
1674 // \ / |
1675 // [sink.split] |
1676 // \ /
1677 // [ end ]
1678 //
1679 SmallVector<BasicBlock*,4> UnconditionalPreds;
1680 Instruction *Cond = nullptr;
1681 for (auto *B : predecessors(BBEnd)) {
1682 auto *T = B->getTerminator();
1683 if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional())
1684 UnconditionalPreds.push_back(B);
1685 else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond)
1686 Cond = T;
1687 else
1688 return false;
1689 }
1690 if (UnconditionalPreds.size() < 2)
James Molloy475f4a72016-08-22 18:13:12 +00001691 return false;
Taewook Oh505a25a2017-01-28 07:05:43 +00001692
Manman Ren93ab6492012-09-20 22:37:36 +00001693 bool Changed = false;
James Molloyeec6df32016-09-01 10:44:35 +00001694 // We take a two-step approach to tail sinking. First we scan from the end of
1695 // each block upwards in lockstep. If the n'th instruction from the end of each
1696 // block can be sunk, those instructions are added to ValuesToSink and we
1697 // carry on. If we can sink an instruction but need to PHI-merge some operands
1698 // (because they're not identical in each instruction) we add these to
1699 // PHIOperands.
1700 unsigned ScanIdx = 0;
1701 SmallPtrSet<Value*,4> InstructionsToSink;
1702 DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
James Molloy88cad7e2016-09-01 12:58:13 +00001703 LockstepReverseIterator LRI(UnconditionalPreds);
James Molloyeec6df32016-09-01 10:44:35 +00001704 while (LRI.isValid() &&
1705 canSinkInstructions(*LRI, PHIOperands)) {
1706 DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0] << "\n");
1707 InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
1708 ++ScanIdx;
1709 --LRI;
1710 }
1711
James Molloy18d96e82016-09-11 08:07:30 +00001712 auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
James Molloy88cad7e2016-09-01 12:58:13 +00001713 unsigned NumPHIdValues = 0;
1714 for (auto *I : *LRI)
1715 for (auto *V : PHIOperands[I])
1716 if (InstructionsToSink.count(V) == 0)
1717 ++NumPHIdValues;
1718 DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
1719 unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
1720 if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
1721 NumPHIInsts++;
Taewook Oh505a25a2017-01-28 07:05:43 +00001722
James Molloy88cad7e2016-09-01 12:58:13 +00001723 return NumPHIInsts <= 1;
1724 };
1725
1726 if (ScanIdx > 0 && Cond) {
James Molloy18d96e82016-09-11 08:07:30 +00001727 // Check if we would actually sink anything first! This mutates the CFG and
1728 // adds an extra block. The goal in doing this is to allow instructions that
1729 // couldn't be sunk before to be sunk - obviously, speculatable instructions
1730 // (such as trunc, add) can be sunk and predicated already. So we check that
1731 // we're going to sink at least one non-speculatable instruction.
1732 LRI.reset();
1733 unsigned Idx = 0;
1734 bool Profitable = false;
1735 while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
1736 if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
1737 Profitable = true;
1738 break;
1739 }
1740 --LRI;
1741 ++Idx;
1742 }
1743 if (!Profitable)
James Molloy88cad7e2016-09-01 12:58:13 +00001744 return false;
Taewook Oh505a25a2017-01-28 07:05:43 +00001745
James Molloy88cad7e2016-09-01 12:58:13 +00001746 DEBUG(dbgs() << "SINK: Splitting edge\n");
1747 // We have a conditional edge and we're going to sink some instructions.
1748 // Insert a new block postdominating all blocks we're going to sink from.
1749 if (!SplitBlockPredecessors(BI1->getSuccessor(0), UnconditionalPreds,
1750 ".sink.split"))
1751 // Edges couldn't be split.
1752 return false;
1753 Changed = true;
1754 }
Taewook Oh505a25a2017-01-28 07:05:43 +00001755
James Molloyeec6df32016-09-01 10:44:35 +00001756 // Now that we've analyzed all potential sinking candidates, perform the
1757 // actual sink. We iteratively sink the last non-terminator of the source
1758 // blocks into their common successor unless doing so would require too
1759 // many PHI instructions to be generated (currently only one PHI is allowed
1760 // per sunk instruction).
1761 //
1762 // We can use InstructionsToSink to discount values needing PHI-merging that will
1763 // actually be sunk in a later iteration. This allows us to be more
1764 // aggressive in what we sink. This does allow a false positive where we
1765 // sink presuming a later value will also be sunk, but stop half way through
1766 // and never actually sink it which means we produce more PHIs than intended.
1767 // This is unlikely in practice though.
1768 for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
1769 DEBUG(dbgs() << "SINK: Sink: "
James Molloy88cad7e2016-09-01 12:58:13 +00001770 << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
James Molloyeec6df32016-09-01 10:44:35 +00001771 << "\n");
1772
1773 // Because we've sunk every instruction in turn, the current instruction to
1774 // sink is always at index 0.
James Molloy18d96e82016-09-11 08:07:30 +00001775 LRI.reset();
1776 if (!ProfitableToSinkInstruction(LRI)) {
James Molloyeec6df32016-09-01 10:44:35 +00001777 // Too many PHIs would be created.
James Molloy88cad7e2016-09-01 12:58:13 +00001778 DEBUG(dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
James Molloyeec6df32016-09-01 10:44:35 +00001779 break;
James Molloy88cad7e2016-09-01 12:58:13 +00001780 }
Taewook Oh505a25a2017-01-28 07:05:43 +00001781
James Molloy88cad7e2016-09-01 12:58:13 +00001782 if (!sinkLastInstruction(UnconditionalPreds))
James Molloyeec6df32016-09-01 10:44:35 +00001783 return Changed;
Manman Ren93ab6492012-09-20 22:37:36 +00001784 NumSinkCommons++;
1785 Changed = true;
1786 }
1787 return Changed;
1788}
1789
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001790/// \brief Determine if we can hoist sink a sole store instruction out of a
1791/// conditional block.
1792///
1793/// We are looking for code like the following:
1794/// BrBB:
1795/// store i32 %add, i32* %arrayidx2
1796/// ... // No other stores or function calls (we could be calling a memory
1797/// ... // function).
1798/// %cmp = icmp ult %x, %y
1799/// br i1 %cmp, label %EndBB, label %ThenBB
1800/// ThenBB:
1801/// store i32 %add5, i32* %arrayidx2
1802/// br label EndBB
1803/// EndBB:
1804/// ...
1805/// We are going to transform this into:
1806/// BrBB:
1807/// store i32 %add, i32* %arrayidx2
1808/// ... //
1809/// %cmp = icmp ult %x, %y
1810/// %add.add5 = select i1 %cmp, i32 %add, %add5
1811/// store i32 %add.add5, i32* %arrayidx2
1812/// ...
1813///
1814/// \return The pointer to the value of the previous store if the store can be
1815/// hoisted into the predecessor block. 0 otherwise.
Benjamin Kramerad5c24f2013-05-23 16:09:15 +00001816static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
1817 BasicBlock *StoreBB, BasicBlock *EndBB) {
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001818 StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
1819 if (!StoreToHoist)
Craig Topperf40110f2014-04-25 05:29:35 +00001820 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001821
1822 // Volatile or atomic.
1823 if (!StoreToHoist->isSimple())
Craig Topperf40110f2014-04-25 05:29:35 +00001824 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001825
1826 Value *StorePtr = StoreToHoist->getPointerOperand();
1827
1828 // Look for a store to the same pointer in BrBB.
Hans Wennborg0c3518e2016-05-04 15:40:57 +00001829 unsigned MaxNumInstToLookAt = 9;
David Majnemerd7708772016-06-24 04:05:21 +00001830 for (Instruction &CurI : reverse(*BrBB)) {
1831 if (!MaxNumInstToLookAt)
1832 break;
Hans Wennborg0c3518e2016-05-04 15:40:57 +00001833 // Skip debug info.
1834 if (isa<DbgInfoIntrinsic>(CurI))
1835 continue;
1836 --MaxNumInstToLookAt;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001837
David L Kreitzer96674172016-08-12 21:06:53 +00001838 // Could be calling an instruction that affects memory like free().
David Majnemerd7708772016-06-24 04:05:21 +00001839 if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
Craig Topperf40110f2014-04-25 05:29:35 +00001840 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001841
David Majnemerd7708772016-06-24 04:05:21 +00001842 if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
1843 // Found the previous store make sure it stores to the same location.
1844 if (SI->getPointerOperand() == StorePtr)
1845 // Found the previous store, return its value operand.
1846 return SI->getValueOperand();
Craig Topperf40110f2014-04-25 05:29:35 +00001847 return nullptr; // Unknown store.
David Majnemerd7708772016-06-24 04:05:21 +00001848 }
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001849 }
1850
Craig Topperf40110f2014-04-25 05:29:35 +00001851 return nullptr;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001852}
1853
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001854/// \brief Speculate a conditional basic block flattening the CFG.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001855///
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001856/// Note that this is a very risky transform currently. Speculating
1857/// instructions like this is most often not desirable. Instead, there is an MI
1858/// pass which can do it with full awareness of the resource constraints.
1859/// However, some cases are "obvious" and we should do directly. An example of
1860/// this is speculating a single, reasonably cheap instruction.
1861///
1862/// There is only one distinct advantage to flattening the CFG at the IR level:
1863/// it makes very common but simplistic optimizations such as are common in
1864/// instcombine and the DAG combiner more powerful by removing CFG edges and
1865/// modeling their effects with easier to reason about SSA value graphs.
1866///
1867///
1868/// An illustration of this transform is turning this IR:
1869/// \code
1870/// BB:
1871/// %cmp = icmp ult %x, %y
1872/// br i1 %cmp, label %EndBB, label %ThenBB
1873/// ThenBB:
1874/// %sub = sub %x, %y
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001875/// br label BB2
Chandler Carruth8a4a1662013-01-24 08:05:06 +00001876/// EndBB:
1877/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
1878/// ...
1879/// \endcode
1880///
1881/// Into this IR:
1882/// \code
1883/// BB:
1884/// %cmp = icmp ult %x, %y
1885/// %sub = sub %x, %y
1886/// %cond = select i1 %cmp, 0, %sub
1887/// ...
1888/// \endcode
1889///
1890/// \returns true if the conditional block is removed.
Hal Finkela995f922014-07-10 14:41:31 +00001891static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
James Molloy7c336572015-02-11 12:15:41 +00001892 const TargetTransformInfo &TTI) {
Chandler Carruth1d20c022013-01-24 08:22:40 +00001893 // Be conservative for now. FP select instruction can often be expensive.
1894 Value *BrCond = BI->getCondition();
1895 if (isa<FCmpInst>(BrCond))
1896 return false;
1897
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001898 BasicBlock *BB = BI->getParent();
1899 BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
1900
1901 // If ThenBB is actually on the false edge of the conditional branch, remember
1902 // to swap the select operands later.
1903 bool Invert = false;
1904 if (ThenBB != BI->getSuccessor(0)) {
1905 assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
1906 Invert = true;
1907 }
1908 assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
1909
Chandler Carruthceff2222013-01-25 05:40:09 +00001910 // Keep a count of how many times instructions are used within CondBB when
1911 // they are candidates for sinking into CondBB. Specifically:
1912 // - They are defined in BB, and
1913 // - They have no side effects, and
1914 // - All of their uses are in CondBB.
1915 SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
1916
Chandler Carruth7481ca82013-01-24 11:52:58 +00001917 unsigned SpeculationCost = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00001918 Value *SpeculatedStoreValue = nullptr;
1919 StoreInst *SpeculatedStore = nullptr;
Chandler Carruth7481ca82013-01-24 11:52:58 +00001920 for (BasicBlock::iterator BBI = ThenBB->begin(),
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001921 BBE = std::prev(ThenBB->end());
Devang Patel5aed7762009-03-06 06:00:17 +00001922 BBI != BBE; ++BBI) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00001923 Instruction *I = &*BBI;
Devang Patel5aed7762009-03-06 06:00:17 +00001924 // Skip debug info.
Chandler Carruth7481ca82013-01-24 11:52:58 +00001925 if (isa<DbgInfoIntrinsic>(I))
1926 continue;
Devang Patel5aed7762009-03-06 06:00:17 +00001927
Mark Lacey274f48b2015-04-12 18:18:51 +00001928 // Only speculatively execute a single instruction (not counting the
Chandler Carruth7481ca82013-01-24 11:52:58 +00001929 // terminator) for now.
Chandler Carruth329b5902013-01-27 06:42:03 +00001930 ++SpeculationCost;
1931 if (SpeculationCost > 1)
Devang Patel5aed7762009-03-06 06:00:17 +00001932 return false;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001933
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001934 // Don't hoist the instruction if it's unsafe or expensive.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001935 if (!isSafeToSpeculativelyExecute(I) &&
1936 !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
1937 I, BB, ThenBB, EndBB))))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001938 return false;
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001939 if (!SpeculatedStoreValue &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001940 ComputeSpeculationCost(I, TTI) >
1941 PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001942 return false;
1943
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001944 // Store the store speculation candidate.
1945 if (SpeculatedStoreValue)
1946 SpeculatedStore = cast<StoreInst>(I);
1947
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001948 // Do not hoist the instruction if any of its operands are defined but not
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00001949 // used in BB. The transformation will prevent the operand from
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001950 // being sunk into the use block.
Dehao Chenf6c00832016-05-18 19:44:21 +00001951 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001952 Instruction *OpI = dyn_cast<Instruction>(*i);
Dehao Chenf6c00832016-05-18 19:44:21 +00001953 if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
Chandler Carruthceff2222013-01-25 05:40:09 +00001954 continue; // Not a candidate for sinking.
1955
1956 ++SinkCandidateUseCounts[OpI];
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001957 }
1958 }
Evan Cheng89200c92008-06-07 08:52:29 +00001959
Chandler Carruthceff2222013-01-25 05:40:09 +00001960 // Consider any sink candidates which are only used in CondBB as costs for
1961 // speculation. Note, while we iterate over a DenseMap here, we are summing
1962 // and so iteration order isn't significant.
Dehao Chenf6c00832016-05-18 19:44:21 +00001963 for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
1964 I = SinkCandidateUseCounts.begin(),
1965 E = SinkCandidateUseCounts.end();
Chandler Carruthceff2222013-01-25 05:40:09 +00001966 I != E; ++I)
1967 if (I->first->getNumUses() == I->second) {
Chandler Carruth329b5902013-01-27 06:42:03 +00001968 ++SpeculationCost;
1969 if (SpeculationCost > 1)
Chandler Carruthceff2222013-01-25 05:40:09 +00001970 return false;
1971 }
1972
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001973 // Check that the PHI nodes can be converted to selects.
1974 bool HaveRewritablePHIs = false;
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001975 for (BasicBlock::iterator I = EndBB->begin();
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001976 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001977 Value *OrigV = PN->getIncomingValueForBlock(BB);
1978 Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001979
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001980 // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001981 // Skip PHIs which are trivial.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00001982 if (ThenV == OrigV)
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00001983 continue;
1984
Arnold Schwaighoferd7d010e2014-10-10 01:27:02 +00001985 // Don't convert to selects if we could remove undefined behavior instead.
1986 if (passingValueIsAlwaysUndefined(OrigV, PN) ||
1987 passingValueIsAlwaysUndefined(ThenV, PN))
1988 return false;
1989
Chandler Carruth76aacbd2013-01-24 10:40:51 +00001990 HaveRewritablePHIs = true;
Rafael Espindolaa5e536a2013-06-04 14:11:59 +00001991 ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
1992 ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
1993 if (!OrigCE && !ThenCE)
Chandler Carruth8a210052013-01-24 11:53:01 +00001994 continue; // Known safe and cheap.
1995
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001996 if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
1997 (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
Chandler Carruth8a210052013-01-24 11:53:01 +00001998 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001999 unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
2000 unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
Dehao Chenf6c00832016-05-18 19:44:21 +00002001 unsigned MaxCost =
2002 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
James Molloy7c336572015-02-11 12:15:41 +00002003 if (OrigCost + ThenCost > MaxCost)
Chandler Carruth8a210052013-01-24 11:53:01 +00002004 return false;
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002005
Chandler Carruth01bffaa2013-01-24 12:05:17 +00002006 // Account for the cost of an unfolded ConstantExpr which could end up
2007 // getting expanded into Instructions.
2008 // FIXME: This doesn't account for how many operations are combined in the
Chandler Carruth329b5902013-01-27 06:42:03 +00002009 // constant expression.
2010 ++SpeculationCost;
2011 if (SpeculationCost > 1)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002012 return false;
Evan Cheng89200c92008-06-07 08:52:29 +00002013 }
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002014
2015 // If there are no PHIs to process, bail early. This helps ensure idempotence
2016 // as well.
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002017 if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002018 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002019
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002020 // If we get here, we can hoist the instruction and if-convert.
Chandler Carruthe2a779f2013-01-24 09:59:39 +00002021 DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
Evan Cheng89200c92008-06-07 08:52:29 +00002022
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002023 // Insert a select of the value of the speculated store.
2024 if (SpeculatedStoreValue) {
Mehdi Aminiba9fba82016-03-13 21:05:13 +00002025 IRBuilder<NoFolder> Builder(BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002026 Value *TrueV = SpeculatedStore->getValueOperand();
2027 Value *FalseV = SpeculatedStoreValue;
2028 if (Invert)
2029 std::swap(TrueV, FalseV);
Sanjay Patel796db352016-03-26 23:30:50 +00002030 Value *S = Builder.CreateSelect(
2031 BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI);
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002032 SpeculatedStore->setOperand(0, S);
Taewook Oh505a25a2017-01-28 07:05:43 +00002033 SpeculatedStore->setDebugLoc(
2034 DILocation::getMergedLocation(
2035 BI->getDebugLoc(), SpeculatedStore->getDebugLoc()));
Arnold Schwaighofer474df6d2013-04-29 21:28:24 +00002036 }
2037
Igor Laevsky7310c682015-11-18 14:50:18 +00002038 // Metadata can be dependent on the condition we are hoisting above.
2039 // Conservatively strip all metadata on the instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00002040 for (auto &I : *ThenBB)
Igor Laevsky7310c682015-11-18 14:50:18 +00002041 I.dropUnknownNonDebugMetadata();
2042
Chandler Carruth7481ca82013-01-24 11:52:58 +00002043 // Hoist the instructions.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002044 BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
2045 ThenBB->begin(), std::prev(ThenBB->end()));
Evan Cheng89553cc2008-06-12 21:15:59 +00002046
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002047 // Insert selects and rewrite the PHI operands.
Mehdi Aminiba9fba82016-03-13 21:05:13 +00002048 IRBuilder<NoFolder> Builder(BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002049 for (BasicBlock::iterator I = EndBB->begin();
2050 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2051 unsigned OrigI = PN->getBasicBlockIndex(BB);
2052 unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
2053 Value *OrigV = PN->getIncomingValue(OrigI);
2054 Value *ThenV = PN->getIncomingValue(ThenI);
2055
2056 // Skip PHIs which are trivial.
2057 if (OrigV == ThenV)
2058 continue;
Evan Cheng89200c92008-06-07 08:52:29 +00002059
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002060 // Create a select whose true value is the speculatively executed value and
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002061 // false value is the preexisting value. Swap them if the branch
2062 // destinations were inverted.
2063 Value *TrueV = ThenV, *FalseV = OrigV;
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00002064 if (Invert)
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002065 std::swap(TrueV, FalseV);
Sanjay Patelf11ab052016-04-15 15:32:12 +00002066 Value *V = Builder.CreateSelect(
2067 BrCond, TrueV, FalseV, TrueV->getName() + "." + FalseV->getName(), BI);
Chandler Carruth76aacbd2013-01-24 10:40:51 +00002068 PN->setIncomingValue(OrigI, V);
2069 PN->setIncomingValue(ThenI, V);
Evan Cheng89200c92008-06-07 08:52:29 +00002070 }
2071
Evan Cheng89553cc2008-06-12 21:15:59 +00002072 ++NumSpeculations;
Evan Cheng89200c92008-06-07 08:52:29 +00002073 return true;
2074}
2075
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002076/// Return true if we can thread a branch across this block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002077static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
2078 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Chris Lattner6c701062005-09-20 01:48:40 +00002079 unsigned Size = 0;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002080
Devang Patel84fceff2009-03-10 18:00:05 +00002081 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
Dale Johannesened6f5a82009-03-12 23:18:09 +00002082 if (isa<DbgInfoIntrinsic>(BBI))
2083 continue;
Dehao Chenf6c00832016-05-18 19:44:21 +00002084 if (Size > 10)
2085 return false; // Don't clone large BB's.
Dale Johannesened6f5a82009-03-12 23:18:09 +00002086 ++Size;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002087
Dale Johannesened6f5a82009-03-12 23:18:09 +00002088 // We can only support instructions that do not define values that are
Chris Lattner6c701062005-09-20 01:48:40 +00002089 // live outside of the current basic block.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002090 for (User *U : BBI->users()) {
2091 Instruction *UI = cast<Instruction>(U);
Dehao Chenf6c00832016-05-18 19:44:21 +00002092 if (UI->getParent() != BB || isa<PHINode>(UI))
2093 return false;
Chris Lattner6c701062005-09-20 01:48:40 +00002094 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002095
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002096 // Looks ok, continue checking.
2097 }
Chris Lattner6c701062005-09-20 01:48:40 +00002098
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002099 return true;
2100}
2101
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002102/// If we have a conditional branch on a PHI node value that is defined in the
2103/// same block as the branch and if any PHI entries are constants, thread edges
2104/// corresponding to that entry to be branches to their ultimate destination.
Peter Collingbourne0609acc2017-02-15 03:01:11 +00002105static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL,
2106 AssumptionCache *AC) {
Chris Lattner748f9032005-09-19 23:49:37 +00002107 BasicBlock *BB = BI->getParent();
2108 PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
Chris Lattner049cb442005-09-19 23:57:04 +00002109 // NOTE: we currently cannot transform this case if the PHI node is used
2110 // outside of the block.
Chris Lattnerf0bd8d02005-09-20 00:43:16 +00002111 if (!PN || PN->getParent() != BB || !PN->hasOneUse())
2112 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002113
Chris Lattner748f9032005-09-19 23:49:37 +00002114 // Degenerate case of a single entry PHI.
2115 if (PN->getNumIncomingValues() == 1) {
Chris Lattnerdc3f6f22008-12-03 19:44:02 +00002116 FoldSingleEntryPHINodes(PN->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002117 return true;
Chris Lattner748f9032005-09-19 23:49:37 +00002118 }
2119
2120 // Now we know that this block has multiple preds and two succs.
Dehao Chenf6c00832016-05-18 19:44:21 +00002121 if (!BlockIsSimpleEnoughToThreadThrough(BB))
2122 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002123
Justin Lebardb639492016-02-12 21:01:36 +00002124 // Can't fold blocks that contain noduplicate or convergent calls.
David Majnemer0a16c222016-08-11 21:15:00 +00002125 if (any_of(*BB, [](const Instruction &I) {
Justin Lebardb639492016-02-12 21:01:36 +00002126 const CallInst *CI = dyn_cast<CallInst>(&I);
2127 return CI && (CI->cannotDuplicate() || CI->isConvergent());
2128 }))
2129 return false;
Tom Stellarde1631dd2013-10-21 20:07:30 +00002130
Chris Lattner748f9032005-09-19 23:49:37 +00002131 // Okay, this is a simple enough basic block. See if any phi values are
2132 // constants.
Zhou Sheng75b871f2007-01-11 12:24:14 +00002133 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Chris Lattner4088e2b2010-12-13 01:47:07 +00002134 ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
Dehao Chenf6c00832016-05-18 19:44:21 +00002135 if (!CB || !CB->getType()->isIntegerTy(1))
2136 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002137
Chris Lattner4088e2b2010-12-13 01:47:07 +00002138 // Okay, we now know that all edges from PredBB should be revectored to
2139 // branch to RealDest.
2140 BasicBlock *PredBB = PN->getIncomingBlock(i);
2141 BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002142
Dehao Chenf6c00832016-05-18 19:44:21 +00002143 if (RealDest == BB)
2144 continue; // Skip self loops.
Bill Wendling4f163df2011-06-04 09:42:04 +00002145 // Skip if the predecessor's terminator is an indirect branch.
Dehao Chenf6c00832016-05-18 19:44:21 +00002146 if (isa<IndirectBrInst>(PredBB->getTerminator()))
2147 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002148
Chris Lattner4088e2b2010-12-13 01:47:07 +00002149 // The dest block might have PHI nodes, other predecessors and other
2150 // difficult cases. Instead of being smart about this, just insert a new
2151 // block that jumps to the destination block, effectively splitting
2152 // the edge we are about to create.
Dehao Chenf6c00832016-05-18 19:44:21 +00002153 BasicBlock *EdgeBB =
2154 BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
2155 RealDest->getParent(), RealDest);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002156 BranchInst::Create(RealDest, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002157
Chris Lattner0f4d67b2010-12-14 07:09:42 +00002158 // Update PHI nodes.
2159 AddPredecessorToBlock(RealDest, EdgeBB, BB);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002160
2161 // BB may have instructions that are being threaded over. Clone these
2162 // instructions into EdgeBB. We know that there will be no uses of the
2163 // cloned instructions outside of EdgeBB.
2164 BasicBlock::iterator InsertPt = EdgeBB->begin();
Dehao Chenf6c00832016-05-18 19:44:21 +00002165 DenseMap<Value *, Value *> TranslateMap; // Track translated values.
Chris Lattner4088e2b2010-12-13 01:47:07 +00002166 for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
2167 if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
2168 TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
2169 continue;
2170 }
2171 // Clone the instruction.
2172 Instruction *N = BBI->clone();
Dehao Chenf6c00832016-05-18 19:44:21 +00002173 if (BBI->hasName())
2174 N->setName(BBI->getName() + ".c");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002175
Chris Lattner4088e2b2010-12-13 01:47:07 +00002176 // Update operands due to translation.
Dehao Chenf6c00832016-05-18 19:44:21 +00002177 for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) {
2178 DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002179 if (PI != TranslateMap.end())
2180 *i = PI->second;
2181 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002182
Chris Lattner4088e2b2010-12-13 01:47:07 +00002183 // Check for trivial simplification.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00002184 if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
David Majnemerb8da3a22016-06-25 00:04:10 +00002185 if (!BBI->use_empty())
2186 TranslateMap[&*BBI] = V;
2187 if (!N->mayHaveSideEffects()) {
Reid Kleckner96ab8722017-05-18 17:24:10 +00002188 N->deleteValue(); // Instruction folded away, don't need actual inst
David Majnemerb8da3a22016-06-25 00:04:10 +00002189 N = nullptr;
2190 }
Chris Lattner4088e2b2010-12-13 01:47:07 +00002191 } else {
Chris Lattner4088e2b2010-12-13 01:47:07 +00002192 if (!BBI->use_empty())
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002193 TranslateMap[&*BBI] = N;
Chris Lattner4088e2b2010-12-13 01:47:07 +00002194 }
David Majnemerb8da3a22016-06-25 00:04:10 +00002195 // Insert the new instruction into its new home.
2196 if (N)
2197 EdgeBB->getInstList().insert(InsertPt, N);
Peter Collingbourne0609acc2017-02-15 03:01:11 +00002198
2199 // Register the new instruction with the assumption cache if necessary.
2200 if (auto *II = dyn_cast_or_null<IntrinsicInst>(N))
2201 if (II->getIntrinsicID() == Intrinsic::assume)
2202 AC->registerAssumption(II);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002203 }
2204
2205 // Loop over all of the edges from PredBB to BB, changing them to branch
2206 // to EdgeBB instead.
2207 TerminatorInst *PredBBTI = PredBB->getTerminator();
2208 for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
2209 if (PredBBTI->getSuccessor(i) == BB) {
2210 BB->removePredecessor(PredBB);
2211 PredBBTI->setSuccessor(i, EdgeBB);
2212 }
Bill Wendling4f163df2011-06-04 09:42:04 +00002213
Chris Lattner4088e2b2010-12-13 01:47:07 +00002214 // Recurse, simplifying any other constants.
Peter Collingbourne0609acc2017-02-15 03:01:11 +00002215 return FoldCondBranchOnPHI(BI, DL, AC) | true;
Zhou Sheng75b871f2007-01-11 12:24:14 +00002216 }
Chris Lattner748f9032005-09-19 23:49:37 +00002217
2218 return false;
2219}
2220
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002221/// Given a BB that starts with the specified two-entry PHI node,
2222/// see if we can eliminate it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002223static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
2224 const DataLayout &DL) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002225 // Ok, this is a two entry PHI node. Check to see if this is a simple "if
2226 // statement", which has a very simple dominance structure. Basically, we
2227 // are trying to find the condition that is being branched on, which
2228 // subsequently causes this merge to happen. We really want control
2229 // dependence information for this check, but simplifycfg can't keep it up
2230 // to date, and this catches most of the cases we care about anyway.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002231 BasicBlock *BB = PN->getParent();
2232 BasicBlock *IfTrue, *IfFalse;
2233 Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
Chris Lattner335f0e42010-12-14 08:01:53 +00002234 if (!IfCond ||
2235 // Don't bother if the branch will be constant folded trivially.
2236 isa<ConstantInt>(IfCond))
2237 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002238
Chris Lattner95adf8f12006-11-18 19:19:36 +00002239 // Okay, we found that we can merge this two-entry phi node into a select.
2240 // Doing so would require us to fold *all* two entry phi nodes in this block.
2241 // At some point this becomes non-profitable (particularly if the target
2242 // doesn't support cmov's). Only do this transformation if there are two or
2243 // fewer PHI nodes in this block.
2244 unsigned NumPhis = 0;
2245 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
2246 if (NumPhis > 2)
2247 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002248
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002249 // Loop over the PHI's seeing if we can promote them all to select
2250 // instructions. While we are at it, keep track of the instructions
2251 // that need to be moved to the dominating block.
Dehao Chenf6c00832016-05-18 19:44:21 +00002252 SmallPtrSet<Instruction *, 4> AggressiveInsts;
Peter Collingbourne616044a2011-04-29 18:47:38 +00002253 unsigned MaxCostVal0 = PHINodeFoldingThreshold,
2254 MaxCostVal1 = PHINodeFoldingThreshold;
James Molloy7c336572015-02-11 12:15:41 +00002255 MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
2256 MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002257
Chris Lattner7499b452010-12-14 08:46:09 +00002258 for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
2259 PHINode *PN = cast<PHINode>(II++);
Daniel Berlin4d0fe642017-04-28 19:55:38 +00002260 if (Value *V = SimplifyInstruction(PN, {DL, PN})) {
Chris Lattnerb42d2932010-12-14 07:20:29 +00002261 PN->replaceAllUsesWith(V);
Chris Lattner7499b452010-12-14 08:46:09 +00002262 PN->eraseFromParent();
Chris Lattnerb42d2932010-12-14 07:20:29 +00002263 continue;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002264 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002265
Peter Collingbournee3511e12011-04-29 18:47:31 +00002266 if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002267 MaxCostVal0, TTI) ||
Peter Collingbournee3511e12011-04-29 18:47:31 +00002268 !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002269 MaxCostVal1, TTI))
Chris Lattnerb42d2932010-12-14 07:20:29 +00002270 return false;
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002271 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002272
Sylvestre Ledru35521e22012-07-23 08:51:15 +00002273 // If we folded the first phi, PN dangles at this point. Refresh it. If
Chris Lattner9ac168d2010-12-14 07:41:39 +00002274 // we ran out of PHIs then we simplified them all.
2275 PN = dyn_cast<PHINode>(BB->begin());
Dehao Chenf6c00832016-05-18 19:44:21 +00002276 if (!PN)
2277 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002278
Chris Lattner7499b452010-12-14 08:46:09 +00002279 // Don't fold i1 branches on PHIs which contain binary operators. These can
2280 // often be turned into switches and other things.
2281 if (PN->getType()->isIntegerTy(1) &&
2282 (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
2283 isa<BinaryOperator>(PN->getIncomingValue(1)) ||
2284 isa<BinaryOperator>(IfCond)))
2285 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002286
Sanjay Patel2e002772016-03-12 18:05:53 +00002287 // If all PHI nodes are promotable, check to make sure that all instructions
2288 // in the predecessor blocks can be promoted as well. If not, we won't be able
2289 // to get rid of the control flow, so it's not worth promoting to select
2290 // instructions.
Craig Topperf40110f2014-04-25 05:29:35 +00002291 BasicBlock *DomBlock = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002292 BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
2293 BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
2294 if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002295 IfBlock1 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002296 } else {
2297 DomBlock = *pred_begin(IfBlock1);
Dehao Chenf6c00832016-05-18 19:44:21 +00002298 for (BasicBlock::iterator I = IfBlock1->begin(); !isa<TerminatorInst>(I);
2299 ++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002300 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002301 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00002302 // Because of this, we won't be able to get rid of the control flow, so
2303 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002304 return false;
2305 }
2306 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002307
Chris Lattner9ac168d2010-12-14 07:41:39 +00002308 if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
Craig Topperf40110f2014-04-25 05:29:35 +00002309 IfBlock2 = nullptr;
Chris Lattner9ac168d2010-12-14 07:41:39 +00002310 } else {
2311 DomBlock = *pred_begin(IfBlock2);
Dehao Chenf6c00832016-05-18 19:44:21 +00002312 for (BasicBlock::iterator I = IfBlock2->begin(); !isa<TerminatorInst>(I);
2313 ++I)
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002314 if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002315 // This is not an aggressive instruction that we can promote.
Sanjay Patel2e002772016-03-12 18:05:53 +00002316 // Because of this, we won't be able to get rid of the control flow, so
2317 // the xform is not worth it.
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002318 return false;
2319 }
2320 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002321
Chris Lattner9fd838d2010-12-14 07:23:10 +00002322 DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
Chris Lattner9ac168d2010-12-14 07:41:39 +00002323 << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002324
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002325 // If we can still promote the PHI nodes after this gauntlet of tests,
2326 // do all of the PHI's now.
Chris Lattner7499b452010-12-14 08:46:09 +00002327 Instruction *InsertPt = DomBlock->getTerminator();
Mehdi Aminiba9fba82016-03-13 21:05:13 +00002328 IRBuilder<NoFolder> Builder(InsertPt);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002329
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002330 // Move all 'aggressive' instructions, which are defined in the
2331 // conditional parts of the if's up to the dominating block.
David Majnemere8fd5f92016-08-29 17:14:08 +00002332 if (IfBlock1) {
2333 for (auto &I : *IfBlock1)
2334 I.dropUnknownNonDebugMetadata();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002335 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00002336 IfBlock1->getInstList(), IfBlock1->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002337 IfBlock1->getTerminator()->getIterator());
David Majnemere8fd5f92016-08-29 17:14:08 +00002338 }
2339 if (IfBlock2) {
2340 for (auto &I : *IfBlock2)
2341 I.dropUnknownNonDebugMetadata();
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002342 DomBlock->getInstList().splice(InsertPt->getIterator(),
Chris Lattner4088e2b2010-12-13 01:47:07 +00002343 IfBlock2->getInstList(), IfBlock2->begin(),
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002344 IfBlock2->getTerminator()->getIterator());
David Majnemere8fd5f92016-08-29 17:14:08 +00002345 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002346
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002347 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
2348 // Change the PHI node into a select instruction.
Dehao Chenf6c00832016-05-18 19:44:21 +00002349 Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
Chris Lattner4088e2b2010-12-13 01:47:07 +00002350 Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002351
Sanjay Patel9e23fed2016-03-17 15:30:52 +00002352 Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
2353 PN->replaceAllUsesWith(Sel);
2354 Sel->takeName(PN);
Chris Lattnerd7beca32010-12-14 06:17:25 +00002355 PN->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002356 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002357
Chris Lattner335f0e42010-12-14 08:01:53 +00002358 // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
2359 // has been flattened. Change DomBlock to jump directly to our new block to
2360 // avoid other simplifycfg's kicking in on the diamond.
2361 TerminatorInst *OldTI = DomBlock->getTerminator();
Devang Patel5c810ce2011-05-18 18:16:44 +00002362 Builder.SetInsertPoint(OldTI);
2363 Builder.CreateBr(BB);
Chris Lattner335f0e42010-12-14 08:01:53 +00002364 OldTI->eraseFromParent();
Chris Lattnercc14ebc2005-09-23 06:39:30 +00002365 return true;
2366}
Chris Lattner748f9032005-09-19 23:49:37 +00002367
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002368/// If we found a conditional branch that goes to two returning blocks,
2369/// try to merge them together into one return,
Chris Lattner86bbf332008-04-24 00:01:19 +00002370/// introducing a select if the return values disagree.
Andrew Trickf3cf1932012-08-29 21:46:36 +00002371static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
Devang Pateldd14e0f2011-05-18 21:33:11 +00002372 IRBuilder<> &Builder) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002373 assert(BI->isConditional() && "Must be a conditional branch");
2374 BasicBlock *TrueSucc = BI->getSuccessor(0);
2375 BasicBlock *FalseSucc = BI->getSuccessor(1);
2376 ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
2377 ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002378
Chris Lattner86bbf332008-04-24 00:01:19 +00002379 // Check to ensure both blocks are empty (just a return) or optionally empty
2380 // with PHI nodes. If there are other instructions, merging would cause extra
2381 // computation on one path or the other.
Chris Lattner4088e2b2010-12-13 01:47:07 +00002382 if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00002383 return false;
Chris Lattner4088e2b2010-12-13 01:47:07 +00002384 if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
Devang Patel086b2122009-02-05 00:30:42 +00002385 return false;
Chris Lattner86bbf332008-04-24 00:01:19 +00002386
Devang Pateldd14e0f2011-05-18 21:33:11 +00002387 Builder.SetInsertPoint(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002388 // Okay, we found a branch that is going to two return nodes. If
2389 // there is no return value for this function, just change the
2390 // branch into a return.
2391 if (FalseRet->getNumOperands() == 0) {
2392 TrueSucc->removePredecessor(BI->getParent());
2393 FalseSucc->removePredecessor(BI->getParent());
Devang Pateldd14e0f2011-05-18 21:33:11 +00002394 Builder.CreateRetVoid();
Eli Friedmancb61afb2008-12-16 20:54:32 +00002395 EraseTerminatorInstAndDCECond(BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002396 return true;
2397 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002398
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002399 // Otherwise, figure out what the true and false return values are
2400 // so we can insert a new select instruction.
2401 Value *TrueValue = TrueRet->getReturnValue();
2402 Value *FalseValue = FalseRet->getReturnValue();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002403
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002404 // Unwrap any PHI nodes in the return blocks.
2405 if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
2406 if (TVPN->getParent() == TrueSucc)
2407 TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
2408 if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
2409 if (FVPN->getParent() == FalseSucc)
2410 FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002411
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002412 // In order for this transformation to be safe, we must be able to
2413 // unconditionally execute both operands to the return. This is
2414 // normally the case, but we could have a potentially-trapping
2415 // constant expression that prevents this transformation from being
2416 // safe.
2417 if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
2418 if (TCV->canTrap())
2419 return false;
2420 if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
2421 if (FCV->canTrap())
2422 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002423
Chris Lattner86bbf332008-04-24 00:01:19 +00002424 // Okay, we collected all the mapped values and checked them for sanity, and
2425 // defined to really do this transformation. First, update the CFG.
2426 TrueSucc->removePredecessor(BI->getParent());
2427 FalseSucc->removePredecessor(BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002428
Chris Lattner86bbf332008-04-24 00:01:19 +00002429 // Insert select instructions where needed.
2430 Value *BrCond = BI->getCondition();
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002431 if (TrueValue) {
Chris Lattner86bbf332008-04-24 00:01:19 +00002432 // Insert a select if the results differ.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002433 if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
2434 } else if (isa<UndefValue>(TrueValue)) {
2435 TrueValue = FalseValue;
2436 } else {
Sanjay Patelfacf45a2016-04-27 23:14:12 +00002437 TrueValue =
2438 Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
Chris Lattner86bbf332008-04-24 00:01:19 +00002439 }
Chris Lattner86bbf332008-04-24 00:01:19 +00002440 }
2441
Dehao Chenf6c00832016-05-18 19:44:21 +00002442 Value *RI =
2443 !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
Devang Pateldd14e0f2011-05-18 21:33:11 +00002444
Dehao Chenf6c00832016-05-18 19:44:21 +00002445 (void)RI;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002446
David Greene725c7c32010-01-05 01:26:52 +00002447 DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002448 << "\n " << *BI << "NewRet = " << *RI
Dehao Chenf6c00832016-05-18 19:44:21 +00002449 << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: " << *FalseSucc);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002450
Eli Friedmancb61afb2008-12-16 20:54:32 +00002451 EraseTerminatorInstAndDCECond(BI);
2452
Chris Lattner86bbf332008-04-24 00:01:19 +00002453 return true;
2454}
2455
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002456/// Return true if the given instruction is available
Manman Rend33f4ef2012-06-13 05:43:29 +00002457/// in its predecessor block. If yes, the instruction will be removed.
Benjamin Kramerabbfe692012-07-13 13:25:15 +00002458static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002459 if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
2460 return false;
Benjamin Kramer135f7352016-06-26 12:28:59 +00002461 for (Instruction &I : *PB) {
2462 Instruction *PBI = &I;
Manman Rend33f4ef2012-06-13 05:43:29 +00002463 // Check whether Inst and PBI generate the same value.
2464 if (Inst->isIdenticalTo(PBI)) {
2465 Inst->replaceAllUsesWith(PBI);
2466 Inst->eraseFromParent();
2467 return true;
2468 }
2469 }
2470 return false;
2471}
Nick Lewycky3c3feaf2012-01-25 09:43:14 +00002472
Dehao Chenf16376b2016-05-18 22:41:03 +00002473/// Return true if either PBI or BI has branch weight available, and store
2474/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
2475/// not have branch weight, use 1:1 as its weight.
2476static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
2477 uint64_t &PredTrueWeight,
2478 uint64_t &PredFalseWeight,
2479 uint64_t &SuccTrueWeight,
2480 uint64_t &SuccFalseWeight) {
2481 bool PredHasWeights =
2482 PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
2483 bool SuccHasWeights =
2484 BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
2485 if (PredHasWeights || SuccHasWeights) {
2486 if (!PredHasWeights)
2487 PredTrueWeight = PredFalseWeight = 1;
2488 if (!SuccHasWeights)
2489 SuccTrueWeight = SuccFalseWeight = 1;
2490 return true;
2491 } else {
2492 return false;
2493 }
2494}
2495
Sanjay Patel09159b8f2015-06-24 20:40:57 +00002496/// If this basic block is simple enough, and if a predecessor branches to us
2497/// and one of our successors, fold the block into the predecessor and use
2498/// logical operations to pick the right destination.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002499bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
Chris Lattner80b03a12008-07-13 22:23:11 +00002500 BasicBlock *BB = BI->getParent();
Devang Patel1407fb42011-05-19 20:52:46 +00002501
Craig Topperf40110f2014-04-25 05:29:35 +00002502 Instruction *Cond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002503 if (BI->isConditional())
2504 Cond = dyn_cast<Instruction>(BI->getCondition());
2505 else {
2506 // For unconditional branch, check for a simple CFG pattern, where
2507 // BB has a single predecessor and BB's successor is also its predecessor's
Craig Topper36af40c2017-08-02 02:34:16 +00002508 // successor. If such pattern exists, check for CSE between BB and its
Manman Rend33f4ef2012-06-13 05:43:29 +00002509 // predecessor.
2510 if (BasicBlock *PB = BB->getSinglePredecessor())
2511 if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
2512 if (PBI->isConditional() &&
2513 (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
2514 BI->getSuccessor(0) == PBI->getSuccessor(1))) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002515 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002516 Instruction *Curr = &*I++;
Manman Rend33f4ef2012-06-13 05:43:29 +00002517 if (isa<CmpInst>(Curr)) {
2518 Cond = Curr;
2519 break;
2520 }
2521 // Quit if we can't remove this instruction.
2522 if (!checkCSEInPredecessor(Curr, PB))
2523 return false;
2524 }
2525 }
2526
Craig Topperf40110f2014-04-25 05:29:35 +00002527 if (!Cond)
Manman Rend33f4ef2012-06-13 05:43:29 +00002528 return false;
2529 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002530
Craig Topperf40110f2014-04-25 05:29:35 +00002531 if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
2532 Cond->getParent() != BB || !Cond->hasOneUse())
Sanjay Patel2e002772016-03-12 18:05:53 +00002533 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002534
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002535 // Make sure the instruction after the condition is the cond branch.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002536 BasicBlock::iterator CondIt = ++Cond->getIterator();
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002537
Sanjay Patel0a2ada72014-07-06 23:10:24 +00002538 // Ignore dbg intrinsics.
Dehao Chenf6c00832016-05-18 19:44:21 +00002539 while (isa<DbgInfoIntrinsic>(CondIt))
2540 ++CondIt;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002541
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002542 if (&*CondIt != BI)
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002543 return false;
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002544
Jingyue Wufc029672014-09-30 22:23:38 +00002545 // Only allow this transformation if computing the condition doesn't involve
2546 // too many instructions and these involved instructions can be executed
2547 // unconditionally. We denote all involved instructions except the condition
2548 // as "bonus instructions", and only allow this transformation when the
2549 // number of the bonus instructions does not exceed a certain threshold.
2550 unsigned NumBonusInsts = 0;
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002551 for (auto I = BB->begin(); Cond != &*I; ++I) {
Jingyue Wufc029672014-09-30 22:23:38 +00002552 // Ignore dbg intrinsics.
2553 if (isa<DbgInfoIntrinsic>(I))
2554 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002555 if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
Jingyue Wufc029672014-09-30 22:23:38 +00002556 return false;
2557 // I has only one use and can be executed unconditionally.
2558 Instruction *User = dyn_cast<Instruction>(I->user_back());
2559 if (User == nullptr || User->getParent() != BB)
2560 return false;
2561 // I is used in the same BB. Since BI uses Cond and doesn't have more slots
2562 // to use any other instruction, User must be an instruction between next(I)
2563 // and Cond.
2564 ++NumBonusInsts;
2565 // Early exits once we reach the limit.
2566 if (NumBonusInsts > BonusInstThreshold)
2567 return false;
2568 }
2569
Chris Lattnerea9f1d32009-01-19 23:03:13 +00002570 // Cond is known to be a compare or binary operator. Check to make sure that
2571 // neither operand is a potentially-trapping constant expression.
2572 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
2573 if (CE->canTrap())
2574 return false;
2575 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
2576 if (CE->canTrap())
2577 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002578
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002579 // Finally, don't infinitely unroll conditional loops.
Dehao Chenf6c00832016-05-18 19:44:21 +00002580 BasicBlock *TrueDest = BI->getSuccessor(0);
Craig Topperf40110f2014-04-25 05:29:35 +00002581 BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002582 if (TrueDest == BB || FalseDest == BB)
2583 return false;
Devang Pateld715ec82011-04-06 22:37:20 +00002584
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002585 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
2586 BasicBlock *PredBlock = *PI;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002587 BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
Andrew Trickf3cf1932012-08-29 21:46:36 +00002588
Chris Lattner80b03a12008-07-13 22:23:11 +00002589 // Check that we have two conditional branches. If there is a PHI node in
2590 // the common successor, verify that the same value flows in from both
2591 // blocks.
Dehao Chenf6c00832016-05-18 19:44:21 +00002592 SmallVector<PHINode *, 4> PHIs;
Craig Topperf40110f2014-04-25 05:29:35 +00002593 if (!PBI || PBI->isUnconditional() ||
Dehao Chenf6c00832016-05-18 19:44:21 +00002594 (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
Manman Rend33f4ef2012-06-13 05:43:29 +00002595 (!BI->isConditional() &&
2596 !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002597 continue;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002598
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002599 // Determine if the two branches share a common destination.
Axel Naumann4a127062012-09-17 14:20:57 +00002600 Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002601 bool InvertPredCond = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00002602
Manman Rend33f4ef2012-06-13 05:43:29 +00002603 if (BI->isConditional()) {
Richard Trieu7a083812016-02-18 22:09:30 +00002604 if (PBI->getSuccessor(0) == TrueDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002605 Opc = Instruction::Or;
Richard Trieu7a083812016-02-18 22:09:30 +00002606 } else if (PBI->getSuccessor(1) == FalseDest) {
Manman Rend33f4ef2012-06-13 05:43:29 +00002607 Opc = Instruction::And;
Richard Trieu7a083812016-02-18 22:09:30 +00002608 } else if (PBI->getSuccessor(0) == FalseDest) {
2609 Opc = Instruction::And;
2610 InvertPredCond = true;
2611 } else if (PBI->getSuccessor(1) == TrueDest) {
2612 Opc = Instruction::Or;
2613 InvertPredCond = true;
2614 } else {
Manman Rend33f4ef2012-06-13 05:43:29 +00002615 continue;
Richard Trieu7a083812016-02-18 22:09:30 +00002616 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002617 } else {
2618 if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
2619 continue;
2620 }
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002621
David Greene725c7c32010-01-05 01:26:52 +00002622 DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002623 IRBuilder<> Builder(PBI);
Devang Patel1407fb42011-05-19 20:52:46 +00002624
Chris Lattner55eaae12008-07-13 21:20:19 +00002625 // If we need to invert the condition in the pred block to match, do so now.
2626 if (InvertPredCond) {
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002627 Value *NewCond = PBI->getCondition();
Andrew Trickf3cf1932012-08-29 21:46:36 +00002628
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002629 if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
2630 CmpInst *CI = cast<CmpInst>(NewCond);
2631 CI->setPredicate(CI->getInversePredicate());
2632 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00002633 NewCond =
2634 Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
Chris Lattnerfbeb5582010-12-13 07:00:06 +00002635 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002636
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002637 PBI->setCondition(NewCond);
Nick Lewycky8d302df2011-12-26 20:54:14 +00002638 PBI->swapSuccessors();
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002639 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002640
Jingyue Wufc029672014-09-30 22:23:38 +00002641 // If we have bonus instructions, clone them into the predecessor block.
Sanjay Pateladb110c2015-06-24 20:07:50 +00002642 // Note that there may be multiple predecessor blocks, so we cannot move
Jingyue Wufc029672014-09-30 22:23:38 +00002643 // bonus instructions to a predecessor block.
2644 ValueToValueMapTy VMap; // maps original values to cloned values
2645 // We already make sure Cond is the last instruction before BI. Therefore,
Sanjay Pateladb110c2015-06-24 20:07:50 +00002646 // all instructions before Cond other than DbgInfoIntrinsic are bonus
Jingyue Wufc029672014-09-30 22:23:38 +00002647 // instructions.
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +00002648 for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
Jingyue Wufc029672014-09-30 22:23:38 +00002649 if (isa<DbgInfoIntrinsic>(BonusInst))
2650 continue;
2651 Instruction *NewBonusInst = BonusInst->clone();
2652 RemapInstruction(NewBonusInst, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00002653 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002654 VMap[&*BonusInst] = NewBonusInst;
Rafael Espindolaab73c492014-01-28 16:56:46 +00002655
2656 // If we moved a load, we cannot any longer claim any knowledge about
2657 // its potential value. The previous information might have been valid
2658 // only given the branch precondition.
2659 // For an analogous reason, we must also drop all the metadata whose
2660 // semantics we don't understand.
Adrian Prantlcbdfdb72015-08-20 22:00:30 +00002661 NewBonusInst->dropUnknownNonDebugMetadata();
Rafael Espindolaab73c492014-01-28 16:56:46 +00002662
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002663 PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
2664 NewBonusInst->takeName(&*BonusInst);
Jingyue Wufc029672014-09-30 22:23:38 +00002665 BonusInst->setName(BonusInst->getName() + ".old");
Owen Anderson2cfe9132010-07-14 19:52:16 +00002666 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00002667
Chris Lattner55eaae12008-07-13 21:20:19 +00002668 // Clone Cond into the predecessor basic block, and or/and the
2669 // two conditions together.
Nick Lewycky42fb7452009-09-27 07:38:41 +00002670 Instruction *New = Cond->clone();
Jingyue Wufc029672014-09-30 22:23:38 +00002671 RemapInstruction(New, VMap,
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +00002672 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00002673 PredBlock->getInstList().insert(PBI->getIterator(), New);
Chris Lattner55eaae12008-07-13 21:20:19 +00002674 New->takeName(Cond);
Jingyue Wufc029672014-09-30 22:23:38 +00002675 Cond->setName(New->getName() + ".old");
Andrew Trickf3cf1932012-08-29 21:46:36 +00002676
Manman Rend33f4ef2012-06-13 05:43:29 +00002677 if (BI->isConditional()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002678 Instruction *NewCond = cast<Instruction>(
2679 Builder.CreateBinOp(Opc, PBI->getCondition(), New, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002680 PBI->setCondition(NewCond);
2681
Manman Renbfb9d432012-09-15 00:39:57 +00002682 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Dehao Chenf16376b2016-05-18 22:41:03 +00002683 bool HasWeights =
2684 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
2685 SuccTrueWeight, SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002686 SmallVector<uint64_t, 8> NewWeights;
2687
Manman Rend33f4ef2012-06-13 05:43:29 +00002688 if (PBI->getSuccessor(0) == BB) {
Dehao Chenf16376b2016-05-18 22:41:03 +00002689 if (HasWeights) {
Manman Renbfb9d432012-09-15 00:39:57 +00002690 // PBI: br i1 %x, BB, FalseDest
2691 // BI: br i1 %y, TrueDest, FalseDest
Dehao Chenf6c00832016-05-18 19:44:21 +00002692 // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
Manman Renbfb9d432012-09-15 00:39:57 +00002693 NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
Dehao Chenf6c00832016-05-18 19:44:21 +00002694 // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
Manman Renbfb9d432012-09-15 00:39:57 +00002695 // TrueWeight for PBI * FalseWeight for BI.
2696 // We assume that total weights of a BranchInst can fit into 32 bits.
2697 // Therefore, we will not have overflow using 64-bit arithmetic.
Dehao Chenf6c00832016-05-18 19:44:21 +00002698 NewWeights.push_back(PredFalseWeight *
2699 (SuccFalseWeight + SuccTrueWeight) +
2700 PredTrueWeight * SuccFalseWeight);
Manman Renbfb9d432012-09-15 00:39:57 +00002701 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002702 AddPredecessorToBlock(TrueDest, PredBlock, BB);
2703 PBI->setSuccessor(0, TrueDest);
2704 }
2705 if (PBI->getSuccessor(1) == BB) {
Dehao Chenf16376b2016-05-18 22:41:03 +00002706 if (HasWeights) {
Manman Renbfb9d432012-09-15 00:39:57 +00002707 // PBI: br i1 %x, TrueDest, BB
2708 // BI: br i1 %y, TrueDest, FalseDest
Dehao Chenf6c00832016-05-18 19:44:21 +00002709 // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
Manman Renbfb9d432012-09-15 00:39:57 +00002710 // FalseWeight for PBI * TrueWeight for BI.
Dehao Chenf6c00832016-05-18 19:44:21 +00002711 NewWeights.push_back(PredTrueWeight *
2712 (SuccFalseWeight + SuccTrueWeight) +
2713 PredFalseWeight * SuccTrueWeight);
2714 // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
Manman Renbfb9d432012-09-15 00:39:57 +00002715 NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
2716 }
Manman Rend33f4ef2012-06-13 05:43:29 +00002717 AddPredecessorToBlock(FalseDest, PredBlock, BB);
2718 PBI->setSuccessor(1, FalseDest);
2719 }
Manman Renbfb9d432012-09-15 00:39:57 +00002720 if (NewWeights.size() == 2) {
2721 // Halve the weights if any of them cannot fit in an uint32_t
2722 FitWeights(NewWeights);
2723
Dehao Chenf6c00832016-05-18 19:44:21 +00002724 SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
2725 NewWeights.end());
2726 PBI->setMetadata(
2727 LLVMContext::MD_prof,
2728 MDBuilder(BI->getContext()).createBranchWeights(MDWeights));
Manman Renbfb9d432012-09-15 00:39:57 +00002729 } else
Craig Topperf40110f2014-04-25 05:29:35 +00002730 PBI->setMetadata(LLVMContext::MD_prof, nullptr);
Manman Rend33f4ef2012-06-13 05:43:29 +00002731 } else {
2732 // Update PHI nodes in the common successors.
2733 for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
Nick Lewycky0a045bb2012-06-24 10:15:42 +00002734 ConstantInt *PBI_C = cast<ConstantInt>(
Dehao Chenf6c00832016-05-18 19:44:21 +00002735 PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
Manman Rend33f4ef2012-06-13 05:43:29 +00002736 assert(PBI_C->getType()->isIntegerTy(1));
Craig Topperf40110f2014-04-25 05:29:35 +00002737 Instruction *MergedCond = nullptr;
Manman Rend33f4ef2012-06-13 05:43:29 +00002738 if (PBI->getSuccessor(0) == TrueDest) {
2739 // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
2740 // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
2741 // is false: !PBI_Cond and BI_Value
Dehao Chenf6c00832016-05-18 19:44:21 +00002742 Instruction *NotCond = cast<Instruction>(
2743 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2744 MergedCond = cast<Instruction>(
2745 Builder.CreateBinOp(Instruction::And, NotCond, New, "and.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002746 if (PBI_C->isOne())
Dehao Chenf6c00832016-05-18 19:44:21 +00002747 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2748 Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002749 } else {
2750 // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
2751 // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
2752 // is false: PBI_Cond and BI_Value
Dehao Chenf6c00832016-05-18 19:44:21 +00002753 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2754 Instruction::And, PBI->getCondition(), New, "and.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002755 if (PBI_C->isOne()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00002756 Instruction *NotCond = cast<Instruction>(
2757 Builder.CreateNot(PBI->getCondition(), "not.cond"));
2758 MergedCond = cast<Instruction>(Builder.CreateBinOp(
2759 Instruction::Or, NotCond, MergedCond, "or.cond"));
Manman Rend33f4ef2012-06-13 05:43:29 +00002760 }
2761 }
2762 // Update PHI Node.
2763 PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
2764 MergedCond);
2765 }
2766 // Change PBI from Conditional to Unconditional.
2767 BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
2768 EraseTerminatorInstAndDCECond(PBI);
2769 PBI = New_PBI;
Chris Lattner55eaae12008-07-13 21:20:19 +00002770 }
Devang Pateld715ec82011-04-06 22:37:20 +00002771
Michael Kuperstein3ca147e2016-12-16 21:23:59 +00002772 // If BI was a loop latch, it may have had associated loop metadata.
2773 // We need to copy it to the new latch, that is, PBI.
2774 if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
2775 PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
2776
Nick Lewyckyc554a9b2011-12-27 04:31:52 +00002777 // TODO: If BB is reachable from all paths through PredBlock, then we
2778 // could replace PBI's branch probabilities with BI's.
2779
Chris Lattnerfba5cdf2011-04-14 02:44:53 +00002780 // Copy any debug value intrinsics into the end of PredBlock.
Benjamin Kramer135f7352016-06-26 12:28:59 +00002781 for (Instruction &I : *BB)
2782 if (isa<DbgInfoIntrinsic>(I))
2783 I.clone()->insertBefore(PBI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00002784
Chris Lattner5a9d59d2010-12-14 05:57:30 +00002785 return true;
Chris Lattner2e25b8f2008-07-13 21:12:01 +00002786 }
2787 return false;
2788}
2789
James Molloy4de84dd2015-11-04 15:28:04 +00002790// If there is only one store in BB1 and BB2, return it, otherwise return
2791// nullptr.
2792static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
2793 StoreInst *S = nullptr;
2794 for (auto *BB : {BB1, BB2}) {
2795 if (!BB)
2796 continue;
2797 for (auto &I : *BB)
2798 if (auto *SI = dyn_cast<StoreInst>(&I)) {
2799 if (S)
2800 // Multiple stores seen.
2801 return nullptr;
2802 else
2803 S = SI;
2804 }
2805 }
2806 return S;
2807}
2808
2809static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
2810 Value *AlternativeV = nullptr) {
2811 // PHI is going to be a PHI node that allows the value V that is defined in
2812 // BB to be referenced in BB's only successor.
2813 //
2814 // If AlternativeV is nullptr, the only value we care about in PHI is V. It
2815 // doesn't matter to us what the other operand is (it'll never get used). We
2816 // could just create a new PHI with an undef incoming value, but that could
2817 // increase register pressure if EarlyCSE/InstCombine can't fold it with some
2818 // other PHI. So here we directly look for some PHI in BB's successor with V
2819 // as an incoming operand. If we find one, we use it, else we create a new
2820 // one.
2821 //
2822 // If AlternativeV is not nullptr, we care about both incoming values in PHI.
2823 // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
2824 // where OtherBB is the single other predecessor of BB's only successor.
2825 PHINode *PHI = nullptr;
2826 BasicBlock *Succ = BB->getSingleSuccessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00002827
James Molloy4de84dd2015-11-04 15:28:04 +00002828 for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
2829 if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
2830 PHI = cast<PHINode>(I);
2831 if (!AlternativeV)
2832 break;
2833
2834 assert(std::distance(pred_begin(Succ), pred_end(Succ)) == 2);
2835 auto PredI = pred_begin(Succ);
2836 BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
2837 if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
2838 break;
2839 PHI = nullptr;
2840 }
2841 if (PHI)
2842 return PHI;
2843
James Molloy3d21dcf2015-12-16 14:12:44 +00002844 // If V is not an instruction defined in BB, just return it.
2845 if (!AlternativeV &&
2846 (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
2847 return V;
2848
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002849 PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
James Molloy4de84dd2015-11-04 15:28:04 +00002850 PHI->addIncoming(V, BB);
2851 for (BasicBlock *PredBB : predecessors(Succ))
2852 if (PredBB != BB)
Dehao Chenf6c00832016-05-18 19:44:21 +00002853 PHI->addIncoming(
2854 AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
James Molloy4de84dd2015-11-04 15:28:04 +00002855 return PHI;
2856}
2857
2858static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
2859 BasicBlock *QTB, BasicBlock *QFB,
2860 BasicBlock *PostBB, Value *Address,
Alexey Bataev978e2e42017-08-29 20:06:24 +00002861 bool InvertPCond, bool InvertQCond,
2862 const DataLayout &DL) {
James Molloy4de84dd2015-11-04 15:28:04 +00002863 auto IsaBitcastOfPointerType = [](const Instruction &I) {
2864 return Operator::getOpcode(&I) == Instruction::BitCast &&
2865 I.getType()->isPointerTy();
2866 };
2867
2868 // If we're not in aggressive mode, we only optimize if we have some
2869 // confidence that by optimizing we'll allow P and/or Q to be if-converted.
2870 auto IsWorthwhile = [&](BasicBlock *BB) {
2871 if (!BB)
2872 return true;
2873 // Heuristic: if the block can be if-converted/phi-folded and the
2874 // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
2875 // thread this store.
James Molloy9e959ac2015-11-05 08:40:19 +00002876 unsigned N = 0;
2877 for (auto &I : *BB) {
2878 // Cheap instructions viable for folding.
2879 if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
2880 isa<StoreInst>(I))
2881 ++N;
2882 // Free instructions.
2883 else if (isa<TerminatorInst>(I) || isa<DbgInfoIntrinsic>(I) ||
2884 IsaBitcastOfPointerType(I))
2885 continue;
2886 else
James Molloy4de84dd2015-11-04 15:28:04 +00002887 return false;
James Molloy9e959ac2015-11-05 08:40:19 +00002888 }
2889 return N <= PHINodeFoldingThreshold;
James Molloy4de84dd2015-11-04 15:28:04 +00002890 };
2891
Dehao Chenf6c00832016-05-18 19:44:21 +00002892 if (!MergeCondStoresAggressively &&
2893 (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
2894 !IsWorthwhile(QFB)))
James Molloy4de84dd2015-11-04 15:28:04 +00002895 return false;
2896
2897 // For every pointer, there must be exactly two stores, one coming from
2898 // PTB or PFB, and the other from QTB or QFB. We don't support more than one
2899 // store (to any address) in PTB,PFB or QTB,QFB.
2900 // FIXME: We could relax this restriction with a bit more work and performance
2901 // testing.
2902 StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
2903 StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
2904 if (!PStore || !QStore)
2905 return false;
2906
2907 // Now check the stores are compatible.
2908 if (!QStore->isUnordered() || !PStore->isUnordered())
2909 return false;
2910
2911 // Check that sinking the store won't cause program behavior changes. Sinking
2912 // the store out of the Q blocks won't change any behavior as we're sinking
2913 // from a block to its unconditional successor. But we're moving a store from
2914 // the P blocks down through the middle block (QBI) and past both QFB and QTB.
2915 // So we need to check that there are no aliasing loads or stores in
2916 // QBI, QTB and QFB. We also need to check there are no conflicting memory
2917 // operations between PStore and the end of its parent block.
2918 //
2919 // The ideal way to do this is to query AliasAnalysis, but we don't
2920 // preserve AA currently so that is dangerous. Be super safe and just
2921 // check there are no other memory operations at all.
2922 for (auto &I : *QFB->getSinglePredecessor())
2923 if (I.mayReadOrWriteMemory())
2924 return false;
2925 for (auto &I : *QFB)
2926 if (&I != QStore && I.mayReadOrWriteMemory())
2927 return false;
2928 if (QTB)
2929 for (auto &I : *QTB)
2930 if (&I != QStore && I.mayReadOrWriteMemory())
2931 return false;
2932 for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
2933 I != E; ++I)
2934 if (&*I != PStore && I->mayReadOrWriteMemory())
2935 return false;
2936
2937 // OK, we're going to sink the stores to PostBB. The store has to be
2938 // conditional though, so first create the predicate.
2939 Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
2940 ->getCondition();
2941 Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
2942 ->getCondition();
2943
2944 Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
2945 PStore->getParent());
2946 Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
2947 QStore->getParent(), PPHI);
2948
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002949 IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
2950
James Molloy4de84dd2015-11-04 15:28:04 +00002951 Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
2952 Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
2953
2954 if (InvertPCond)
2955 PPred = QB.CreateNot(PPred);
2956 if (InvertQCond)
2957 QPred = QB.CreateNot(QPred);
2958 Value *CombinedPred = QB.CreateOr(PPred, QPred);
2959
Duncan P. N. Exon Smith83c4b682015-11-07 00:01:16 +00002960 auto *T =
2961 SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
James Molloy4de84dd2015-11-04 15:28:04 +00002962 QB.SetInsertPoint(T);
2963 StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
2964 AAMDNodes AAMD;
2965 PStore->getAAMetadata(AAMD, /*Merge=*/false);
2966 PStore->getAAMetadata(AAMD, /*Merge=*/true);
2967 SI->setAAMetadata(AAMD);
Alexey Bataev978e2e42017-08-29 20:06:24 +00002968 unsigned PAlignment = PStore->getAlignment();
2969 unsigned QAlignment = QStore->getAlignment();
2970 unsigned TypeAlignment =
2971 DL.getABITypeAlignment(SI->getValueOperand()->getType());
2972 unsigned MinAlignment;
2973 unsigned MaxAlignment;
2974 std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment);
2975 // Choose the minimum alignment. If we could prove both stores execute, we
2976 // could use biggest one. In this case, though, we only know that one of the
2977 // stores executes. And we don't know it's safe to take the alignment from a
2978 // store that doesn't execute.
2979 if (MinAlignment != 0) {
2980 // Choose the minimum of all non-zero alignments.
2981 SI->setAlignment(MinAlignment);
2982 } else if (MaxAlignment != 0) {
2983 // Choose the minimal alignment between the non-zero alignment and the ABI
2984 // default alignment for the type of the stored value.
2985 SI->setAlignment(std::min(MaxAlignment, TypeAlignment));
2986 } else {
2987 // If both alignments are zero, use ABI default alignment for the type of
2988 // the stored value.
2989 SI->setAlignment(TypeAlignment);
2990 }
James Molloy4de84dd2015-11-04 15:28:04 +00002991
2992 QStore->eraseFromParent();
2993 PStore->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00002994
James Molloy4de84dd2015-11-04 15:28:04 +00002995 return true;
2996}
2997
Alexey Bataev978e2e42017-08-29 20:06:24 +00002998static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
2999 const DataLayout &DL) {
James Molloy4de84dd2015-11-04 15:28:04 +00003000 // The intention here is to find diamonds or triangles (see below) where each
3001 // conditional block contains a store to the same address. Both of these
3002 // stores are conditional, so they can't be unconditionally sunk. But it may
3003 // be profitable to speculatively sink the stores into one merged store at the
3004 // end, and predicate the merged store on the union of the two conditions of
3005 // PBI and QBI.
3006 //
3007 // This can reduce the number of stores executed if both of the conditions are
3008 // true, and can allow the blocks to become small enough to be if-converted.
3009 // This optimization will also chain, so that ladders of test-and-set
3010 // sequences can be if-converted away.
3011 //
3012 // We only deal with simple diamonds or triangles:
3013 //
3014 // PBI or PBI or a combination of the two
3015 // / \ | \
3016 // PTB PFB | PFB
3017 // \ / | /
3018 // QBI QBI
3019 // / \ | \
3020 // QTB QFB | QFB
3021 // \ / | /
3022 // PostBB PostBB
3023 //
3024 // We model triangles as a type of diamond with a nullptr "true" block.
3025 // Triangles are canonicalized so that the fallthrough edge is represented by
3026 // a true condition, as in the diagram above.
Dehao Chenf6c00832016-05-18 19:44:21 +00003027 //
James Molloy4de84dd2015-11-04 15:28:04 +00003028 BasicBlock *PTB = PBI->getSuccessor(0);
3029 BasicBlock *PFB = PBI->getSuccessor(1);
3030 BasicBlock *QTB = QBI->getSuccessor(0);
3031 BasicBlock *QFB = QBI->getSuccessor(1);
3032 BasicBlock *PostBB = QFB->getSingleSuccessor();
3033
Craig Topper7af07882017-04-21 15:53:42 +00003034 // Make sure we have a good guess for PostBB. If QTB's only successor is
3035 // QFB, then QFB is a better PostBB.
3036 if (QTB->getSingleSuccessor() == QFB)
3037 PostBB = QFB;
3038
3039 // If we couldn't find a good PostBB, stop.
3040 if (!PostBB)
3041 return false;
3042
James Molloy4de84dd2015-11-04 15:28:04 +00003043 bool InvertPCond = false, InvertQCond = false;
3044 // Canonicalize fallthroughs to the true branches.
3045 if (PFB == QBI->getParent()) {
3046 std::swap(PFB, PTB);
3047 InvertPCond = true;
3048 }
3049 if (QFB == PostBB) {
3050 std::swap(QFB, QTB);
3051 InvertQCond = true;
3052 }
3053
3054 // From this point on we can assume PTB or QTB may be fallthroughs but PFB
3055 // and QFB may not. Model fallthroughs as a nullptr block.
3056 if (PTB == QBI->getParent())
3057 PTB = nullptr;
3058 if (QTB == PostBB)
3059 QTB = nullptr;
3060
3061 // Legality bailouts. We must have at least the non-fallthrough blocks and
3062 // the post-dominating block, and the non-fallthroughs must only have one
3063 // predecessor.
3064 auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
Dehao Chenf6c00832016-05-18 19:44:21 +00003065 return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
James Molloy4de84dd2015-11-04 15:28:04 +00003066 };
Craig Topper7af07882017-04-21 15:53:42 +00003067 if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
James Molloy4de84dd2015-11-04 15:28:04 +00003068 !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
3069 return false;
3070 if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
3071 (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
3072 return false;
Craig Topperc2280682017-04-17 22:13:00 +00003073 if (!PostBB->hasNUses(2) || !QBI->getParent()->hasNUses(2))
James Molloy4de84dd2015-11-04 15:28:04 +00003074 return false;
3075
3076 // OK, this is a sequence of two diamonds or triangles.
3077 // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
Dehao Chenf6c00832016-05-18 19:44:21 +00003078 SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
James Molloy4de84dd2015-11-04 15:28:04 +00003079 for (auto *BB : {PTB, PFB}) {
3080 if (!BB)
3081 continue;
3082 for (auto &I : *BB)
3083 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3084 PStoreAddresses.insert(SI->getPointerOperand());
3085 }
3086 for (auto *BB : {QTB, QFB}) {
3087 if (!BB)
3088 continue;
3089 for (auto &I : *BB)
3090 if (StoreInst *SI = dyn_cast<StoreInst>(&I))
3091 QStoreAddresses.insert(SI->getPointerOperand());
3092 }
Dehao Chenf6c00832016-05-18 19:44:21 +00003093
James Molloy4de84dd2015-11-04 15:28:04 +00003094 set_intersect(PStoreAddresses, QStoreAddresses);
3095 // set_intersect mutates PStoreAddresses in place. Rename it here to make it
3096 // clear what it contains.
3097 auto &CommonAddresses = PStoreAddresses;
3098
3099 bool Changed = false;
3100 for (auto *Address : CommonAddresses)
3101 Changed |= mergeConditionalStoreToAddress(
Alexey Bataev978e2e42017-08-29 20:06:24 +00003102 PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL);
James Molloy4de84dd2015-11-04 15:28:04 +00003103 return Changed;
3104}
3105
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003106/// If we have a conditional branch as a predecessor of another block,
3107/// this function tries to simplify it. We know
Chris Lattner9aada1d2008-07-13 21:53:26 +00003108/// that PBI and BI are both conditional branches, and BI is in one of the
3109/// successor blocks of PBI - PBI branches to BI.
Philip Reamesb42db212015-10-14 22:46:19 +00003110static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
3111 const DataLayout &DL) {
Chris Lattner9aada1d2008-07-13 21:53:26 +00003112 assert(PBI->isConditional() && BI->isConditional());
3113 BasicBlock *BB = BI->getParent();
Dan Gohman5476cfd2009-08-12 16:23:25 +00003114
Chris Lattner9aada1d2008-07-13 21:53:26 +00003115 // If this block ends with a branch instruction, and if there is a
Andrew Trickf3cf1932012-08-29 21:46:36 +00003116 // predecessor that ends on a branch of the same condition, make
Chris Lattner9aada1d2008-07-13 21:53:26 +00003117 // this conditional branch redundant.
3118 if (PBI->getCondition() == BI->getCondition() &&
3119 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3120 // Okay, the outcome of this conditional branch is statically
3121 // knowable. If this block had a single pred, handle specially.
3122 if (BB->getSinglePredecessor()) {
3123 // Turn this into a branch on constant.
3124 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Dehao Chenf6c00832016-05-18 19:44:21 +00003125 BI->setCondition(
3126 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
3127 return true; // Nuke the branch on constant.
Chris Lattner9aada1d2008-07-13 21:53:26 +00003128 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003129
Chris Lattner9aada1d2008-07-13 21:53:26 +00003130 // Otherwise, if there are multiple predecessors, insert a PHI that merges
3131 // in the constant and simplify the block result. Subsequent passes of
3132 // simplifycfg will thread the block.
3133 if (BlockIsSimpleEnoughToThreadThrough(BB)) {
Jay Foade0938d82011-03-30 11:19:20 +00003134 pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003135 PHINode *NewPN = PHINode::Create(
3136 Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
3137 BI->getCondition()->getName() + ".pr", &BB->front());
Chris Lattner5eed3722008-07-13 21:55:46 +00003138 // Okay, we're going to insert the PHI node. Since PBI is not the only
3139 // predecessor, compute the PHI'd conditional value for all of the preds.
3140 // Any predecessor where the condition is not computable we keep symbolic.
Jay Foade0938d82011-03-30 11:19:20 +00003141 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif8629f122010-07-12 10:59:23 +00003142 BasicBlock *P = *PI;
Dehao Chenf6c00832016-05-18 19:44:21 +00003143 if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
3144 PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
Chris Lattner9aada1d2008-07-13 21:53:26 +00003145 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
3146 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Dehao Chenf6c00832016-05-18 19:44:21 +00003147 NewPN->addIncoming(
3148 ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
3149 P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00003150 } else {
Gabor Greif8629f122010-07-12 10:59:23 +00003151 NewPN->addIncoming(BI->getCondition(), P);
Chris Lattner9aada1d2008-07-13 21:53:26 +00003152 }
Gabor Greif8629f122010-07-12 10:59:23 +00003153 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003154
Chris Lattner9aada1d2008-07-13 21:53:26 +00003155 BI->setCondition(NewPN);
Chris Lattner9aada1d2008-07-13 21:53:26 +00003156 return true;
3157 }
3158 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003159
Philip Reamesb42db212015-10-14 22:46:19 +00003160 if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
3161 if (CE->canTrap())
3162 return false;
3163
James Molloy4de84dd2015-11-04 15:28:04 +00003164 // If both branches are conditional and both contain stores to the same
3165 // address, remove the stores from the conditionals and create a conditional
3166 // merged store at the end.
Alexey Bataev978e2e42017-08-29 20:06:24 +00003167 if (MergeCondStores && mergeConditionalStores(PBI, BI, DL))
James Molloy4de84dd2015-11-04 15:28:04 +00003168 return true;
3169
Chris Lattner9aada1d2008-07-13 21:53:26 +00003170 // If this is a conditional branch in an empty block, and if any
Sanjay Patel0a2ada72014-07-06 23:10:24 +00003171 // predecessors are a conditional branch to one of our destinations,
Chris Lattner9aada1d2008-07-13 21:53:26 +00003172 // fold the conditions into logical ops and one cond br.
Zhou Sheng264e46e2009-02-26 06:56:37 +00003173 BasicBlock::iterator BBI = BB->begin();
3174 // Ignore dbg intrinsics.
3175 while (isa<DbgInfoIntrinsic>(BBI))
3176 ++BBI;
3177 if (&*BBI != BI)
Chris Lattner834ab4e2008-07-13 22:04:41 +00003178 return false;
Chris Lattnerc59945b2009-01-20 01:15:41 +00003179
Chris Lattner834ab4e2008-07-13 22:04:41 +00003180 int PBIOp, BIOp;
Richard Trieu7a083812016-02-18 22:09:30 +00003181 if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
3182 PBIOp = 0;
3183 BIOp = 0;
3184 } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
3185 PBIOp = 0;
3186 BIOp = 1;
3187 } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
3188 PBIOp = 1;
3189 BIOp = 0;
3190 } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
3191 PBIOp = 1;
3192 BIOp = 1;
3193 } else {
Chris Lattner834ab4e2008-07-13 22:04:41 +00003194 return false;
Richard Trieu7a083812016-02-18 22:09:30 +00003195 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003196
Chris Lattner834ab4e2008-07-13 22:04:41 +00003197 // Check to make sure that the other destination of this branch
3198 // isn't BB itself. If so, this is an infinite loop that will
3199 // keep getting unwound.
3200 if (PBI->getSuccessor(PBIOp) == BB)
3201 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003202
3203 // Do not perform this transformation if it would require
Chris Lattner834ab4e2008-07-13 22:04:41 +00003204 // insertion of a large number of select instructions. For targets
3205 // without predication/cmovs, this is a big pessimization.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003206
Sanjay Patela932da82014-07-07 21:19:00 +00003207 // Also do not perform this transformation if any phi node in the common
3208 // destination block can trap when reached by BB or PBB (PR17073). In that
3209 // case, it would be unsafe to hoist the operation into a select instruction.
3210
3211 BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
Chris Lattner834ab4e2008-07-13 22:04:41 +00003212 unsigned NumPhis = 0;
Dehao Chenf6c00832016-05-18 19:44:21 +00003213 for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
3214 ++II, ++NumPhis) {
Chris Lattner834ab4e2008-07-13 22:04:41 +00003215 if (NumPhis > 2) // Disable this xform.
3216 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003217
Sanjay Patela932da82014-07-07 21:19:00 +00003218 PHINode *PN = cast<PHINode>(II);
3219 Value *BIV = PN->getIncomingValueForBlock(BB);
3220 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
3221 if (CE->canTrap())
3222 return false;
3223
3224 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3225 Value *PBIV = PN->getIncomingValue(PBBIdx);
3226 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
3227 if (CE->canTrap())
3228 return false;
3229 }
3230
Chris Lattner834ab4e2008-07-13 22:04:41 +00003231 // Finally, if everything is ok, fold the branches to logical ops.
Sanjay Patela932da82014-07-07 21:19:00 +00003232 BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003233
David Greene725c7c32010-01-05 01:26:52 +00003234 DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
Chris Lattnerb25de3f2009-08-23 04:37:46 +00003235 << "AND: " << *BI->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003236
Chris Lattner80b03a12008-07-13 22:23:11 +00003237 // If OtherDest *is* BB, then BB is a basic block with a single conditional
3238 // branch in it, where one edge (OtherDest) goes back to itself but the other
3239 // exits. We don't *know* that the program avoids the infinite loop
3240 // (even though that seems likely). If we do this xform naively, we'll end up
3241 // recursively unpeeling the loop. Since we know that (after the xform is
3242 // done) that the block *is* infinite if reached, we just make it an obviously
3243 // infinite loop with no cond branch.
3244 if (OtherDest == BB) {
3245 // Insert it at the end of the function, because it's either code,
3246 // or it won't matter if it's hot. :)
Dehao Chenf6c00832016-05-18 19:44:21 +00003247 BasicBlock *InfLoopBlock =
3248 BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
Chris Lattner80b03a12008-07-13 22:23:11 +00003249 BranchInst::Create(InfLoopBlock, InfLoopBlock);
3250 OtherDest = InfLoopBlock;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003251 }
3252
David Greene725c7c32010-01-05 01:26:52 +00003253 DEBUG(dbgs() << *PBI->getParent()->getParent());
Devang Patel1407fb42011-05-19 20:52:46 +00003254
Chris Lattner834ab4e2008-07-13 22:04:41 +00003255 // BI may have other predecessors. Because of this, we leave
3256 // it alone, but modify PBI.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003257
Chris Lattner834ab4e2008-07-13 22:04:41 +00003258 // Make sure we get to CommonDest on True&True directions.
3259 Value *PBICond = PBI->getCondition();
Mehdi Aminiba9fba82016-03-13 21:05:13 +00003260 IRBuilder<NoFolder> Builder(PBI);
Chris Lattner834ab4e2008-07-13 22:04:41 +00003261 if (PBIOp)
Dehao Chenf6c00832016-05-18 19:44:21 +00003262 PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
Devang Patel1407fb42011-05-19 20:52:46 +00003263
Chris Lattner834ab4e2008-07-13 22:04:41 +00003264 Value *BICond = BI->getCondition();
3265 if (BIOp)
Dehao Chenf6c00832016-05-18 19:44:21 +00003266 BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
Devang Patel1407fb42011-05-19 20:52:46 +00003267
Chris Lattner834ab4e2008-07-13 22:04:41 +00003268 // Merge the conditions.
Devang Patel1407fb42011-05-19 20:52:46 +00003269 Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
Andrew Trickf3cf1932012-08-29 21:46:36 +00003270
Chris Lattner834ab4e2008-07-13 22:04:41 +00003271 // Modify PBI to branch on the new condition to the new dests.
3272 PBI->setCondition(Cond);
3273 PBI->setSuccessor(0, CommonDest);
3274 PBI->setSuccessor(1, OtherDest);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003275
Manman Ren2d4c10f2012-09-17 21:30:40 +00003276 // Update branch weight for PBI.
3277 uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
Dehao Chenb76e5d92016-05-10 23:07:19 +00003278 uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
Dehao Chenf16376b2016-05-18 22:41:03 +00003279 bool HasWeights =
3280 extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
3281 SuccTrueWeight, SuccFalseWeight);
Dehao Chenb76e5d92016-05-10 23:07:19 +00003282 if (HasWeights) {
Dehao Chenb76e5d92016-05-10 23:07:19 +00003283 PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3284 PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3285 SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3286 SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
Manman Ren2d4c10f2012-09-17 21:30:40 +00003287 // The weight to CommonDest should be PredCommon * SuccTotal +
3288 // PredOther * SuccCommon.
3289 // The weight to OtherDest should be PredOther * SuccOther.
Benjamin Kramerea68a942015-02-19 15:26:17 +00003290 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
3291 PredOther * SuccCommon,
3292 PredOther * SuccOther};
Sanjay Patel84a0bf62016-05-06 17:51:37 +00003293 // Halve the weights if any of them cannot fit in an uint32_t
Manman Ren2d4c10f2012-09-17 21:30:40 +00003294 FitWeights(NewWeights);
3295
Manman Ren2d4c10f2012-09-17 21:30:40 +00003296 PBI->setMetadata(LLVMContext::MD_prof,
Sanjay Patel84a0bf62016-05-06 17:51:37 +00003297 MDBuilder(BI->getContext())
3298 .createBranchWeights(NewWeights[0], NewWeights[1]));
Manman Ren2d4c10f2012-09-17 21:30:40 +00003299 }
3300
Chris Lattner834ab4e2008-07-13 22:04:41 +00003301 // OtherDest may have phi nodes. If so, add an entry from PBI's
3302 // block that are identical to the entries for BI's block.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003303 AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003304
Chris Lattner834ab4e2008-07-13 22:04:41 +00003305 // We know that the CommonDest already had an edge from PBI to
3306 // it. If it has PHIs though, the PHIs may have different
3307 // entries for BB and PBI's BB. If so, insert a select to make
3308 // them agree.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003309 PHINode *PN;
Chris Lattner834ab4e2008-07-13 22:04:41 +00003310 for (BasicBlock::iterator II = CommonDest->begin();
3311 (PN = dyn_cast<PHINode>(II)); ++II) {
3312 Value *BIV = PN->getIncomingValueForBlock(BB);
3313 unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
3314 Value *PBIV = PN->getIncomingValue(PBBIdx);
3315 if (BIV != PBIV) {
3316 // Insert a select in PBI to pick the right value.
Dehao Chenf6c00832016-05-18 19:44:21 +00003317 SelectInst *NV = cast<SelectInst>(
3318 Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
Chris Lattner834ab4e2008-07-13 22:04:41 +00003319 PN->setIncomingValue(PBBIdx, NV);
Sanjay Patel1cb62412016-05-06 18:07:46 +00003320 // Although the select has the same condition as PBI, the original branch
3321 // weights for PBI do not apply to the new select because the select's
3322 // 'logical' edges are incoming edges of the phi that is eliminated, not
3323 // the outgoing edges of PBI.
Dehao Chenf16376b2016-05-18 22:41:03 +00003324 if (HasWeights) {
Sanjay Patel1cb62412016-05-06 18:07:46 +00003325 uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
3326 uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
3327 uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
3328 uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
3329 // The weight to PredCommonDest should be PredCommon * SuccTotal.
3330 // The weight to PredOtherDest should be PredOther * SuccCommon.
3331 uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
3332 PredOther * SuccCommon};
3333
3334 FitWeights(NewWeights);
3335
3336 NV->setMetadata(LLVMContext::MD_prof,
3337 MDBuilder(BI->getContext())
3338 .createBranchWeights(NewWeights[0], NewWeights[1]));
3339 }
Chris Lattner9aada1d2008-07-13 21:53:26 +00003340 }
3341 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003342
David Greene725c7c32010-01-05 01:26:52 +00003343 DEBUG(dbgs() << "INTO: " << *PBI->getParent());
3344 DEBUG(dbgs() << *PBI->getParent()->getParent());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003345
Chris Lattner834ab4e2008-07-13 22:04:41 +00003346 // This basic block is probably dead. We know it has at least
3347 // one fewer predecessor.
3348 return true;
Chris Lattner9aada1d2008-07-13 21:53:26 +00003349}
3350
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003351// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
3352// true or to FalseBB if Cond is false.
Frits van Bommel8e158492011-01-11 12:52:11 +00003353// Takes care of updating the successors and removing the old terminator.
3354// Also makes sure not to introduce new successors by assuming that edges to
3355// non-successor TrueBBs and FalseBBs aren't reachable.
3356static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
Manman Ren774246a2012-09-17 22:28:55 +00003357 BasicBlock *TrueBB, BasicBlock *FalseBB,
3358 uint32_t TrueWeight,
Dehao Chenf6c00832016-05-18 19:44:21 +00003359 uint32_t FalseWeight) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003360 // Remove any superfluous successor edges from the CFG.
3361 // First, figure out which successors to preserve.
3362 // If TrueBB and FalseBB are equal, only try to preserve one copy of that
3363 // successor.
3364 BasicBlock *KeepEdge1 = TrueBB;
Craig Topperf40110f2014-04-25 05:29:35 +00003365 BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003366
3367 // Then remove the rest.
Pete Cooperebcd7482015-08-06 20:22:46 +00003368 for (BasicBlock *Succ : OldTerm->successors()) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003369 // Make sure only to keep exactly one copy of each edge.
3370 if (Succ == KeepEdge1)
Craig Topperf40110f2014-04-25 05:29:35 +00003371 KeepEdge1 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003372 else if (Succ == KeepEdge2)
Craig Topperf40110f2014-04-25 05:29:35 +00003373 KeepEdge2 = nullptr;
Frits van Bommel8e158492011-01-11 12:52:11 +00003374 else
David Majnemerdc3b67b2015-10-21 18:22:24 +00003375 Succ->removePredecessor(OldTerm->getParent(),
3376 /*DontDeleteUselessPHIs=*/true);
Frits van Bommel8e158492011-01-11 12:52:11 +00003377 }
3378
Devang Patel2c2ea222011-05-18 18:43:31 +00003379 IRBuilder<> Builder(OldTerm);
3380 Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
3381
Frits van Bommel8e158492011-01-11 12:52:11 +00003382 // Insert an appropriate new terminator.
Craig Topperf40110f2014-04-25 05:29:35 +00003383 if (!KeepEdge1 && !KeepEdge2) {
Frits van Bommel8e158492011-01-11 12:52:11 +00003384 if (TrueBB == FalseBB)
3385 // We were only looking for one successor, and it was present.
3386 // Create an unconditional branch to it.
Devang Patel2c2ea222011-05-18 18:43:31 +00003387 Builder.CreateBr(TrueBB);
Manman Ren774246a2012-09-17 22:28:55 +00003388 else {
Frits van Bommel8e158492011-01-11 12:52:11 +00003389 // We found both of the successors we were looking for.
3390 // Create a conditional branch sharing the condition of the select.
Manman Ren774246a2012-09-17 22:28:55 +00003391 BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
3392 if (TrueWeight != FalseWeight)
3393 NewBI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00003394 MDBuilder(OldTerm->getContext())
3395 .createBranchWeights(TrueWeight, FalseWeight));
Manman Ren774246a2012-09-17 22:28:55 +00003396 }
Frits van Bommel8e158492011-01-11 12:52:11 +00003397 } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
3398 // Neither of the selected blocks were successors, so this
3399 // terminator must be unreachable.
3400 new UnreachableInst(OldTerm->getContext(), OldTerm);
3401 } else {
3402 // One of the selected values was a successor, but the other wasn't.
3403 // Insert an unconditional branch to the one that was found;
3404 // the edge to the one that wasn't must be unreachable.
Craig Topperf40110f2014-04-25 05:29:35 +00003405 if (!KeepEdge1)
Frits van Bommel8e158492011-01-11 12:52:11 +00003406 // Only TrueBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00003407 Builder.CreateBr(TrueBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00003408 else
3409 // Only FalseBB was found.
Devang Patel2c2ea222011-05-18 18:43:31 +00003410 Builder.CreateBr(FalseBB);
Frits van Bommel8e158492011-01-11 12:52:11 +00003411 }
3412
3413 EraseTerminatorInstAndDCECond(OldTerm);
3414 return true;
3415}
3416
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003417// Replaces
Frits van Bommel8ae07992011-02-28 09:44:07 +00003418// (switch (select cond, X, Y)) on constant X, Y
3419// with a branch - conditional if X and Y lead to distinct BBs,
3420// unconditional otherwise.
3421static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
3422 // Check for constant integer values in the select.
3423 ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
3424 ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
3425 if (!TrueVal || !FalseVal)
3426 return false;
3427
3428 // Find the relevant condition and destinations.
3429 Value *Condition = Select->getCondition();
Chandler Carruth927d8e62017-04-12 07:27:28 +00003430 BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
3431 BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
Frits van Bommel8ae07992011-02-28 09:44:07 +00003432
Manman Ren774246a2012-09-17 22:28:55 +00003433 // Get weight for TrueBB and FalseBB.
3434 uint32_t TrueWeight = 0, FalseWeight = 0;
3435 SmallVector<uint64_t, 8> Weights;
3436 bool HasWeights = HasBranchWeights(SI);
3437 if (HasWeights) {
3438 GetBranchWeights(SI, Weights);
3439 if (Weights.size() == 1 + SI->getNumCases()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00003440 TrueWeight =
Chandler Carruth927d8e62017-04-12 07:27:28 +00003441 (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
Dehao Chenf6c00832016-05-18 19:44:21 +00003442 FalseWeight =
Chandler Carruth927d8e62017-04-12 07:27:28 +00003443 (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
Manman Ren774246a2012-09-17 22:28:55 +00003444 }
3445 }
3446
Frits van Bommel8ae07992011-02-28 09:44:07 +00003447 // Perform the actual simplification.
Dehao Chenf6c00832016-05-18 19:44:21 +00003448 return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
3449 FalseWeight);
Frits van Bommel8ae07992011-02-28 09:44:07 +00003450}
3451
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003452// Replaces
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003453// (indirectbr (select cond, blockaddress(@fn, BlockA),
3454// blockaddress(@fn, BlockB)))
3455// with
3456// (br cond, BlockA, BlockB).
3457static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
3458 // Check that both operands of the select are block addresses.
3459 BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
3460 BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
3461 if (!TBA || !FBA)
3462 return false;
3463
3464 // Extract the actual blocks.
3465 BasicBlock *TrueBB = TBA->getBasicBlock();
3466 BasicBlock *FalseBB = FBA->getBasicBlock();
3467
Frits van Bommel8e158492011-01-11 12:52:11 +00003468 // Perform the actual simplification.
Dehao Chenf6c00832016-05-18 19:44:21 +00003469 return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
3470 0);
Frits van Bommel8fb69ee2010-12-05 18:29:03 +00003471}
3472
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003473/// This is called when we find an icmp instruction
3474/// (a seteq/setne with a constant) as the only instruction in a
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003475/// block that ends with an uncond branch. We are looking for a very specific
3476/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
3477/// this case, we merge the first two "or's of icmp" into a switch, but then the
3478/// default value goes to an uncond block with a seteq in it, we get something
3479/// like:
3480///
3481/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
3482/// DEFAULT:
3483/// %tmp = icmp eq i8 %A, 92
3484/// br label %end
3485/// end:
3486/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
Andrew Trickf3cf1932012-08-29 21:46:36 +00003487///
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003488/// We prefer to split the edge to 'end' so that there is a true/false entry to
3489/// the PHI, merging the third icmp into the switch.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00003490static bool TryToSimplifyUncondBranchWithICmpInIt(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003491 ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
Sanjay Patel0f9b4772017-09-27 14:54:16 +00003492 const TargetTransformInfo &TTI, AssumptionCache *AC,
3493 const SimplifyCFGOptions &Options) {
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003494 BasicBlock *BB = ICI->getParent();
Devang Patel767f6932011-05-18 18:28:48 +00003495
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003496 // If the block has any PHIs in it or the icmp has multiple uses, it is too
3497 // complex.
Dehao Chenf6c00832016-05-18 19:44:21 +00003498 if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
3499 return false;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003500
3501 Value *V = ICI->getOperand(0);
3502 ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
Andrew Trickf3cf1932012-08-29 21:46:36 +00003503
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003504 // The pattern we're looking for is where our only predecessor is a switch on
3505 // 'V' and this block is the default case for the switch. In this case we can
3506 // fold the compared value into the switch to simplify things.
3507 BasicBlock *Pred = BB->getSinglePredecessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00003508 if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
3509 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003510
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003511 SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
3512 if (SI->getCondition() != V)
3513 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003514
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003515 // If BB is reachable on a non-default case, then we simply know the value of
3516 // V in this block. Substitute it and constant fold the icmp instruction
3517 // away.
3518 if (SI->getDefaultDest() != BB) {
3519 ConstantInt *VVal = SI->findCaseDest(BB);
3520 assert(VVal && "Should have a unique destination value");
3521 ICI->setOperand(0, VVal);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003522
Daniel Berlin4d0fe642017-04-28 19:55:38 +00003523 if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
Chris Lattnerd7beca32010-12-14 06:17:25 +00003524 ICI->replaceAllUsesWith(V);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003525 ICI->eraseFromParent();
3526 }
3527 // BB is now empty, so it is likely to simplify away.
Sanjay Patel0f9b4772017-09-27 14:54:16 +00003528 return SimplifyCFG(BB, TTI, AC, Options) | true;
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003529 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003530
Chris Lattner62cc76e2010-12-13 03:43:57 +00003531 // Ok, the block is reachable from the default dest. If the constant we're
3532 // comparing exists in one of the other edges, then we can constant fold ICI
3533 // and zap it.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00003534 if (SI->findCaseValue(Cst) != SI->case_default()) {
Chris Lattner62cc76e2010-12-13 03:43:57 +00003535 Value *V;
3536 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3537 V = ConstantInt::getFalse(BB->getContext());
3538 else
3539 V = ConstantInt::getTrue(BB->getContext());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003540
Chris Lattner62cc76e2010-12-13 03:43:57 +00003541 ICI->replaceAllUsesWith(V);
3542 ICI->eraseFromParent();
3543 // BB is now empty, so it is likely to simplify away.
Sanjay Patel0f9b4772017-09-27 14:54:16 +00003544 return SimplifyCFG(BB, TTI, AC, Options) | true;
Chris Lattner62cc76e2010-12-13 03:43:57 +00003545 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003546
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003547 // The use of the icmp has to be in the 'end' block, by the only PHI node in
3548 // the block.
3549 BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003550 PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
Craig Topperf40110f2014-04-25 05:29:35 +00003551 if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003552 isa<PHINode>(++BasicBlock::iterator(PHIUse)))
3553 return false;
3554
3555 // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
3556 // true in the PHI.
3557 Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
Dehao Chenf6c00832016-05-18 19:44:21 +00003558 Constant *NewCst = ConstantInt::getFalse(BB->getContext());
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003559
3560 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
3561 std::swap(DefaultCst, NewCst);
3562
3563 // Replace ICI (which is used by the PHI for the default value) with true or
3564 // false depending on if it is EQ or NE.
3565 ICI->replaceAllUsesWith(DefaultCst);
3566 ICI->eraseFromParent();
3567
3568 // Okay, the switch goes to this block on a default value. Add an edge from
3569 // the switch to the merge point on the compared value.
Dehao Chenf6c00832016-05-18 19:44:21 +00003570 BasicBlock *NewBB =
3571 BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
Manman Rence48ea72012-09-17 23:07:43 +00003572 SmallVector<uint64_t, 8> Weights;
3573 bool HasWeights = HasBranchWeights(SI);
3574 if (HasWeights) {
3575 GetBranchWeights(SI, Weights);
3576 if (Weights.size() == 1 + SI->getNumCases()) {
3577 // Split weight for default case to case for "Cst".
Dehao Chenf6c00832016-05-18 19:44:21 +00003578 Weights[0] = (Weights[0] + 1) >> 1;
Manman Rence48ea72012-09-17 23:07:43 +00003579 Weights.push_back(Weights[0]);
3580
3581 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
Dehao Chenf6c00832016-05-18 19:44:21 +00003582 SI->setMetadata(
3583 LLVMContext::MD_prof,
3584 MDBuilder(SI->getContext()).createBranchWeights(MDWeights));
Manman Rence48ea72012-09-17 23:07:43 +00003585 }
3586 }
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003587 SI->addCase(Cst, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003588
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003589 // NewBB branches to the phi block, add the uncond branch and the phi entry.
Devang Patel767f6932011-05-18 18:28:48 +00003590 Builder.SetInsertPoint(NewBB);
3591 Builder.SetCurrentDebugLocation(SI->getDebugLoc());
3592 Builder.CreateBr(SuccBlock);
Chris Lattnerd9bacc02010-12-13 03:18:54 +00003593 PHIUse->addIncoming(NewCst, NewBB);
3594 return true;
3595}
3596
Sanjay Patel09159b8f2015-06-24 20:40:57 +00003597/// The specified branch is a conditional branch.
Chris Lattnera69c4432010-12-13 05:03:41 +00003598/// Check to see if it is branching on an or/and chain of icmp instructions, and
3599/// fold it into a switch instruction if so.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003600static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
3601 const DataLayout &DL) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003602 Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
Dehao Chenf6c00832016-05-18 19:44:21 +00003603 if (!Cond)
3604 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003605
Chris Lattnera69c4432010-12-13 05:03:41 +00003606 // Change br (X == 0 | X == 1), T, F into a switch instruction.
3607 // If this is a bunch of seteq's or'd together, or if it's a bunch of
3608 // 'setne's and'ed together, collect them.
Andrew Trickf3cf1932012-08-29 21:46:36 +00003609
Mehdi Amini9a25cb82014-11-19 20:09:11 +00003610 // Try to gather values from a chain of and/or to be turned into a switch
Mehdi Aminiffd01002014-11-20 22:40:25 +00003611 ConstantComparesGatherer ConstantCompare(Cond, DL);
3612 // Unpack the result
Dehao Chenf6c00832016-05-18 19:44:21 +00003613 SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
Mehdi Aminiffd01002014-11-20 22:40:25 +00003614 Value *CompVal = ConstantCompare.CompValue;
3615 unsigned UsedICmps = ConstantCompare.UsedICmps;
3616 Value *ExtraCase = ConstantCompare.Extra;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003617
Chris Lattnera69c4432010-12-13 05:03:41 +00003618 // If we didn't have a multiply compared value, fail.
Dehao Chenf6c00832016-05-18 19:44:21 +00003619 if (!CompVal)
3620 return false;
Chris Lattnera69c4432010-12-13 05:03:41 +00003621
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00003622 // Avoid turning single icmps into a switch.
3623 if (UsedICmps <= 1)
3624 return false;
3625
Mehdi Aminiffd01002014-11-20 22:40:25 +00003626 bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
3627
Chris Lattnera69c4432010-12-13 05:03:41 +00003628 // There might be duplicate constants in the list, which the switch
3629 // instruction can't handle, remove them now.
3630 array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
3631 Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
Andrew Trickf3cf1932012-08-29 21:46:36 +00003632
Chris Lattnera69c4432010-12-13 05:03:41 +00003633 // If Extra was used, we require at least two switch values to do the
Sanjay Patel59661452015-09-10 15:14:34 +00003634 // transformation. A switch with one value is just a conditional branch.
Dehao Chenf6c00832016-05-18 19:44:21 +00003635 if (ExtraCase && Values.size() < 2)
3636 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00003637
Andrew Trick3051aa12012-08-29 21:46:38 +00003638 // TODO: Preserve branch weight metadata, similarly to how
3639 // FoldValueComparisonIntoPredecessors preserves it.
3640
Chris Lattnera69c4432010-12-13 05:03:41 +00003641 // Figure out which block is which destination.
3642 BasicBlock *DefaultBB = BI->getSuccessor(1);
Dehao Chenf6c00832016-05-18 19:44:21 +00003643 BasicBlock *EdgeBB = BI->getSuccessor(0);
3644 if (!TrueWhenEqual)
3645 std::swap(DefaultBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003646
Chris Lattnera69c4432010-12-13 05:03:41 +00003647 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003648
Chris Lattnerd7beca32010-12-14 06:17:25 +00003649 DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
Dehao Chenf6c00832016-05-18 19:44:21 +00003650 << " cases into SWITCH. BB is:\n"
3651 << *BB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003652
Chris Lattnera69c4432010-12-13 05:03:41 +00003653 // If there are any extra values that couldn't be folded into the switch
3654 // then we evaluate them with an explicit branch first. Split the block
3655 // right before the condbr to handle it.
3656 if (ExtraCase) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003657 BasicBlock *NewBB =
3658 BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
Chris Lattnera69c4432010-12-13 05:03:41 +00003659 // Remove the uncond branch added to the old block.
3660 TerminatorInst *OldTI = BB->getTerminator();
Devang Patel7de6c4b2011-05-18 23:18:47 +00003661 Builder.SetInsertPoint(OldTI);
3662
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003663 if (TrueWhenEqual)
Devang Patel7de6c4b2011-05-18 23:18:47 +00003664 Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
Chris Lattner5a9d59d2010-12-14 05:57:30 +00003665 else
Devang Patel7de6c4b2011-05-18 23:18:47 +00003666 Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003667
Chris Lattnera69c4432010-12-13 05:03:41 +00003668 OldTI->eraseFromParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00003669
Chris Lattnercb570f82010-12-13 05:34:18 +00003670 // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
3671 // for the edge we just added.
Chris Lattner0f4d67b2010-12-14 07:09:42 +00003672 AddPredecessorToBlock(EdgeBB, BB, NewBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003673
Chris Lattnerd7beca32010-12-14 06:17:25 +00003674 DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
Dehao Chenf6c00832016-05-18 19:44:21 +00003675 << "\nEXTRABB = " << *BB);
Chris Lattnera69c4432010-12-13 05:03:41 +00003676 BB = NewBB;
3677 }
Devang Patel7de6c4b2011-05-18 23:18:47 +00003678
3679 Builder.SetInsertPoint(BI);
Chris Lattnera69c4432010-12-13 05:03:41 +00003680 // Convert pointer to int before we switch.
3681 if (CompVal->getType()->isPointerTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003682 CompVal = Builder.CreatePtrToInt(
3683 CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
Chris Lattnera69c4432010-12-13 05:03:41 +00003684 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003685
Chris Lattnera69c4432010-12-13 05:03:41 +00003686 // Create the new switch instruction now.
Devang Patel7de6c4b2011-05-18 23:18:47 +00003687 SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
Devang Patelb849cd52011-05-17 23:29:05 +00003688
Chris Lattnera69c4432010-12-13 05:03:41 +00003689 // Add all of the 'cases' to the switch instruction.
3690 for (unsigned i = 0, e = Values.size(); i != e; ++i)
3691 New->addCase(Values[i], EdgeBB);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003692
Chris Lattnera69c4432010-12-13 05:03:41 +00003693 // We added edges from PI to the EdgeBB. As such, if there were any
3694 // PHI nodes in EdgeBB, they need entries to be added corresponding to
3695 // the number of edges added.
Dehao Chenf6c00832016-05-18 19:44:21 +00003696 for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
Chris Lattnera69c4432010-12-13 05:03:41 +00003697 PHINode *PN = cast<PHINode>(BBI);
3698 Value *InVal = PN->getIncomingValueForBlock(BB);
Dehao Chenf6c00832016-05-18 19:44:21 +00003699 for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
Chris Lattnera69c4432010-12-13 05:03:41 +00003700 PN->addIncoming(InVal, BB);
3701 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00003702
Chris Lattnera69c4432010-12-13 05:03:41 +00003703 // Erase the old branch instruction.
3704 EraseTerminatorInstAndDCECond(BI);
Andrew Trickf3cf1932012-08-29 21:46:36 +00003705
Chris Lattnerd7beca32010-12-14 06:17:25 +00003706 DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
Chris Lattnera69c4432010-12-13 05:03:41 +00003707 return true;
3708}
3709
Duncan Sands29192d02011-09-05 12:57:57 +00003710bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
Chen Li1689c2f2016-01-10 05:48:01 +00003711 if (isa<PHINode>(RI->getValue()))
3712 return SimplifyCommonResume(RI);
3713 else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
3714 RI->getValue() == RI->getParent()->getFirstNonPHI())
3715 // The resume must unwind the exception that caused control to branch here.
3716 return SimplifySingleResume(RI);
Chen Li509ff212016-01-11 19:20:53 +00003717
3718 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003719}
3720
3721// Simplify resume that is shared by several landing pads (phi of landing pad).
3722bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
3723 BasicBlock *BB = RI->getParent();
3724
3725 // Check that there are no other instructions except for debug intrinsics
3726 // between the phi of landing pads (RI->getValue()) and resume instruction.
3727 BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
Dehao Chenf6c00832016-05-18 19:44:21 +00003728 E = RI->getIterator();
Chen Li1689c2f2016-01-10 05:48:01 +00003729 while (++I != E)
3730 if (!isa<DbgInfoIntrinsic>(I))
3731 return false;
3732
Mandeep Singh Grang799a2ed2017-04-24 19:20:45 +00003733 SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
Chen Li1689c2f2016-01-10 05:48:01 +00003734 auto *PhiLPInst = cast<PHINode>(RI->getValue());
3735
3736 // Check incoming blocks to see if any of them are trivial.
Dehao Chenf6c00832016-05-18 19:44:21 +00003737 for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
3738 Idx++) {
Chen Li1689c2f2016-01-10 05:48:01 +00003739 auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
3740 auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
3741
3742 // If the block has other successors, we can not delete it because
3743 // it has other dependents.
3744 if (IncomingBB->getUniqueSuccessor() != BB)
3745 continue;
3746
Dehao Chenf6c00832016-05-18 19:44:21 +00003747 auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
Chen Li1689c2f2016-01-10 05:48:01 +00003748 // Not the landing pad that caused the control to branch here.
3749 if (IncomingValue != LandingPad)
3750 continue;
3751
3752 bool isTrivial = true;
3753
3754 I = IncomingBB->getFirstNonPHI()->getIterator();
3755 E = IncomingBB->getTerminator()->getIterator();
3756 while (++I != E)
3757 if (!isa<DbgInfoIntrinsic>(I)) {
3758 isTrivial = false;
3759 break;
3760 }
3761
3762 if (isTrivial)
3763 TrivialUnwindBlocks.insert(IncomingBB);
3764 }
3765
3766 // If no trivial unwind blocks, don't do any simplifications.
Dehao Chenf6c00832016-05-18 19:44:21 +00003767 if (TrivialUnwindBlocks.empty())
3768 return false;
Chen Li1689c2f2016-01-10 05:48:01 +00003769
3770 // Turn all invokes that unwind here into calls.
3771 for (auto *TrivialBB : TrivialUnwindBlocks) {
3772 // Blocks that will be simplified should be removed from the phi node.
3773 // Note there could be multiple edges to the resume block, and we need
3774 // to remove them all.
3775 while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
3776 BB->removePredecessor(TrivialBB, true);
3777
3778 for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
3779 PI != PE;) {
3780 BasicBlock *Pred = *PI++;
3781 removeUnwindEdge(Pred);
3782 }
3783
3784 // In each SimplifyCFG run, only the current processed block can be erased.
3785 // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
3786 // of erasing TrivialBB, we only remove the branch to the common resume
3787 // block so that we can later erase the resume block since it has no
3788 // predecessors.
3789 TrivialBB->getTerminator()->eraseFromParent();
3790 new UnreachableInst(RI->getContext(), TrivialBB);
3791 }
3792
3793 // Delete the resume block if all its predecessors have been removed.
3794 if (pred_empty(BB))
3795 BB->eraseFromParent();
3796
3797 return !TrivialUnwindBlocks.empty();
3798}
3799
3800// Simplify resume that is only used by a single (non-phi) landing pad.
3801bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
Duncan Sands29192d02011-09-05 12:57:57 +00003802 BasicBlock *BB = RI->getParent();
3803 LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
Dehao Chenf6c00832016-05-18 19:44:21 +00003804 assert(RI->getValue() == LPInst &&
3805 "Resume must unwind the exception that caused control to here");
Duncan Sands29192d02011-09-05 12:57:57 +00003806
Chen Li7009cd32015-10-23 21:13:01 +00003807 // Check that there are no other instructions except for debug intrinsics.
3808 BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
Duncan Sands29192d02011-09-05 12:57:57 +00003809 while (++I != E)
3810 if (!isa<DbgInfoIntrinsic>(I))
3811 return false;
3812
Chen Lic6e28782015-10-22 20:48:38 +00003813 // Turn all invokes that unwind here into calls and delete the basic block.
Chen Li7009cd32015-10-23 21:13:01 +00003814 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3815 BasicBlock *Pred = *PI++;
3816 removeUnwindEdge(Pred);
Chen Lic6e28782015-10-22 20:48:38 +00003817 }
3818
Chen Li7009cd32015-10-23 21:13:01 +00003819 // The landingpad is now unreachable. Zap it.
3820 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00003821 if (LoopHeaders)
3822 LoopHeaders->erase(BB);
Chen Li7009cd32015-10-23 21:13:01 +00003823 return true;
Duncan Sands29192d02011-09-05 12:57:57 +00003824}
3825
David Majnemer1efa23d2016-02-20 01:07:45 +00003826static bool removeEmptyCleanup(CleanupReturnInst *RI) {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003827 // If this is a trivial cleanup pad that executes no instructions, it can be
3828 // eliminated. If the cleanup pad continues to the caller, any predecessor
3829 // that is an EH pad will be updated to continue to the caller and any
3830 // predecessor that terminates with an invoke instruction will have its invoke
3831 // instruction converted to a call instruction. If the cleanup pad being
3832 // simplified does not continue to the caller, each predecessor will be
3833 // updated to continue to the unwind destination of the cleanup pad being
3834 // simplified.
3835 BasicBlock *BB = RI->getParent();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003836 CleanupPadInst *CPInst = RI->getCleanupPad();
3837 if (CPInst->getParent() != BB)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003838 // This isn't an empty cleanup.
3839 return false;
3840
David Majnemer2482e1c2016-06-04 23:50:03 +00003841 // We cannot kill the pad if it has multiple uses. This typically arises
3842 // from unreachable basic blocks.
3843 if (!CPInst->hasOneUse())
3844 return false;
3845
David Majnemer9f92f4c2016-05-21 05:12:32 +00003846 // Check that there are no other instructions except for benign intrinsics.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003847 BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
David Majnemer9f92f4c2016-05-21 05:12:32 +00003848 while (++I != E) {
3849 auto *II = dyn_cast<IntrinsicInst>(I);
3850 if (!II)
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003851 return false;
3852
David Majnemer9f92f4c2016-05-21 05:12:32 +00003853 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
3854 switch (IntrinsicID) {
3855 case Intrinsic::dbg_declare:
3856 case Intrinsic::dbg_value:
3857 case Intrinsic::lifetime_end:
3858 break;
3859 default:
3860 return false;
3861 }
3862 }
3863
David Majnemer8a1c45d2015-12-12 05:38:55 +00003864 // If the cleanup return we are simplifying unwinds to the caller, this will
3865 // set UnwindDest to nullptr.
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003866 BasicBlock *UnwindDest = RI->getUnwindDest();
David Majnemer8a1c45d2015-12-12 05:38:55 +00003867 Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003868
3869 // We're about to remove BB from the control flow. Before we do, sink any
3870 // PHINodes into the unwind destination. Doing this before changing the
3871 // control flow avoids some potentially slow checks, since we can currently
3872 // be certain that UnwindDest and BB have no common predecessors (since they
3873 // are both EH pads).
3874 if (UnwindDest) {
3875 // First, go through the PHI nodes in UnwindDest and update any nodes that
3876 // reference the block we are removing
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003877 for (BasicBlock::iterator I = UnwindDest->begin(),
David Majnemer8a1c45d2015-12-12 05:38:55 +00003878 IE = DestEHPad->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003879 I != IE; ++I) {
3880 PHINode *DestPN = cast<PHINode>(I);
James Molloy4de84dd2015-11-04 15:28:04 +00003881
Andrew Kaylor2a9a6d82015-09-05 01:00:51 +00003882 int Idx = DestPN->getBasicBlockIndex(BB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003883 // Since BB unwinds to UnwindDest, it has to be in the PHI node.
Craig Topper02a55d72015-09-05 04:49:44 +00003884 assert(Idx != -1);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003885 // This PHI node has an incoming value that corresponds to a control
3886 // path through the cleanup pad we are removing. If the incoming
3887 // value is in the cleanup pad, it must be a PHINode (because we
3888 // verified above that the block is otherwise empty). Otherwise, the
3889 // value is either a constant or a value that dominates the cleanup
3890 // pad being removed.
3891 //
3892 // Because BB and UnwindDest are both EH pads, all of their
3893 // predecessors must unwind to these blocks, and since no instruction
3894 // can have multiple unwind destinations, there will be no overlap in
3895 // incoming blocks between SrcPN and DestPN.
3896 Value *SrcVal = DestPN->getIncomingValue(Idx);
3897 PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
3898
3899 // Remove the entry for the block we are deleting.
3900 DestPN->removeIncomingValue(Idx, false);
3901
3902 if (SrcPN && SrcPN->getParent() == BB) {
3903 // If the incoming value was a PHI node in the cleanup pad we are
3904 // removing, we need to merge that PHI node's incoming values into
3905 // DestPN.
James Molloy4de84dd2015-11-04 15:28:04 +00003906 for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
Dehao Chenf6c00832016-05-18 19:44:21 +00003907 SrcIdx != SrcE; ++SrcIdx) {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003908 DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
3909 SrcPN->getIncomingBlock(SrcIdx));
3910 }
3911 } else {
3912 // Otherwise, the incoming value came from above BB and
3913 // so we can just reuse it. We must associate all of BB's
3914 // predecessors with this value.
3915 for (auto *pred : predecessors(BB)) {
3916 DestPN->addIncoming(SrcVal, pred);
3917 }
3918 }
3919 }
3920
3921 // Sink any remaining PHI nodes directly into UnwindDest.
David Majnemer8a1c45d2015-12-12 05:38:55 +00003922 Instruction *InsertPt = DestEHPad;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00003923 for (BasicBlock::iterator I = BB->begin(),
3924 IE = BB->getFirstNonPHI()->getIterator();
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003925 I != IE;) {
3926 // The iterator must be incremented here because the instructions are
3927 // being moved to another block.
3928 PHINode *PN = cast<PHINode>(I++);
3929 if (PN->use_empty())
3930 // If the PHI node has no uses, just leave it. It will be erased
3931 // when we erase BB below.
3932 continue;
3933
3934 // Otherwise, sink this PHI node into UnwindDest.
3935 // Any predecessors to UnwindDest which are not already represented
3936 // must be back edges which inherit the value from the path through
3937 // BB. In this case, the PHI value must reference itself.
3938 for (auto *pred : predecessors(UnwindDest))
3939 if (pred != BB)
3940 PN->addIncoming(PN, pred);
3941 PN->moveBefore(InsertPt);
3942 }
3943 }
3944
3945 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
3946 // The iterator must be updated here because we are removing this pred.
3947 BasicBlock *PredBB = *PI++;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003948 if (UnwindDest == nullptr) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003949 removeUnwindEdge(PredBB);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003950 } else {
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003951 TerminatorInst *TI = PredBB->getTerminator();
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00003952 TI->replaceUsesOfWith(BB, UnwindDest);
Andrew Kaylor50e4e862015-09-04 23:39:40 +00003953 }
3954 }
3955
3956 // The cleanup pad is now unreachable. Zap it.
3957 BB->eraseFromParent();
3958 return true;
3959}
3960
David Majnemer1efa23d2016-02-20 01:07:45 +00003961// Try to merge two cleanuppads together.
3962static bool mergeCleanupPad(CleanupReturnInst *RI) {
3963 // Skip any cleanuprets which unwind to caller, there is nothing to merge
3964 // with.
3965 BasicBlock *UnwindDest = RI->getUnwindDest();
3966 if (!UnwindDest)
3967 return false;
3968
3969 // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
3970 // be safe to merge without code duplication.
3971 if (UnwindDest->getSinglePredecessor() != RI->getParent())
3972 return false;
3973
3974 // Verify that our cleanuppad's unwind destination is another cleanuppad.
3975 auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
3976 if (!SuccessorCleanupPad)
3977 return false;
3978
3979 CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
3980 // Replace any uses of the successor cleanupad with the predecessor pad
3981 // The only cleanuppad uses should be this cleanupret, it's cleanupret and
3982 // funclet bundle operands.
3983 SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
3984 // Remove the old cleanuppad.
3985 SuccessorCleanupPad->eraseFromParent();
3986 // Now, we simply replace the cleanupret with a branch to the unwind
3987 // destination.
3988 BranchInst::Create(UnwindDest, RI->getParent());
3989 RI->eraseFromParent();
3990
3991 return true;
3992}
3993
3994bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00003995 // It is possible to transiantly have an undef cleanuppad operand because we
3996 // have deleted some, but not all, dead blocks.
3997 // Eventually, this block will be deleted.
3998 if (isa<UndefValue>(RI->getOperand(0)))
3999 return false;
4000
David Majnemer9f92f4c2016-05-21 05:12:32 +00004001 if (mergeCleanupPad(RI))
David Majnemer1efa23d2016-02-20 01:07:45 +00004002 return true;
4003
David Majnemer9f92f4c2016-05-21 05:12:32 +00004004 if (removeEmptyCleanup(RI))
David Majnemer1efa23d2016-02-20 01:07:45 +00004005 return true;
4006
4007 return false;
4008}
4009
Devang Pateldd14e0f2011-05-18 21:33:11 +00004010bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004011 BasicBlock *BB = RI->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00004012 if (!BB->getFirstNonPHIOrDbg()->isTerminator())
4013 return false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004014
Chris Lattner25c3af32010-12-13 06:25:44 +00004015 // Find predecessors that end with branches.
Dehao Chenf6c00832016-05-18 19:44:21 +00004016 SmallVector<BasicBlock *, 8> UncondBranchPreds;
4017 SmallVector<BranchInst *, 8> CondBranchPreds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004018 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
4019 BasicBlock *P = *PI;
Chris Lattner25c3af32010-12-13 06:25:44 +00004020 TerminatorInst *PTI = P->getTerminator();
4021 if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
4022 if (BI->isUnconditional())
4023 UncondBranchPreds.push_back(P);
4024 else
4025 CondBranchPreds.push_back(BI);
4026 }
4027 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004028
Chris Lattner25c3af32010-12-13 06:25:44 +00004029 // If we found some, do the transformation!
Evan Chengd983eba2011-01-29 04:46:23 +00004030 if (!UncondBranchPreds.empty() && DupRet) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004031 while (!UncondBranchPreds.empty()) {
4032 BasicBlock *Pred = UncondBranchPreds.pop_back_val();
4033 DEBUG(dbgs() << "FOLDING: " << *BB
Dehao Chenf6c00832016-05-18 19:44:21 +00004034 << "INTO UNCOND BRANCH PRED: " << *Pred);
Evan Chengd983eba2011-01-29 04:46:23 +00004035 (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
Chris Lattner25c3af32010-12-13 06:25:44 +00004036 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004037
Chris Lattner25c3af32010-12-13 06:25:44 +00004038 // If we eliminated all predecessors of the block, delete the block now.
Hyojin Sung4673f102016-03-29 04:08:57 +00004039 if (pred_empty(BB)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004040 // We know there are no successors, so just nuke the block.
4041 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00004042 if (LoopHeaders)
4043 LoopHeaders->erase(BB);
Hyojin Sung4673f102016-03-29 04:08:57 +00004044 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004045
Chris Lattner25c3af32010-12-13 06:25:44 +00004046 return true;
4047 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004048
Chris Lattner25c3af32010-12-13 06:25:44 +00004049 // Check out all of the conditional branches going to this return
4050 // instruction. If any of them just select between returns, change the
4051 // branch itself into a select/return pair.
4052 while (!CondBranchPreds.empty()) {
4053 BranchInst *BI = CondBranchPreds.pop_back_val();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004054
Chris Lattner25c3af32010-12-13 06:25:44 +00004055 // Check to see if the non-BB successor is also a return block.
4056 if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
4057 isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
Devang Pateldd14e0f2011-05-18 21:33:11 +00004058 SimplifyCondBranchToTwoReturns(BI, Builder))
Chris Lattner25c3af32010-12-13 06:25:44 +00004059 return true;
4060 }
4061 return false;
4062}
4063
Chris Lattner25c3af32010-12-13 06:25:44 +00004064bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
4065 BasicBlock *BB = UI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00004066
Chris Lattner25c3af32010-12-13 06:25:44 +00004067 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004068
Chris Lattner25c3af32010-12-13 06:25:44 +00004069 // If there are any instructions immediately before the unreachable that can
4070 // be removed, do so.
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004071 while (UI->getIterator() != BB->begin()) {
4072 BasicBlock::iterator BBI = UI->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00004073 --BBI;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004074 // Do not delete instructions that can have side effects which might cause
4075 // the unreachable to not be reachable; specifically, calls and volatile
4076 // operations may have this effect.
Dehao Chenf6c00832016-05-18 19:44:21 +00004077 if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
4078 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004079
4080 if (BBI->mayHaveSideEffects()) {
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004081 if (auto *SI = dyn_cast<StoreInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004082 if (SI->isVolatile())
4083 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004084 } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004085 if (LI->isVolatile())
4086 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004087 } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004088 if (RMWI->isVolatile())
4089 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004090 } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004091 if (CXI->isVolatile())
4092 break;
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004093 } else if (isa<CatchPadInst>(BBI)) {
4094 // A catchpad may invoke exception object constructors and such, which
4095 // in some languages can be arbitrary code, so be conservative by
4096 // default.
4097 // For CoreCLR, it just involves a type test, so can be removed.
4098 if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
4099 EHPersonality::CoreCLR)
4100 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004101 } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
4102 !isa<LandingPadInst>(BBI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004103 break;
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004104 }
Bill Wendling55d875f2011-08-16 20:41:17 +00004105 // Note that deleting LandingPad's here is in fact okay, although it
4106 // involves a bit of subtle reasoning. If this inst is a LandingPad,
4107 // all the predecessors of this block will be the unwind edges of Invokes,
4108 // and we can therefore guarantee this block will be erased.
Eli Friedman0ffdf2e2011-08-15 23:59:28 +00004109 }
4110
Eli Friedmanaac35b32011-03-09 00:48:33 +00004111 // Delete this instruction (any uses are guaranteed to be dead)
4112 if (!BBI->use_empty())
4113 BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
Chris Lattnerd7beca32010-12-14 06:17:25 +00004114 BBI->eraseFromParent();
Chris Lattner25c3af32010-12-13 06:25:44 +00004115 Changed = true;
4116 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004117
Chris Lattner25c3af32010-12-13 06:25:44 +00004118 // If the unreachable instruction is the first in the block, take a gander
4119 // at all of the predecessors of this instruction, and simplify them.
Dehao Chenf6c00832016-05-18 19:44:21 +00004120 if (&BB->front() != UI)
4121 return Changed;
Andrew Trickf3cf1932012-08-29 21:46:36 +00004122
Dehao Chenf6c00832016-05-18 19:44:21 +00004123 SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
Chris Lattner25c3af32010-12-13 06:25:44 +00004124 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
4125 TerminatorInst *TI = Preds[i]->getTerminator();
Devang Patel31458a02011-05-19 00:09:21 +00004126 IRBuilder<> Builder(TI);
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004127 if (auto *BI = dyn_cast<BranchInst>(TI)) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004128 if (BI->isUnconditional()) {
4129 if (BI->getSuccessor(0) == BB) {
4130 new UnreachableInst(TI->getContext(), TI);
4131 TI->eraseFromParent();
4132 Changed = true;
4133 }
4134 } else {
4135 if (BI->getSuccessor(0) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00004136 Builder.CreateBr(BI->getSuccessor(1));
Chris Lattner25c3af32010-12-13 06:25:44 +00004137 EraseTerminatorInstAndDCECond(BI);
4138 } else if (BI->getSuccessor(1) == BB) {
Devang Patel31458a02011-05-19 00:09:21 +00004139 Builder.CreateBr(BI->getSuccessor(0));
Chris Lattner25c3af32010-12-13 06:25:44 +00004140 EraseTerminatorInstAndDCECond(BI);
4141 Changed = true;
4142 }
4143 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004144 } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
Chandler Carruth0d256c02017-03-26 02:49:23 +00004145 for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004146 if (i->getCaseSuccessor() != BB) {
Chandler Carruth0d256c02017-03-26 02:49:23 +00004147 ++i;
4148 continue;
Chris Lattner25c3af32010-12-13 06:25:44 +00004149 }
Chandler Carruth0d256c02017-03-26 02:49:23 +00004150 BB->removePredecessor(SI->getParent());
4151 i = SI->removeCase(i);
4152 e = SI->case_end();
4153 Changed = true;
4154 }
Joseph Tremoulet0d808882016-01-05 02:37:41 +00004155 } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
4156 if (II->getUnwindDest() == BB) {
4157 removeUnwindEdge(TI->getParent());
4158 Changed = true;
4159 }
4160 } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
4161 if (CSI->getUnwindDest() == BB) {
4162 removeUnwindEdge(TI->getParent());
4163 Changed = true;
4164 continue;
4165 }
4166
4167 for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
4168 E = CSI->handler_end();
4169 I != E; ++I) {
4170 if (*I == BB) {
4171 CSI->removeHandler(I);
4172 --I;
4173 --E;
4174 Changed = true;
4175 }
4176 }
4177 if (CSI->getNumHandlers() == 0) {
4178 BasicBlock *CatchSwitchBB = CSI->getParent();
4179 if (CSI->hasUnwindDest()) {
4180 // Redirect preds to the unwind dest
4181 CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
4182 } else {
4183 // Rewrite all preds to unwind to caller (or from invoke to call).
4184 SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
4185 for (BasicBlock *EHPred : EHPreds)
4186 removeUnwindEdge(EHPred);
4187 }
4188 // The catchswitch is no longer reachable.
4189 new UnreachableInst(CSI->getContext(), CSI);
4190 CSI->eraseFromParent();
4191 Changed = true;
4192 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004193 } else if (isa<CleanupReturnInst>(TI)) {
Joseph Tremoulet09af67a2015-09-27 01:47:46 +00004194 new UnreachableInst(TI->getContext(), TI);
4195 TI->eraseFromParent();
4196 Changed = true;
Chris Lattner25c3af32010-12-13 06:25:44 +00004197 }
4198 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00004199
Chris Lattner25c3af32010-12-13 06:25:44 +00004200 // If this block is now dead, remove it.
Dehao Chenf6c00832016-05-18 19:44:21 +00004201 if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00004202 // We know there are no successors, so just nuke the block.
4203 BB->eraseFromParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00004204 if (LoopHeaders)
4205 LoopHeaders->erase(BB);
Chris Lattner25c3af32010-12-13 06:25:44 +00004206 return true;
4207 }
4208
4209 return Changed;
4210}
4211
Hans Wennborg68000082015-01-26 19:52:32 +00004212static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
4213 assert(Cases.size() >= 1);
4214
4215 array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
4216 for (size_t I = 1, E = Cases.size(); I != E; ++I) {
4217 if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
4218 return false;
4219 }
4220 return true;
4221}
4222
4223/// Turn a switch with two reachable destinations into an integer range
4224/// comparison and branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00004225static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00004226 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004227
Hans Wennborg68000082015-01-26 19:52:32 +00004228 bool HasDefault =
4229 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00004230
Hans Wennborg68000082015-01-26 19:52:32 +00004231 // Partition the cases into two sets with different destinations.
4232 BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
4233 BasicBlock *DestB = nullptr;
Dehao Chenf6c00832016-05-18 19:44:21 +00004234 SmallVector<ConstantInt *, 16> CasesA;
4235 SmallVector<ConstantInt *, 16> CasesB;
Hans Wennborg68000082015-01-26 19:52:32 +00004236
Chandler Carruth927d8e62017-04-12 07:27:28 +00004237 for (auto Case : SI->cases()) {
4238 BasicBlock *Dest = Case.getCaseSuccessor();
Dehao Chenf6c00832016-05-18 19:44:21 +00004239 if (!DestA)
4240 DestA = Dest;
Hans Wennborg68000082015-01-26 19:52:32 +00004241 if (Dest == DestA) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004242 CasesA.push_back(Case.getCaseValue());
Hans Wennborg68000082015-01-26 19:52:32 +00004243 continue;
4244 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004245 if (!DestB)
4246 DestB = Dest;
Hans Wennborg68000082015-01-26 19:52:32 +00004247 if (Dest == DestB) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004248 CasesB.push_back(Case.getCaseValue());
Hans Wennborg68000082015-01-26 19:52:32 +00004249 continue;
4250 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004251 return false; // More than two destinations.
Benjamin Kramer62aa46b2011-02-03 22:51:41 +00004252 }
4253
Dehao Chenf6c00832016-05-18 19:44:21 +00004254 assert(DestA && DestB &&
4255 "Single-destination switch should have been folded.");
Hans Wennborg68000082015-01-26 19:52:32 +00004256 assert(DestA != DestB);
4257 assert(DestB != SI->getDefaultDest());
4258 assert(!CasesB.empty() && "There must be non-default cases.");
4259 assert(!CasesA.empty() || HasDefault);
4260
4261 // Figure out if one of the sets of cases form a contiguous range.
4262 SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
4263 BasicBlock *ContiguousDest = nullptr;
4264 BasicBlock *OtherDest = nullptr;
4265 if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
4266 ContiguousCases = &CasesA;
4267 ContiguousDest = DestA;
4268 OtherDest = DestB;
4269 } else if (CasesAreContiguous(CasesB)) {
4270 ContiguousCases = &CasesB;
4271 ContiguousDest = DestB;
4272 OtherDest = DestA;
4273 } else
4274 return false;
4275
4276 // Start building the compare and branch.
4277
4278 Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
Dehao Chenf6c00832016-05-18 19:44:21 +00004279 Constant *NumCases =
4280 ConstantInt::get(Offset->getType(), ContiguousCases->size());
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004281
Benjamin Kramer8d6a8c12011-02-07 22:37:28 +00004282 Value *Sub = SI->getCondition();
4283 if (!Offset->isNullValue())
Hans Wennborg68000082015-01-26 19:52:32 +00004284 Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
4285
Hans Wennborgc9e1d992013-04-16 08:35:36 +00004286 Value *Cmp;
4287 // If NumCases overflowed, then all possible values jump to the successor.
Hans Wennborg68000082015-01-26 19:52:32 +00004288 if (NumCases->isNullValue() && !ContiguousCases->empty())
Hans Wennborgc9e1d992013-04-16 08:35:36 +00004289 Cmp = ConstantInt::getTrue(SI->getContext());
4290 else
4291 Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
Hans Wennborg68000082015-01-26 19:52:32 +00004292 BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004293
Manman Ren56575552012-09-18 00:47:33 +00004294 // Update weight for the newly-created conditional branch.
Hans Wennborg68000082015-01-26 19:52:32 +00004295 if (HasBranchWeights(SI)) {
4296 SmallVector<uint64_t, 8> Weights;
Manman Ren56575552012-09-18 00:47:33 +00004297 GetBranchWeights(SI, Weights);
4298 if (Weights.size() == 1 + SI->getNumCases()) {
Hans Wennborg68000082015-01-26 19:52:32 +00004299 uint64_t TrueWeight = 0;
4300 uint64_t FalseWeight = 0;
4301 for (size_t I = 0, E = Weights.size(); I != E; ++I) {
4302 if (SI->getSuccessor(I) == ContiguousDest)
4303 TrueWeight += Weights[I];
4304 else
4305 FalseWeight += Weights[I];
4306 }
4307 while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
4308 TrueWeight /= 2;
4309 FalseWeight /= 2;
4310 }
Manman Ren56575552012-09-18 00:47:33 +00004311 NewBI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00004312 MDBuilder(SI->getContext())
4313 .createBranchWeights((uint32_t)TrueWeight,
4314 (uint32_t)FalseWeight));
Manman Ren56575552012-09-18 00:47:33 +00004315 }
4316 }
4317
Hans Wennborg68000082015-01-26 19:52:32 +00004318 // Prune obsolete incoming values off the successors' PHI nodes.
4319 for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
4320 unsigned PreviousEdges = ContiguousCases->size();
Dehao Chenf6c00832016-05-18 19:44:21 +00004321 if (ContiguousDest == SI->getDefaultDest())
4322 ++PreviousEdges;
Hans Wennborg68000082015-01-26 19:52:32 +00004323 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004324 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4325 }
Hans Wennborg68000082015-01-26 19:52:32 +00004326 for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
4327 unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
Dehao Chenf6c00832016-05-18 19:44:21 +00004328 if (OtherDest == SI->getDefaultDest())
4329 ++PreviousEdges;
Hans Wennborg68000082015-01-26 19:52:32 +00004330 for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
4331 cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
4332 }
4333
4334 // Drop the switch.
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00004335 SI->eraseFromParent();
4336
4337 return true;
4338}
Chris Lattner25c3af32010-12-13 06:25:44 +00004339
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004340/// Compute masked bits for the condition of a switch
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004341/// and use it to remove dead cases.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004342static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
4343 const DataLayout &DL) {
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004344 Value *Cond = SI->getCondition();
Matt Arsenault8227b9f2013-09-06 00:37:24 +00004345 unsigned Bits = Cond->getType()->getIntegerBitWidth();
Craig Topper8205a1a2017-05-24 16:53:07 +00004346 KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004347
Sanjay Patel75892a12016-05-20 14:53:09 +00004348 // We can also eliminate cases by determining that their values are outside of
4349 // the limited range of the condition based on how many significant (non-sign)
4350 // bits are in the condition value.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004351 unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
Sanjay Patel75892a12016-05-20 14:53:09 +00004352 unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
4353
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004354 // Gather dead cases.
Dehao Chenf6c00832016-05-18 19:44:21 +00004355 SmallVector<ConstantInt *, 8> DeadCases;
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004356 for (auto &Case : SI->cases()) {
Craig Toppere777fed2017-05-22 00:49:35 +00004357 const APInt &CaseVal = Case.getCaseValue()->getValue();
Craig Topperb45eabc2017-04-26 16:39:58 +00004358 if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
Sanjay Patel75892a12016-05-20 14:53:09 +00004359 (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004360 DeadCases.push_back(Case.getCaseValue());
Sanjay Patel75892a12016-05-20 14:53:09 +00004361 DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal << " is dead.\n");
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004362 }
4363 }
4364
Dehao Chenf6c00832016-05-18 19:44:21 +00004365 // If we can prove that the cases must cover all possible values, the
4366 // default destination becomes dead and we can remove it. If we know some
Philip Reames05370132015-09-10 17:44:47 +00004367 // of the bits in the value, we can use that to more precisely compute the
4368 // number of possible unique case values.
Philip Reames98a2dab2015-08-26 23:56:46 +00004369 bool HasDefault =
Dehao Chenf6c00832016-05-18 19:44:21 +00004370 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
4371 const unsigned NumUnknownBits =
Craig Topperb45eabc2017-04-26 16:39:58 +00004372 Bits - (Known.Zero | Known.One).countPopulation();
Filipe Cabecinhas48b090a2015-09-10 22:34:39 +00004373 assert(NumUnknownBits <= Bits);
Philip Reames05370132015-09-10 17:44:47 +00004374 if (HasDefault && DeadCases.empty() &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004375 NumUnknownBits < 64 /* avoid overflow */ &&
Philip Reames05370132015-09-10 17:44:47 +00004376 SI->getNumCases() == (1ULL << NumUnknownBits)) {
Philip Reames98a2dab2015-08-26 23:56:46 +00004377 DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
Dehao Chenf6c00832016-05-18 19:44:21 +00004378 BasicBlock *NewDefault =
4379 SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), "");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004380 SI->setDefaultDest(&*NewDefault);
4381 SplitBlock(&*NewDefault, &NewDefault->front());
Philip Reames98a2dab2015-08-26 23:56:46 +00004382 auto *OldTI = NewDefault->getTerminator();
4383 new UnreachableInst(SI->getContext(), OldTI);
4384 EraseTerminatorInstAndDCECond(OldTI);
4385 return true;
4386 }
4387
Manman Ren56575552012-09-18 00:47:33 +00004388 SmallVector<uint64_t, 8> Weights;
4389 bool HasWeight = HasBranchWeights(SI);
4390 if (HasWeight) {
4391 GetBranchWeights(SI, Weights);
4392 HasWeight = (Weights.size() == 1 + SI->getNumCases());
4393 }
4394
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004395 // Remove dead cases from the switch.
Sanjay Patel5d5134f2016-05-13 20:24:53 +00004396 for (ConstantInt *DeadCase : DeadCases) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004397 SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
4398 assert(CaseI != SI->case_default() &&
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +00004399 "Case was not found. Probably mistake in DeadCases forming.");
Manman Ren56575552012-09-18 00:47:33 +00004400 if (HasWeight) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00004401 std::swap(Weights[CaseI->getCaseIndex() + 1], Weights.back());
Manman Ren56575552012-09-18 00:47:33 +00004402 Weights.pop_back();
4403 }
4404
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004405 // Prune unused values from PHI nodes.
Chandler Carruth927d8e62017-04-12 07:27:28 +00004406 CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
4407 SI->removeCase(CaseI);
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004408 }
Justin Bogner0ba3f212013-12-20 08:21:30 +00004409 if (HasWeight && Weights.size() >= 2) {
Manman Ren56575552012-09-18 00:47:33 +00004410 SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
4411 SI->setMetadata(LLVMContext::MD_prof,
Dehao Chenf6c00832016-05-18 19:44:21 +00004412 MDBuilder(SI->getParent()->getContext())
4413 .createBranchWeights(MDWeights));
Manman Ren56575552012-09-18 00:47:33 +00004414 }
Benjamin Kramerd96205c2011-05-14 15:57:25 +00004415
4416 return !DeadCases.empty();
4417}
4418
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004419/// If BB would be eligible for simplification by
4420/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004421/// by an unconditional branch), look at the phi node for BB in the successor
4422/// block and see if the incoming value is equal to CaseValue. If so, return
4423/// the phi node, and set PhiIndex to BB's index in the phi node.
4424static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
Dehao Chenf6c00832016-05-18 19:44:21 +00004425 BasicBlock *BB, int *PhiIndex) {
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004426 if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
Craig Topperf40110f2014-04-25 05:29:35 +00004427 return nullptr; // BB must be empty to be a candidate for simplification.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004428 if (!BB->getSinglePredecessor())
Craig Topperf40110f2014-04-25 05:29:35 +00004429 return nullptr; // BB must be dominated by the switch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004430
4431 BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
4432 if (!Branch || !Branch->isUnconditional())
Craig Topperf40110f2014-04-25 05:29:35 +00004433 return nullptr; // Terminator must be unconditional branch.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004434
4435 BasicBlock *Succ = Branch->getSuccessor(0);
4436
4437 BasicBlock::iterator I = Succ->begin();
4438 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4439 int Idx = PHI->getBasicBlockIndex(BB);
4440 assert(Idx >= 0 && "PHI has no entry for predecessor?");
4441
4442 Value *InValue = PHI->getIncomingValue(Idx);
Dehao Chenf6c00832016-05-18 19:44:21 +00004443 if (InValue != CaseValue)
4444 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004445
4446 *PhiIndex = Idx;
4447 return PHI;
4448 }
4449
Craig Topperf40110f2014-04-25 05:29:35 +00004450 return nullptr;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004451}
4452
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004453/// Try to forward the condition of a switch instruction to a phi node
4454/// dominated by the switch, if that would mean that some of the destination
4455/// blocks of the switch can be folded away.
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004456/// Returns true if a change is made.
4457static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
Dehao Chenf6c00832016-05-18 19:44:21 +00004458 typedef DenseMap<PHINode *, SmallVector<int, 4>> ForwardingNodesMap;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004459 ForwardingNodesMap ForwardingNodes;
4460
Chandler Carruth927d8e62017-04-12 07:27:28 +00004461 for (auto Case : SI->cases()) {
4462 ConstantInt *CaseValue = Case.getCaseValue();
4463 BasicBlock *CaseDest = Case.getCaseSuccessor();
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004464
4465 int PhiIndex;
Dehao Chenf6c00832016-05-18 19:44:21 +00004466 PHINode *PHI =
4467 FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIndex);
4468 if (!PHI)
4469 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004470
4471 ForwardingNodes[PHI].push_back(PhiIndex);
4472 }
4473
4474 bool Changed = false;
4475
4476 for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
Dehao Chenf6c00832016-05-18 19:44:21 +00004477 E = ForwardingNodes.end();
4478 I != E; ++I) {
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004479 PHINode *Phi = I->first;
Craig Topperb94011f2013-07-14 04:42:23 +00004480 SmallVectorImpl<int> &Indexes = I->second;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004481
Dehao Chenf6c00832016-05-18 19:44:21 +00004482 if (Indexes.size() < 2)
4483 continue;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00004484
4485 for (size_t I = 0, E = Indexes.size(); I != E; ++I)
4486 Phi->setIncomingValue(Indexes[I], SI->getCondition());
4487 Changed = true;
4488 }
4489
4490 return Changed;
4491}
4492
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004493/// Return true if the backend will be able to handle
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004494/// initializing an array of constants like C.
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004495static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
Hans Wennborg4dc89512014-06-20 00:38:12 +00004496 if (C->isThreadDependent())
4497 return false;
4498 if (C->isDLLImportDependent())
4499 return false;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004500
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004501 if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
4502 !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
4503 !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
4504 return false;
Hans Wennborgb03ebfb2014-06-26 00:30:52 +00004505
Oliver Stannardfe4432b2016-10-17 12:00:24 +00004506 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004507 if (!CE->isGEPWithNoNotionalOverIndexing())
4508 return false;
Oliver Stannardfe4432b2016-10-17 12:00:24 +00004509 if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
4510 return false;
4511 }
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004512
4513 if (!TTI.shouldBuildLookupTablesForConstant(C))
4514 return false;
4515
4516 return true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004517}
4518
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004519/// If V is a Constant, return it. Otherwise, try to look up
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004520/// its constant value in ConstantPool, returning 0 if it's not there.
Dehao Chenf6c00832016-05-18 19:44:21 +00004521static Constant *
4522LookupConstant(Value *V,
4523 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00004524 if (Constant *C = dyn_cast<Constant>(V))
4525 return C;
4526 return ConstantPool.lookup(V);
4527}
4528
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004529/// Try to fold instruction I into a constant. This works for
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004530/// simple instructions such as binary operations where both operands are
4531/// constant or can be replaced by constants from the ConstantPool. Returns the
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004532/// resulting constant on success, 0 otherwise.
Benjamin Kramer7c302602013-11-12 12:24:36 +00004533static Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004534ConstantFold(Instruction *I, const DataLayout &DL,
4535 const SmallDenseMap<Value *, Constant *> &ConstantPool) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004536 if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Hans Wennborg09acdb92012-10-31 15:14:39 +00004537 Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
4538 if (!A)
Craig Topperf40110f2014-04-25 05:29:35 +00004539 return nullptr;
Hans Wennborg09acdb92012-10-31 15:14:39 +00004540 if (A->isAllOnesValue())
4541 return LookupConstant(Select->getTrueValue(), ConstantPool);
4542 if (A->isNullValue())
4543 return LookupConstant(Select->getFalseValue(), ConstantPool);
Craig Topperf40110f2014-04-25 05:29:35 +00004544 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004545 }
4546
Benjamin Kramer7c302602013-11-12 12:24:36 +00004547 SmallVector<Constant *, 4> COps;
4548 for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
4549 if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
4550 COps.push_back(A);
4551 else
Craig Topperf40110f2014-04-25 05:29:35 +00004552 return nullptr;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004553 }
4554
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004555 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
Benjamin Kramer7c302602013-11-12 12:24:36 +00004556 return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
4557 COps[1], DL);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004558 }
Benjamin Kramer7c302602013-11-12 12:24:36 +00004559
Manuel Jacobe9024592016-01-21 06:33:22 +00004560 return ConstantFoldInstOperands(I, COps, DL);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004561}
4562
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004563/// Try to determine the resulting constant values in phi nodes
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004564/// at the common destination basic block, *CommonDest, for one of the case
Hans Wennborg4fef2fe2012-10-31 15:31:09 +00004565/// destionations CaseDest corresponding to value CaseVal (0 for the default
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004566/// case), of a switch instruction SI.
Craig Topperb94011f2013-07-14 04:42:23 +00004567static bool
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004568GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
Craig Topperb94011f2013-07-14 04:42:23 +00004569 BasicBlock **CommonDest,
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004570 SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004571 const DataLayout &DL, const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004572 // The block from which we enter the common destination.
4573 BasicBlock *Pred = SI->getParent();
4574
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004575 // If CaseDest is empty except for some side-effect free instructions through
4576 // which we can constant-propagate the CaseVal, continue to its successor.
Dehao Chenf6c00832016-05-18 19:44:21 +00004577 SmallDenseMap<Value *, Constant *> ConstantPool;
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004578 ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
4579 for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
4580 ++I) {
4581 if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
4582 // If the terminator is a simple branch, continue to the next block.
David Majnemer8c03c1b2016-10-07 01:38:35 +00004583 if (T->getNumSuccessors() != 1 || T->isExceptional())
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004584 return false;
4585 Pred = CaseDest;
4586 CaseDest = T->getSuccessor(0);
4587 } else if (isa<DbgInfoIntrinsic>(I)) {
4588 // Skip debug intrinsic.
4589 continue;
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004590 } else if (Constant *C = ConstantFold(&*I, DL, ConstantPool)) {
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004591 // Instruction is side-effect free and constant.
Hans Wennborgdcc6e5b2015-01-09 22:13:31 +00004592
4593 // If the instruction has uses outside this block or a phi node slot for
4594 // the block, it is not safe to bypass the instruction since it would then
4595 // no longer dominate all its uses.
4596 for (auto &Use : I->uses()) {
4597 User *User = Use.getUser();
4598 if (Instruction *I = dyn_cast<Instruction>(User))
4599 if (I->getParent() == CaseDest)
4600 continue;
4601 if (PHINode *Phi = dyn_cast<PHINode>(User))
4602 if (Phi->getIncomingBlock(Use) == CaseDest)
4603 continue;
4604 return false;
4605 }
4606
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +00004607 ConstantPool.insert(std::make_pair(&*I, C));
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004608 } else {
4609 break;
4610 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004611 }
4612
4613 // If we did not have a CommonDest before, use the current one.
4614 if (!*CommonDest)
4615 *CommonDest = CaseDest;
4616 // If the destination isn't the common one, abort.
4617 if (CaseDest != *CommonDest)
4618 return false;
4619
4620 // Get the values for this case from phi nodes in the destination block.
4621 BasicBlock::iterator I = (*CommonDest)->begin();
4622 while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
4623 int Idx = PHI->getBasicBlockIndex(Pred);
4624 if (Idx == -1)
4625 continue;
4626
Dehao Chenf6c00832016-05-18 19:44:21 +00004627 Constant *ConstVal =
4628 LookupConstant(PHI->getIncomingValue(Idx), ConstantPool);
Hans Wennborg9e74dd92012-10-31 13:42:45 +00004629 if (!ConstVal)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004630 return false;
4631
4632 // Be conservative about which kinds of constants we support.
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004633 if (!ValidLookupTableConstant(ConstVal, TTI))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004634 return false;
4635
4636 Res.push_back(std::make_pair(PHI, ConstVal));
4637 }
4638
Hans Wennborgac114a32014-01-12 00:44:41 +00004639 return Res.size() > 0;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004640}
4641
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004642// Helper function used to add CaseVal to the list of cases that generate
4643// Result.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004644static void MapCaseToResult(ConstantInt *CaseVal,
Dehao Chenf6c00832016-05-18 19:44:21 +00004645 SwitchCaseResultVectorTy &UniqueResults,
4646 Constant *Result) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004647 for (auto &I : UniqueResults) {
4648 if (I.first == Result) {
4649 I.second.push_back(CaseVal);
4650 return;
4651 }
4652 }
Dehao Chenf6c00832016-05-18 19:44:21 +00004653 UniqueResults.push_back(
4654 std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004655}
4656
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004657// Helper function that initializes a map containing
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004658// results for the PHI node of the common destination block for a switch
4659// instruction. Returns false if multiple PHI nodes have been found or if
4660// there is not a common destination block for the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004661static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
4662 BasicBlock *&CommonDest,
4663 SwitchCaseResultVectorTy &UniqueResults,
4664 Constant *&DefaultResult,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004665 const DataLayout &DL,
4666 const TargetTransformInfo &TTI) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004667 for (auto &I : SI->cases()) {
4668 ConstantInt *CaseVal = I.getCaseValue();
4669
4670 // Resulting value at phi nodes for this case value.
4671 SwitchCaseResultsTy Results;
4672 if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004673 DL, TTI))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004674 return false;
4675
4676 // Only one value per case is permitted
4677 if (Results.size() > 1)
4678 return false;
4679 MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
4680
4681 // Check the PHI consistency.
4682 if (!PHI)
4683 PHI = Results[0].first;
4684 else if (PHI != Results[0].first)
4685 return false;
4686 }
4687 // Find the default result value.
4688 SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
4689 BasicBlock *DefaultDest = SI->getDefaultDest();
4690 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004691 DL, TTI);
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004692 // If the default value is not found abort unless the default destination
4693 // is unreachable.
4694 DefaultResult =
4695 DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
4696 if ((!DefaultResult &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004697 !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004698 return false;
4699
4700 return true;
4701}
4702
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004703// Helper function that checks if it is possible to transform a switch with only
4704// two cases (or two cases + default) that produces a result into a select.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004705// Example:
4706// switch (a) {
4707// case 10: %0 = icmp eq i32 %a, 10
4708// return 10; %1 = select i1 %0, i32 10, i32 4
4709// case 20: ----> %2 = icmp eq i32 %a, 20
4710// return 2; %3 = select i1 %2, i32 2, i32 %1
4711// default:
4712// return 4;
4713// }
Dehao Chenf6c00832016-05-18 19:44:21 +00004714static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
4715 Constant *DefaultResult, Value *Condition,
4716 IRBuilder<> &Builder) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004717 assert(ResultVector.size() == 2 &&
Dehao Chenf6c00832016-05-18 19:44:21 +00004718 "We should have exactly two unique results at this point");
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004719 // If we are selecting between only two cases transform into a simple
4720 // select or a two-way select if default is possible.
4721 if (ResultVector[0].second.size() == 1 &&
4722 ResultVector[1].second.size() == 1) {
4723 ConstantInt *const FirstCase = ResultVector[0].second[0];
4724 ConstantInt *const SecondCase = ResultVector[1].second[0];
4725
4726 bool DefaultCanTrigger = DefaultResult;
4727 Value *SelectValue = ResultVector[1].first;
4728 if (DefaultCanTrigger) {
4729 Value *const ValueCompare =
4730 Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
4731 SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
4732 DefaultResult, "switch.select");
4733 }
4734 Value *const ValueCompare =
4735 Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
Dehao Chenf6c00832016-05-18 19:44:21 +00004736 return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
4737 SelectValue, "switch.select");
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004738 }
4739
4740 return nullptr;
4741}
4742
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004743// Helper function to cleanup a switch instruction that has been converted into
4744// a select, fixing up PHI nodes and basic blocks.
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004745static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
4746 Value *SelectValue,
4747 IRBuilder<> &Builder) {
4748 BasicBlock *SelectBB = SI->getParent();
4749 while (PHI->getBasicBlockIndex(SelectBB) >= 0)
4750 PHI->removeIncomingValue(SelectBB);
4751 PHI->addIncoming(SelectValue, SelectBB);
4752
4753 Builder.CreateBr(PHI->getParent());
4754
4755 // Remove the switch.
4756 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
4757 BasicBlock *Succ = SI->getSuccessor(i);
4758
4759 if (Succ == PHI->getParent())
4760 continue;
4761 Succ->removePredecessor(SelectBB);
4762 }
4763 SI->eraseFromParent();
4764}
4765
Sanjay Patel09159b8f2015-06-24 20:40:57 +00004766/// If the switch is only used to initialize one or more
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004767/// phi nodes in a common successor block with only two different
4768/// constant values, replace the switch with select.
4769static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004770 AssumptionCache *AC, const DataLayout &DL,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004771 const TargetTransformInfo &TTI) {
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004772 Value *const Cond = SI->getCondition();
4773 PHINode *PHI = nullptr;
4774 BasicBlock *CommonDest = nullptr;
4775 Constant *DefaultResult;
4776 SwitchCaseResultVectorTy UniqueResults;
4777 // Collect all the cases that will deliver the same value from the switch.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004778 if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00004779 DL, TTI))
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004780 return false;
4781 // Selects choose between maximum two values.
4782 if (UniqueResults.size() != 2)
4783 return false;
4784 assert(PHI != nullptr && "PHI for value select not found");
4785
4786 Builder.SetInsertPoint(SI);
Dehao Chenf6c00832016-05-18 19:44:21 +00004787 Value *SelectValue =
4788 ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00004789 if (SelectValue) {
4790 RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
4791 return true;
4792 }
4793 // The switch couldn't be converted into a select.
4794 return false;
4795}
4796
Hans Wennborg776d7122012-09-26 09:34:53 +00004797namespace {
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004798
Dehao Chenf6c00832016-05-18 19:44:21 +00004799/// This class represents a lookup table that can be used to replace a switch.
4800class SwitchLookupTable {
4801public:
4802 /// Create a lookup table to use as a switch replacement with the contents
4803 /// of Values, using DefaultValue to fill any holes in the table.
4804 SwitchLookupTable(
4805 Module &M, uint64_t TableSize, ConstantInt *Offset,
4806 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
Sumanth Gundapaneni5372f0a2017-06-30 20:00:01 +00004807 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
Hans Wennborg776d7122012-09-26 09:34:53 +00004808
Dehao Chenf6c00832016-05-18 19:44:21 +00004809 /// Build instructions with Builder to retrieve the value at
4810 /// the position given by Index in the lookup table.
4811 Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
Hans Wennborg776d7122012-09-26 09:34:53 +00004812
Dehao Chenf6c00832016-05-18 19:44:21 +00004813 /// Return true if a table with TableSize elements of
4814 /// type ElementType would fit in a target-legal register.
4815 static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
4816 Type *ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004817
Dehao Chenf6c00832016-05-18 19:44:21 +00004818private:
4819 // Depending on the contents of the table, it can be represented in
4820 // different ways.
4821 enum {
4822 // For tables where each element contains the same value, we just have to
4823 // store that single value and return it for each lookup.
4824 SingleValueKind,
Hans Wennborg776d7122012-09-26 09:34:53 +00004825
Dehao Chenf6c00832016-05-18 19:44:21 +00004826 // For tables where there is a linear relationship between table index
4827 // and values. We calculate the result with a simple multiplication
4828 // and addition instead of a table lookup.
4829 LinearMapKind,
Erik Eckstein105374f2014-11-17 09:13:57 +00004830
Dehao Chenf6c00832016-05-18 19:44:21 +00004831 // For small tables with integer elements, we can pack them into a bitmap
4832 // that fits into a target-legal register. Values are retrieved by
4833 // shift and mask operations.
4834 BitMapKind,
Hans Wennborg39583b82012-09-26 09:44:49 +00004835
Dehao Chenf6c00832016-05-18 19:44:21 +00004836 // The table is stored as an array of values. Values are retrieved by load
4837 // instructions from the table.
4838 ArrayKind
4839 } Kind;
Hans Wennborg776d7122012-09-26 09:34:53 +00004840
Dehao Chenf6c00832016-05-18 19:44:21 +00004841 // For SingleValueKind, this is the single value.
4842 Constant *SingleValue;
Hans Wennborg776d7122012-09-26 09:34:53 +00004843
Dehao Chenf6c00832016-05-18 19:44:21 +00004844 // For BitMapKind, this is the bitmap.
4845 ConstantInt *BitMap;
4846 IntegerType *BitMapElementTy;
Hans Wennborg39583b82012-09-26 09:44:49 +00004847
Dehao Chenf6c00832016-05-18 19:44:21 +00004848 // For LinearMapKind, these are the constants used to derive the value.
4849 ConstantInt *LinearOffset;
4850 ConstantInt *LinearMultiplier;
Erik Eckstein105374f2014-11-17 09:13:57 +00004851
Dehao Chenf6c00832016-05-18 19:44:21 +00004852 // For ArrayKind, this is the array.
4853 GlobalVariable *Array;
4854};
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00004855
4856} // end anonymous namespace
Hans Wennborg776d7122012-09-26 09:34:53 +00004857
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004858SwitchLookupTable::SwitchLookupTable(
4859 Module &M, uint64_t TableSize, ConstantInt *Offset,
4860 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
Sumanth Gundapaneni5372f0a2017-06-30 20:00:01 +00004861 Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName)
Craig Topperf40110f2014-04-25 05:29:35 +00004862 : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
Erik Eckstein105374f2014-11-17 09:13:57 +00004863 LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00004864 assert(Values.size() && "Can't build lookup table without values!");
4865 assert(TableSize >= Values.size() && "Can't fit values in table!");
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004866
4867 // If all values in the table are equal, this is that value.
Hans Wennborg776d7122012-09-26 09:34:53 +00004868 SingleValue = Values.begin()->second;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004869
Hans Wennborgac114a32014-01-12 00:44:41 +00004870 Type *ValueType = Values.begin()->second->getType();
4871
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004872 // Build up the table contents.
Dehao Chenf6c00832016-05-18 19:44:21 +00004873 SmallVector<Constant *, 64> TableContents(TableSize);
Hans Wennborg776d7122012-09-26 09:34:53 +00004874 for (size_t I = 0, E = Values.size(); I != E; ++I) {
4875 ConstantInt *CaseVal = Values[I].first;
4876 Constant *CaseRes = Values[I].second;
Hans Wennborgac114a32014-01-12 00:44:41 +00004877 assert(CaseRes->getType() == ValueType);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004878
Dehao Chenf6c00832016-05-18 19:44:21 +00004879 uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004880 TableContents[Idx] = CaseRes;
4881
Hans Wennborg776d7122012-09-26 09:34:53 +00004882 if (CaseRes != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004883 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004884 }
4885
4886 // Fill in any holes in the table with the default result.
Hans Wennborg776d7122012-09-26 09:34:53 +00004887 if (Values.size() < TableSize) {
Marcello Maggioni89c05ad2014-07-03 08:29:06 +00004888 assert(DefaultValue &&
4889 "Need a default value to fill the lookup table holes.");
Hans Wennborgac114a32014-01-12 00:44:41 +00004890 assert(DefaultValue->getType() == ValueType);
Hans Wennborg776d7122012-09-26 09:34:53 +00004891 for (uint64_t I = 0; I < TableSize; ++I) {
4892 if (!TableContents[I])
4893 TableContents[I] = DefaultValue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004894 }
4895
Hans Wennborg776d7122012-09-26 09:34:53 +00004896 if (DefaultValue != SingleValue)
Craig Topperf40110f2014-04-25 05:29:35 +00004897 SingleValue = nullptr;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004898 }
4899
Hans Wennborg776d7122012-09-26 09:34:53 +00004900 // If each element in the table contains the same value, we only need to store
4901 // that single value.
4902 if (SingleValue) {
4903 Kind = SingleValueKind;
4904 return;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004905 }
4906
Erik Eckstein105374f2014-11-17 09:13:57 +00004907 // Check if we can derive the value with a linear transformation from the
4908 // table index.
4909 if (isa<IntegerType>(ValueType)) {
4910 bool LinearMappingPossible = true;
4911 APInt PrevVal;
4912 APInt DistToPrev;
4913 assert(TableSize >= 2 && "Should be a SingleValue table.");
4914 // Check if there is the same distance between two consecutive values.
4915 for (uint64_t I = 0; I < TableSize; ++I) {
4916 ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
4917 if (!ConstVal) {
4918 // This is an undef. We could deal with it, but undefs in lookup tables
4919 // are very seldom. It's probably not worth the additional complexity.
4920 LinearMappingPossible = false;
4921 break;
4922 }
Craig Toppere777fed2017-05-22 00:49:35 +00004923 const APInt &Val = ConstVal->getValue();
Erik Eckstein105374f2014-11-17 09:13:57 +00004924 if (I != 0) {
4925 APInt Dist = Val - PrevVal;
4926 if (I == 1) {
4927 DistToPrev = Dist;
4928 } else if (Dist != DistToPrev) {
4929 LinearMappingPossible = false;
4930 break;
4931 }
4932 }
4933 PrevVal = Val;
4934 }
4935 if (LinearMappingPossible) {
4936 LinearOffset = cast<ConstantInt>(TableContents[0]);
4937 LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
4938 Kind = LinearMapKind;
4939 ++NumLinearMaps;
4940 return;
4941 }
4942 }
4943
Hans Wennborg39583b82012-09-26 09:44:49 +00004944 // If the type is integer and the table fits in a register, build a bitmap.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004945 if (WouldFitInRegister(DL, TableSize, ValueType)) {
Hans Wennborgac114a32014-01-12 00:44:41 +00004946 IntegerType *IT = cast<IntegerType>(ValueType);
Hans Wennborg39583b82012-09-26 09:44:49 +00004947 APInt TableInt(TableSize * IT->getBitWidth(), 0);
4948 for (uint64_t I = TableSize; I > 0; --I) {
4949 TableInt <<= IT->getBitWidth();
Benjamin Kramer9fc3dc72012-10-01 11:31:48 +00004950 // Insert values into the bitmap. Undef values are set to zero.
4951 if (!isa<UndefValue>(TableContents[I - 1])) {
4952 ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
4953 TableInt |= Val->getValue().zext(TableInt.getBitWidth());
4954 }
Hans Wennborg39583b82012-09-26 09:44:49 +00004955 }
4956 BitMap = ConstantInt::get(M.getContext(), TableInt);
4957 BitMapElementTy = IT;
4958 Kind = BitMapKind;
4959 ++NumBitMaps;
4960 return;
4961 }
4962
Hans Wennborg776d7122012-09-26 09:34:53 +00004963 // Store the table in an array.
Hans Wennborgac114a32014-01-12 00:44:41 +00004964 ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00004965 Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
4966
Dehao Chenf6c00832016-05-18 19:44:21 +00004967 Array = new GlobalVariable(M, ArrayTy, /*constant=*/true,
4968 GlobalVariable::PrivateLinkage, Initializer,
Sumanth Gundapaneni5372f0a2017-06-30 20:00:01 +00004969 "switch.table." + FuncName);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00004970 Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Hans Wennborg776d7122012-09-26 09:34:53 +00004971 Kind = ArrayKind;
4972}
4973
Manman Ren4d189fb2014-07-24 21:13:20 +00004974Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
Hans Wennborg776d7122012-09-26 09:34:53 +00004975 switch (Kind) {
Dehao Chenf6c00832016-05-18 19:44:21 +00004976 case SingleValueKind:
4977 return SingleValue;
4978 case LinearMapKind: {
4979 // Derive the result value from the input value.
4980 Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
4981 false, "switch.idx.cast");
4982 if (!LinearMultiplier->isOne())
4983 Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
4984 if (!LinearOffset->isZero())
4985 Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
4986 return Result;
4987 }
4988 case BitMapKind: {
4989 // Type of the bitmap (e.g. i59).
4990 IntegerType *MapTy = BitMap->getType();
Hans Wennborg39583b82012-09-26 09:44:49 +00004991
Dehao Chenf6c00832016-05-18 19:44:21 +00004992 // Cast Index to the same type as the bitmap.
4993 // Note: The Index is <= the number of elements in the table, so
4994 // truncating it to the width of the bitmask is safe.
4995 Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
Hans Wennborg39583b82012-09-26 09:44:49 +00004996
Dehao Chenf6c00832016-05-18 19:44:21 +00004997 // Multiply the shift amount by the element width.
4998 ShiftAmt = Builder.CreateMul(
4999 ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
5000 "switch.shiftamt");
Hans Wennborg39583b82012-09-26 09:44:49 +00005001
Dehao Chenf6c00832016-05-18 19:44:21 +00005002 // Shift down.
5003 Value *DownShifted =
5004 Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
5005 // Mask off.
5006 return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
5007 }
5008 case ArrayKind: {
5009 // Make sure the table index will not overflow when treated as signed.
5010 IntegerType *IT = cast<IntegerType>(Index->getType());
5011 uint64_t TableSize =
5012 Array->getInitializer()->getType()->getArrayNumElements();
5013 if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
5014 Index = Builder.CreateZExt(
5015 Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
5016 "switch.tableidx.zext");
Manman Renedc60372014-07-23 23:13:23 +00005017
Dehao Chenf6c00832016-05-18 19:44:21 +00005018 Value *GEPIndices[] = {Builder.getInt32(0), Index};
5019 Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
5020 GEPIndices, "switch.gep");
5021 return Builder.CreateLoad(GEP, "switch.load");
5022 }
Hans Wennborg776d7122012-09-26 09:34:53 +00005023 }
5024 llvm_unreachable("Unknown lookup table kind!");
5025}
5026
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005027bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
Hans Wennborg39583b82012-09-26 09:44:49 +00005028 uint64_t TableSize,
Craig Toppere3dcce92015-08-01 22:20:21 +00005029 Type *ElementType) {
5030 auto *IT = dyn_cast<IntegerType>(ElementType);
Hans Wennborg39583b82012-09-26 09:44:49 +00005031 if (!IT)
5032 return false;
5033 // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
5034 // are <= 15, we could try to narrow the type.
Benjamin Kramerc2081d12012-09-27 18:29:58 +00005035
5036 // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
Dehao Chenf6c00832016-05-18 19:44:21 +00005037 if (TableSize >= UINT_MAX / IT->getBitWidth())
Benjamin Kramerc2081d12012-09-27 18:29:58 +00005038 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005039 return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
Hans Wennborg39583b82012-09-26 09:44:49 +00005040}
5041
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005042/// Determine whether a lookup table should be built for this switch, based on
5043/// the number of cases, size of the table, and the types of the results.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005044static bool
5045ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
5046 const TargetTransformInfo &TTI, const DataLayout &DL,
5047 const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
Hans Wennborgf2e2c102012-09-26 11:07:37 +00005048 if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
5049 return false; // TableSize overflowed, or mul below might overflow.
Hans Wennborg776d7122012-09-26 09:34:53 +00005050
Chandler Carruth77d433d2012-11-30 09:26:25 +00005051 bool AllTablesFitInRegister = true;
Evan Cheng65df8082012-11-30 02:02:42 +00005052 bool HasIllegalType = false;
Hans Wennborga6a11a92014-11-18 02:37:11 +00005053 for (const auto &I : ResultTypes) {
5054 Type *Ty = I.second;
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00005055
5056 // Saturate this flag to true.
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00005057 HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00005058
5059 // Saturate this flag to false.
Dehao Chenf6c00832016-05-18 19:44:21 +00005060 AllTablesFitInRegister =
5061 AllTablesFitInRegister &&
5062 SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
Chandler Carruthd9ef81e2012-11-30 09:34:29 +00005063
5064 // If both flags saturate, we're done. NOTE: This *only* works with
5065 // saturating flags, and all flags have to saturate first due to the
5066 // non-deterministic behavior of iterating over a dense map.
5067 if (HasIllegalType && !AllTablesFitInRegister)
Evan Cheng65df8082012-11-30 02:02:42 +00005068 break;
Hans Wennborg39583b82012-09-26 09:44:49 +00005069 }
Evan Cheng65df8082012-11-30 02:02:42 +00005070
Chandler Carruth77d433d2012-11-30 09:26:25 +00005071 // If each table would fit in a register, we should build it anyway.
5072 if (AllTablesFitInRegister)
5073 return true;
5074
5075 // Don't build a table that doesn't fit in-register if it has illegal types.
5076 if (HasIllegalType)
5077 return false;
5078
5079 // The table density should be at least 40%. This is the same criterion as for
5080 // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
5081 // FIXME: Find the best cut-off.
5082 return SI->getNumCases() * 10 >= TableSize * 4;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005083}
5084
Erik Eckstein0d86c762014-11-27 15:13:14 +00005085/// Try to reuse the switch table index compare. Following pattern:
5086/// \code
5087/// if (idx < tablesize)
5088/// r = table[idx]; // table does not contain default_value
5089/// else
5090/// r = default_value;
5091/// if (r != default_value)
5092/// ...
5093/// \endcode
5094/// Is optimized to:
5095/// \code
5096/// cond = idx < tablesize;
5097/// if (cond)
5098/// r = table[idx];
5099/// else
5100/// r = default_value;
5101/// if (cond)
5102/// ...
5103/// \endcode
5104/// Jump threading will then eliminate the second if(cond).
Dehao Chenf6c00832016-05-18 19:44:21 +00005105static void reuseTableCompare(
5106 User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
5107 Constant *DefaultValue,
5108 const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
Erik Eckstein0d86c762014-11-27 15:13:14 +00005109
5110 ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
5111 if (!CmpInst)
5112 return;
5113
5114 // We require that the compare is in the same block as the phi so that jump
5115 // threading can do its work afterwards.
5116 if (CmpInst->getParent() != PhiBlock)
5117 return;
5118
5119 Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
5120 if (!CmpOp1)
5121 return;
5122
5123 Value *RangeCmp = RangeCheckBranch->getCondition();
5124 Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
5125 Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
5126
5127 // Check if the compare with the default value is constant true or false.
5128 Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
5129 DefaultValue, CmpOp1, true);
5130 if (DefaultConst != TrueConst && DefaultConst != FalseConst)
5131 return;
5132
5133 // Check if the compare with the case values is distinct from the default
5134 // compare result.
5135 for (auto ValuePair : Values) {
5136 Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
Dehao Chenf6c00832016-05-18 19:44:21 +00005137 ValuePair.second, CmpOp1, true);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005138 if (!CaseConst || CaseConst == DefaultConst)
5139 return;
5140 assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
5141 "Expect true or false as compare result.");
5142 }
Dehao Chenf6c00832016-05-18 19:44:21 +00005143
Erik Eckstein0d86c762014-11-27 15:13:14 +00005144 // Check if the branch instruction dominates the phi node. It's a simple
5145 // dominance check, but sufficient for our needs.
5146 // Although this check is invariant in the calling loops, it's better to do it
5147 // at this late stage. Practically we do it at most once for a switch.
5148 BasicBlock *BranchBlock = RangeCheckBranch->getParent();
5149 for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
5150 BasicBlock *Pred = *PI;
5151 if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
5152 return;
5153 }
5154
5155 if (DefaultConst == FalseConst) {
5156 // The compare yields the same result. We can replace it.
5157 CmpInst->replaceAllUsesWith(RangeCmp);
5158 ++NumTableCmpReuses;
5159 } else {
5160 // The compare yields the same result, just inverted. We can replace it.
Dehao Chenf6c00832016-05-18 19:44:21 +00005161 Value *InvertedTableCmp = BinaryOperator::CreateXor(
5162 RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
5163 RangeCheckBranch);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005164 CmpInst->replaceAllUsesWith(InvertedTableCmp);
5165 ++NumTableCmpReuses;
5166 }
5167}
5168
Sanjay Patel09159b8f2015-06-24 20:40:57 +00005169/// If the switch is only used to initialize one or more phi nodes in a common
5170/// successor block with different constant values, replace the switch with
5171/// lookup tables.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005172static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
5173 const DataLayout &DL,
5174 const TargetTransformInfo &TTI) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005175 assert(SI->getNumCases() > 1 && "Degenerate switch?");
Hans Wennborgf3254832012-10-30 11:23:25 +00005176
Sumanth Gundapaneni8d50a502017-07-28 22:25:40 +00005177 Function *Fn = SI->getParent()->getParent();
5178 // Only build lookup table when we have a target that supports it or the
5179 // attribute is not set.
5180 if (!TTI.shouldBuildLookupTables() ||
5181 (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true"))
Hans Wennborgf3254832012-10-30 11:23:25 +00005182 return false;
5183
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005184 // FIXME: If the switch is too sparse for a lookup table, perhaps we could
5185 // split off a dense part and build a lookup table for that.
5186
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005187 // FIXME: This creates arrays of GEPs to constant strings, which means each
5188 // GEP needs a runtime relocation in PIC code. We should just build one big
5189 // string and lookup indices into that.
5190
Dehao Chenf6c00832016-05-18 19:44:21 +00005191 // Ignore switches with less than three cases. Lookup tables will not make
Sanjay Patelca146972017-09-19 20:58:14 +00005192 // them faster, so we don't analyze them.
Hans Wennborg4744ac12014-01-15 05:00:27 +00005193 if (SI->getNumCases() < 3)
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005194 return false;
5195
5196 // Figure out the corresponding result for each case value and phi node in the
Eric Christopher572e03a2015-06-19 01:53:21 +00005197 // common destination, as well as the min and max case values.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005198 assert(SI->case_begin() != SI->case_end());
5199 SwitchInst::CaseIt CI = SI->case_begin();
Chandler Carruth927d8e62017-04-12 07:27:28 +00005200 ConstantInt *MinCaseVal = CI->getCaseValue();
5201 ConstantInt *MaxCaseVal = CI->getCaseValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005202
Craig Topperf40110f2014-04-25 05:29:35 +00005203 BasicBlock *CommonDest = nullptr;
Dehao Chenf6c00832016-05-18 19:44:21 +00005204 typedef SmallVector<std::pair<ConstantInt *, Constant *>, 4> ResultListTy;
5205 SmallDenseMap<PHINode *, ResultListTy> ResultLists;
5206 SmallDenseMap<PHINode *, Constant *> DefaultResults;
5207 SmallDenseMap<PHINode *, Type *> ResultTypes;
5208 SmallVector<PHINode *, 4> PHIs;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005209
5210 for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
Chandler Carruth927d8e62017-04-12 07:27:28 +00005211 ConstantInt *CaseVal = CI->getCaseValue();
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005212 if (CaseVal->getValue().slt(MinCaseVal->getValue()))
5213 MinCaseVal = CaseVal;
5214 if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
5215 MaxCaseVal = CaseVal;
5216
5217 // Resulting value at phi nodes for this case value.
Dehao Chenf6c00832016-05-18 19:44:21 +00005218 typedef SmallVector<std::pair<PHINode *, Constant *>, 4> ResultsTy;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005219 ResultsTy Results;
Chandler Carruth927d8e62017-04-12 07:27:28 +00005220 if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
Oliver Stannard4df1cc02016-10-07 08:48:24 +00005221 Results, DL, TTI))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005222 return false;
5223
5224 // Append the result from this case to the list for each phi.
Hans Wennborga6a11a92014-11-18 02:37:11 +00005225 for (const auto &I : Results) {
5226 PHINode *PHI = I.first;
5227 Constant *Value = I.second;
5228 if (!ResultLists.count(PHI))
5229 PHIs.push_back(PHI);
5230 ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005231 }
5232 }
5233
Hans Wennborgac114a32014-01-12 00:44:41 +00005234 // Keep track of the result types.
Hans Wennborga6a11a92014-11-18 02:37:11 +00005235 for (PHINode *PHI : PHIs) {
Hans Wennborgac114a32014-01-12 00:44:41 +00005236 ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
5237 }
5238
5239 uint64_t NumResults = ResultLists[PHIs[0]].size();
5240 APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
5241 uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
5242 bool TableHasHoles = (NumResults < TableSize);
5243
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005244 // If the table has holes, we need a constant result for the default case
5245 // or a bitmask that fits in a register.
Dehao Chenf6c00832016-05-18 19:44:21 +00005246 SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
Oliver Stannard4df1cc02016-10-07 08:48:24 +00005247 bool HasDefaultResults =
5248 GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
5249 DefaultResultsList, DL, TTI);
Hans Wennborga6a11a92014-11-18 02:37:11 +00005250
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005251 bool NeedMask = (TableHasHoles && !HasDefaultResults);
5252 if (NeedMask) {
5253 // As an extra penalty for the validity test we require more cases.
Dehao Chenf6c00832016-05-18 19:44:21 +00005254 if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005255 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005256 if (!DL.fitsInLegalInteger(TableSize))
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005257 return false;
5258 }
Hans Wennborgac114a32014-01-12 00:44:41 +00005259
Hans Wennborga6a11a92014-11-18 02:37:11 +00005260 for (const auto &I : DefaultResultsList) {
5261 PHINode *PHI = I.first;
5262 Constant *Result = I.second;
Hans Wennborg7fd5c8442012-09-10 07:44:22 +00005263 DefaultResults[PHI] = Result;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005264 }
5265
Rafael Espindola37dc9e12014-02-21 00:06:31 +00005266 if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005267 return false;
5268
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005269 // Create the BB that does the lookups.
Hans Wennborg776d7122012-09-26 09:34:53 +00005270 Module &Mod = *CommonDest->getParent()->getParent();
Dehao Chenf6c00832016-05-18 19:44:21 +00005271 BasicBlock *LookupBB = BasicBlock::Create(
5272 Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005273
Michael Gottesmanc024f322013-10-20 07:04:37 +00005274 // Compute the table index value.
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005275 Builder.SetInsertPoint(SI);
Sanjay Patel73811a12017-09-20 22:31:35 +00005276 Value *TableIndex;
5277 if (MinCaseVal->isNullValue())
5278 TableIndex = SI->getCondition();
5279 else
5280 TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
5281 "switch.tableidx");
Michael Gottesmanc024f322013-10-20 07:04:37 +00005282
5283 // Compute the maximum table size representable by the integer type we are
5284 // switching upon.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005285 unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
Hans Wennborgac114a32014-01-12 00:44:41 +00005286 uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
Michael Gottesmanc024f322013-10-20 07:04:37 +00005287 assert(MaxTableSize >= TableSize &&
5288 "It is impossible for a switch to have more entries than the max "
5289 "representable value of its input integer type's size.");
5290
Hans Wennborgb64cb272015-01-26 19:52:34 +00005291 // If the default destination is unreachable, or if the lookup table covers
5292 // all values of the conditional variable, branch directly to the lookup table
5293 // BB. Otherwise, check that the condition is within the case range.
5294 const bool DefaultIsReachable =
5295 !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
5296 const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
Erik Eckstein0d86c762014-11-27 15:13:14 +00005297 BranchInst *RangeCheckBranch = nullptr;
5298
Hans Wennborgb64cb272015-01-26 19:52:34 +00005299 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Michael Gottesmanc024f322013-10-20 07:04:37 +00005300 Builder.CreateBr(LookupBB);
Hans Wennborg86ac6302015-04-24 20:57:56 +00005301 // Note: We call removeProdecessor later since we need to be able to get the
5302 // PHI value for the default case in case we're using a bit mask.
Michael Gottesmanc024f322013-10-20 07:04:37 +00005303 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00005304 Value *Cmp = Builder.CreateICmpULT(
5305 TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
5306 RangeCheckBranch =
5307 Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
Michael Gottesmanc024f322013-10-20 07:04:37 +00005308 }
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005309
5310 // Populate the BB that does the lookups.
5311 Builder.SetInsertPoint(LookupBB);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005312
5313 if (NeedMask) {
Sanjay Patelca146972017-09-19 20:58:14 +00005314 // Before doing the lookup, we do the hole check. The LookupBB is therefore
5315 // re-purposed to do the hole check, and we create a new LookupBB.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005316 BasicBlock *MaskBB = LookupBB;
5317 MaskBB->setName("switch.hole_check");
Dehao Chenf6c00832016-05-18 19:44:21 +00005318 LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
5319 CommonDest->getParent(), CommonDest);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005320
Sanjay Patelca146972017-09-19 20:58:14 +00005321 // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
Juergen Ributzkac9591e92014-11-17 19:39:56 +00005322 // unnecessary illegal types.
5323 uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
5324 APInt MaskInt(TableSizePowOf2, 0);
5325 APInt One(TableSizePowOf2, 1);
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005326 // Build bitmask; fill in a 1 bit for every case.
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005327 const ResultListTy &ResultList = ResultLists[PHIs[0]];
5328 for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005329 uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
5330 .getLimitedValue();
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005331 MaskInt |= One << Idx;
5332 }
5333 ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
5334
5335 // Get the TableIndex'th bit of the bitmask.
5336 // If this bit is 0 (meaning hole) jump to the default destination,
5337 // else continue with table lookup.
5338 IntegerType *MapTy = TableMask->getType();
Dehao Chenf6c00832016-05-18 19:44:21 +00005339 Value *MaskIndex =
5340 Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
5341 Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
5342 Value *LoBit = Builder.CreateTrunc(
5343 Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005344 Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
5345
5346 Builder.SetInsertPoint(LookupBB);
5347 AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
5348 }
5349
Hans Wennborg86ac6302015-04-24 20:57:56 +00005350 if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Sanjay Patelca146972017-09-19 20:58:14 +00005351 // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
Hans Wennborg86ac6302015-04-24 20:57:56 +00005352 // do not delete PHINodes here.
5353 SI->getDefaultDest()->removePredecessor(SI->getParent(),
5354 /*DontDeleteUselessPHIs=*/true);
5355 }
5356
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005357 bool ReturnedEarly = false;
Hans Wennborg776d7122012-09-26 09:34:53 +00005358 for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
5359 PHINode *PHI = PHIs[I];
Erik Eckstein0d86c762014-11-27 15:13:14 +00005360 const ResultListTy &ResultList = ResultLists[PHI];
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005361
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005362 // If using a bitmask, use any value to fill the lookup table holes.
5363 Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
Sumanth Gundapaneni8d50a502017-07-28 22:25:40 +00005364 StringRef FuncName = Fn->getName();
Sumanth Gundapaneni5372f0a2017-06-30 20:00:01 +00005365 SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
5366 FuncName);
Hans Wennborg776d7122012-09-26 09:34:53 +00005367
Manman Ren4d189fb2014-07-24 21:13:20 +00005368 Value *Result = Table.BuildLookup(TableIndex, Builder);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005369
Hans Wennborgf744fa92012-09-19 14:24:21 +00005370 // If the result is used to return immediately from the function, we want to
5371 // do that right here.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005372 if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
5373 PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Hans Wennborgf744fa92012-09-19 14:24:21 +00005374 Builder.CreateRet(Result);
5375 ReturnedEarly = true;
5376 break;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005377 }
5378
Erik Eckstein0d86c762014-11-27 15:13:14 +00005379 // Do a small peephole optimization: re-use the switch table compare if
5380 // possible.
5381 if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
5382 BasicBlock *PhiBlock = PHI->getParent();
5383 // Search for compare instructions which use the phi.
5384 for (auto *User : PHI->users()) {
5385 reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
5386 }
5387 }
5388
Hans Wennborgf744fa92012-09-19 14:24:21 +00005389 PHI->addIncoming(Result, LookupBB);
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005390 }
5391
5392 if (!ReturnedEarly)
5393 Builder.CreateBr(CommonDest);
5394
5395 // Remove the switch.
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005396 for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005397 BasicBlock *Succ = SI->getSuccessor(i);
Michael Gottesmanc024f322013-10-20 07:04:37 +00005398
Michael Gottesman63c63ac2013-10-21 05:20:11 +00005399 if (Succ == SI->getDefaultDest())
Michael Gottesmanc024f322013-10-20 07:04:37 +00005400 continue;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005401 Succ->removePredecessor(SI->getParent());
5402 }
5403 SI->eraseFromParent();
5404
5405 ++NumLookupTables;
Hans Wennborgb73c0b02014-03-12 18:35:40 +00005406 if (NeedMask)
5407 ++NumLookupTablesHoles;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005408 return true;
5409}
5410
James Molloyb2e436d2016-08-01 07:45:11 +00005411static bool isSwitchDense(ArrayRef<int64_t> Values) {
5412 // See also SelectionDAGBuilder::isDense(), which this function was based on.
5413 uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
5414 uint64_t Range = Diff + 1;
5415 uint64_t NumCases = Values.size();
5416 // 40% is the default density for building a jump table in optsize/minsize mode.
5417 uint64_t MinDensity = 40;
Junmo Parkdb8f6ee2016-08-02 04:38:27 +00005418
James Molloyb2e436d2016-08-01 07:45:11 +00005419 return NumCases * 100 >= Range * MinDensity;
5420}
5421
Sanjay Patelca146972017-09-19 20:58:14 +00005422/// Try to transform a switch that has "holes" in it to a contiguous sequence
5423/// of cases.
5424///
5425/// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
5426/// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
5427///
5428/// This converts a sparse switch into a dense switch which allows better
5429/// lowering and could also allow transforming into a lookup table.
James Molloyb2e436d2016-08-01 07:45:11 +00005430static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
5431 const DataLayout &DL,
5432 const TargetTransformInfo &TTI) {
5433 auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
5434 if (CondTy->getIntegerBitWidth() > 64 ||
5435 !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
5436 return false;
5437 // Only bother with this optimization if there are more than 3 switch cases;
5438 // SDAG will only bother creating jump tables for 4 or more cases.
5439 if (SI->getNumCases() < 4)
5440 return false;
5441
5442 // This transform is agnostic to the signedness of the input or case values. We
5443 // can treat the case values as signed or unsigned. We can optimize more common
5444 // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
5445 // as signed.
5446 SmallVector<int64_t,4> Values;
5447 for (auto &C : SI->cases())
5448 Values.push_back(C.getCaseValue()->getValue().getSExtValue());
5449 std::sort(Values.begin(), Values.end());
5450
5451 // If the switch is already dense, there's nothing useful to do here.
5452 if (isSwitchDense(Values))
5453 return false;
5454
5455 // First, transform the values such that they start at zero and ascend.
5456 int64_t Base = Values[0];
5457 for (auto &V : Values)
5458 V -= Base;
5459
5460 // Now we have signed numbers that have been shifted so that, given enough
5461 // precision, there are no negative values. Since the rest of the transform
5462 // is bitwise only, we switch now to an unsigned representation.
5463 uint64_t GCD = 0;
5464 for (auto &V : Values)
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005465 GCD = GreatestCommonDivisor64(GCD, (uint64_t)V);
James Molloyb2e436d2016-08-01 07:45:11 +00005466
5467 // This transform can be done speculatively because it is so cheap - it results
5468 // in a single rotate operation being inserted. This can only happen if the
5469 // factor extracted is a power of 2.
5470 // FIXME: If the GCD is an odd number we can multiply by the multiplicative
5471 // inverse of GCD and then perform this transform.
5472 // FIXME: It's possible that optimizing a switch on powers of two might also
5473 // be beneficial - flag values are often powers of two and we could use a CLZ
5474 // as the key function.
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005475 if (GCD <= 1 || !isPowerOf2_64(GCD))
James Molloyb2e436d2016-08-01 07:45:11 +00005476 // No common divisor found or too expensive to compute key function.
5477 return false;
5478
Eugene Zelenkoa3fe70d2016-11-30 17:48:10 +00005479 unsigned Shift = Log2_64(GCD);
James Molloyb2e436d2016-08-01 07:45:11 +00005480 for (auto &V : Values)
5481 V = (int64_t)((uint64_t)V >> Shift);
5482
5483 if (!isSwitchDense(Values))
5484 // Transform didn't create a dense switch.
5485 return false;
5486
5487 // The obvious transform is to shift the switch condition right and emit a
5488 // check that the condition actually cleanly divided by GCD, i.e.
5489 // C & (1 << Shift - 1) == 0
5490 // inserting a new CFG edge to handle the case where it didn't divide cleanly.
5491 //
5492 // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
5493 // shift and puts the shifted-off bits in the uppermost bits. If any of these
5494 // are nonzero then the switch condition will be very large and will hit the
5495 // default case.
Junmo Parkdb8f6ee2016-08-02 04:38:27 +00005496
James Molloyb2e436d2016-08-01 07:45:11 +00005497 auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
5498 Builder.SetInsertPoint(SI);
5499 auto *ShiftC = ConstantInt::get(Ty, Shift);
5500 auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
Benjamin Krameraa160c22016-08-05 14:55:02 +00005501 auto *LShr = Builder.CreateLShr(Sub, ShiftC);
5502 auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
5503 auto *Rot = Builder.CreateOr(LShr, Shl);
James Molloyb2e436d2016-08-01 07:45:11 +00005504 SI->replaceUsesOfWith(SI->getCondition(), Rot);
5505
Chandler Carruth927d8e62017-04-12 07:27:28 +00005506 for (auto Case : SI->cases()) {
5507 auto *Orig = Case.getCaseValue();
James Molloyb2e436d2016-08-01 07:45:11 +00005508 auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005509 Case.setValue(
James Molloybade86c2016-08-01 09:34:48 +00005510 cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
James Molloyb2e436d2016-08-01 07:45:11 +00005511 }
5512 return true;
5513}
5514
Devang Patela7ec47d2011-05-18 20:35:38 +00005515bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005516 BasicBlock *BB = SI->getParent();
5517
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005518 if (isValueEqualityComparison(SI)) {
5519 // If we only have one predecessor, and if it is a branch on this value,
5520 // see if that predecessor totally determines the outcome of this switch.
5521 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
5522 if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005523 return SimplifyCFG(BB, TTI, AC, Options) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00005524
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005525 Value *Cond = SI->getCondition();
5526 if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
5527 if (SimplifySwitchOnSelect(SI, Select))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005528 return SimplifyCFG(BB, TTI, AC, Options) | true;
Frits van Bommel8ae07992011-02-28 09:44:07 +00005529
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005530 // If the block only contains the switch, see if we can fold the block
5531 // away into any preds.
5532 BasicBlock::iterator BBI = BB->begin();
5533 // Ignore dbg intrinsics.
5534 while (isa<DbgInfoIntrinsic>(BBI))
5535 ++BBI;
5536 if (SI == &*BBI)
5537 if (FoldValueComparisonIntoPredecessors(SI, Builder))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005538 return SimplifyCFG(BB, TTI, AC, Options) | true;
Jakob Stoklund Olesen977f41a2012-10-25 18:51:15 +00005539 }
Benjamin Kramerf4ea1d52011-02-02 15:56:22 +00005540
5541 // Try to transform the switch into an icmp and a branch.
Devang Patela7ec47d2011-05-18 20:35:38 +00005542 if (TurnSwitchRangeIntoICmp(SI, Builder))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005543 return SimplifyCFG(BB, TTI, AC, Options) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00005544
5545 // Remove unreachable cases.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005546 if (EliminateDeadSwitchCases(SI, AC, DL))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005547 return SimplifyCFG(BB, TTI, AC, Options) | true;
Benjamin Kramerd96205c2011-05-14 15:57:25 +00005548
Daniel Jasperaec2fa32016-12-19 08:22:17 +00005549 if (SwitchToSelect(SI, Builder, AC, DL, TTI))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005550 return SimplifyCFG(BB, TTI, AC, Options) | true;
Marcello Maggioni5bbe3df2014-10-14 01:58:26 +00005551
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00005552 if (ForwardSwitchConditionToPHI(SI))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005553 return SimplifyCFG(BB, TTI, AC, Options) | true;
Hans Wennborg4ab4a8e2011-06-18 10:28:47 +00005554
Sanjay Patelca146972017-09-19 20:58:14 +00005555 // The conversion from switch to lookup tables results in difficult-to-analyze
5556 // code and makes pruning branches much harder. This is a problem if the
5557 // switch expression itself can still be restricted as a result of inlining or
5558 // CVP. Therefore, only apply this transformation during late stages of the
5559 // optimisation pipeline.
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005560 if (Options.ConvertSwitchToLookupTable &&
5561 SwitchToLookupTable(SI, Builder, DL, TTI))
5562 return SimplifyCFG(BB, TTI, AC, Options) | true;
Hans Wennborg8a62fc52012-09-06 09:43:28 +00005563
James Molloyb2e436d2016-08-01 07:45:11 +00005564 if (ReduceSwitchRange(SI, Builder, DL, TTI))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005565 return SimplifyCFG(BB, TTI, AC, Options) | true;
James Molloyb2e436d2016-08-01 07:45:11 +00005566
Chris Lattner25c3af32010-12-13 06:25:44 +00005567 return false;
5568}
5569
5570bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
5571 BasicBlock *BB = IBI->getParent();
5572 bool Changed = false;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005573
Chris Lattner25c3af32010-12-13 06:25:44 +00005574 // Eliminate redundant destinations.
5575 SmallPtrSet<Value *, 8> Succs;
5576 for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
5577 BasicBlock *Dest = IBI->getDestination(i);
David Blaikie70573dc2014-11-19 07:49:26 +00005578 if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005579 Dest->removePredecessor(BB);
5580 IBI->removeDestination(i);
Dehao Chenf6c00832016-05-18 19:44:21 +00005581 --i;
5582 --e;
Chris Lattner25c3af32010-12-13 06:25:44 +00005583 Changed = true;
5584 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005585 }
Chris Lattner25c3af32010-12-13 06:25:44 +00005586
5587 if (IBI->getNumDestinations() == 0) {
5588 // If the indirectbr has no successors, change it to unreachable.
5589 new UnreachableInst(IBI->getContext(), IBI);
5590 EraseTerminatorInstAndDCECond(IBI);
5591 return true;
5592 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005593
Chris Lattner25c3af32010-12-13 06:25:44 +00005594 if (IBI->getNumDestinations() == 1) {
5595 // If the indirectbr has one successor, change it to a direct branch.
5596 BranchInst::Create(IBI->getDestination(0), IBI);
5597 EraseTerminatorInstAndDCECond(IBI);
5598 return true;
5599 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005600
Chris Lattner25c3af32010-12-13 06:25:44 +00005601 if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
5602 if (SimplifyIndirectBrOnSelect(IBI, SI))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005603 return SimplifyCFG(BB, TTI, AC, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005604 }
5605 return Changed;
5606}
5607
Philip Reames2b969d72015-03-24 22:28:45 +00005608/// Given an block with only a single landing pad and a unconditional branch
5609/// try to find another basic block which this one can be merged with. This
5610/// handles cases where we have multiple invokes with unique landing pads, but
5611/// a shared handler.
5612///
5613/// We specifically choose to not worry about merging non-empty blocks
5614/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
5615/// practice, the optimizer produces empty landing pad blocks quite frequently
5616/// when dealing with exception dense code. (see: instcombine, gvn, if-else
5617/// sinking in this file)
5618///
5619/// This is primarily a code size optimization. We need to avoid performing
5620/// any transform which might inhibit optimization (such as our ability to
5621/// specialize a particular handler via tail commoning). We do this by not
5622/// merging any blocks which require us to introduce a phi. Since the same
5623/// values are flowing through both blocks, we don't loose any ability to
5624/// specialize. If anything, we make such specialization more likely.
5625///
5626/// TODO - This transformation could remove entries from a phi in the target
5627/// block when the inputs in the phi are the same for the two blocks being
5628/// merged. In some cases, this could result in removal of the PHI entirely.
5629static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
5630 BasicBlock *BB) {
5631 auto Succ = BB->getUniqueSuccessor();
5632 assert(Succ);
5633 // If there's a phi in the successor block, we'd likely have to introduce
5634 // a phi into the merged landing pad block.
5635 if (isa<PHINode>(*Succ->begin()))
5636 return false;
5637
5638 for (BasicBlock *OtherPred : predecessors(Succ)) {
5639 if (BB == OtherPred)
5640 continue;
5641 BasicBlock::iterator I = OtherPred->begin();
5642 LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
5643 if (!LPad2 || !LPad2->isIdenticalTo(LPad))
5644 continue;
Dehao Chenf6c00832016-05-18 19:44:21 +00005645 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {
5646 }
Philip Reames2b969d72015-03-24 22:28:45 +00005647 BranchInst *BI2 = dyn_cast<BranchInst>(I);
5648 if (!BI2 || !BI2->isIdenticalTo(BI))
5649 continue;
5650
David Majnemer1efa23d2016-02-20 01:07:45 +00005651 // We've found an identical block. Update our predecessors to take that
Philip Reames2b969d72015-03-24 22:28:45 +00005652 // path instead and make ourselves dead.
5653 SmallSet<BasicBlock *, 16> Preds;
5654 Preds.insert(pred_begin(BB), pred_end(BB));
5655 for (BasicBlock *Pred : Preds) {
5656 InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
Dehao Chenf6c00832016-05-18 19:44:21 +00005657 assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
5658 "unexpected successor");
Philip Reames2b969d72015-03-24 22:28:45 +00005659 II->setUnwindDest(OtherPred);
5660 }
5661
5662 // The debug info in OtherPred doesn't cover the merged control flow that
5663 // used to go through BB. We need to delete it or update it.
Dehao Chenf6c00832016-05-18 19:44:21 +00005664 for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
5665 Instruction &Inst = *I;
5666 I++;
Philip Reames2b969d72015-03-24 22:28:45 +00005667 if (isa<DbgInfoIntrinsic>(Inst))
5668 Inst.eraseFromParent();
5669 }
5670
5671 SmallSet<BasicBlock *, 16> Succs;
5672 Succs.insert(succ_begin(BB), succ_end(BB));
5673 for (BasicBlock *Succ : Succs) {
5674 Succ->removePredecessor(BB);
5675 }
5676
5677 IRBuilder<> Builder(BI);
5678 Builder.CreateUnreachable();
5679 BI->eraseFromParent();
5680 return true;
5681 }
5682 return false;
5683}
5684
Dehao Chenf6c00832016-05-18 19:44:21 +00005685bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI,
5686 IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005687 BasicBlock *BB = BI->getParent();
Balaram Makamb05a5572017-07-19 08:53:34 +00005688 BasicBlock *Succ = BI->getSuccessor(0);
Andrew Trickf3cf1932012-08-29 21:46:36 +00005689
Manman Ren93ab6492012-09-20 22:37:36 +00005690 if (SinkCommon && SinkThenElseCodeToEnd(BI))
5691 return true;
Reid Klecknerbca59d22016-05-02 19:43:22 +00005692
5693 // If the Terminator is the only non-phi instruction, simplify the block.
Sanjay Patelca146972017-09-19 20:58:14 +00005694 // If LoopHeader is provided, check if the block or its successor is a loop
5695 // header. (This is for early invocations before loop simplify and
Balaram Makamb05a5572017-07-19 08:53:34 +00005696 // vectorization to keep canonical loop forms for nested loops. These blocks
5697 // can be eliminated when the pass is invoked later in the back-end.)
5698 bool NeedCanonicalLoop =
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005699 Options.NeedCanonicalLoop &&
Balaram Makamb05a5572017-07-19 08:53:34 +00005700 (LoopHeaders && (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
Reid Klecknerbca59d22016-05-02 19:43:22 +00005701 BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
Chris Lattner25c3af32010-12-13 06:25:44 +00005702 if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
Balaram Makamb05a5572017-07-19 08:53:34 +00005703 !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB))
Chris Lattner25c3af32010-12-13 06:25:44 +00005704 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005705
Sanjay Patelca146972017-09-19 20:58:14 +00005706 // If the only instruction in the block is a seteq/setne comparison against a
5707 // constant, try to simplify the block.
Chris Lattner25c3af32010-12-13 06:25:44 +00005708 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
5709 if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
5710 for (++I; isa<DbgInfoIntrinsic>(I); ++I)
5711 ;
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005712 if (I->isTerminator() &&
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005713 TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI, AC,
5714 Options))
Chris Lattner25c3af32010-12-13 06:25:44 +00005715 return true;
5716 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005717
Philip Reames2b969d72015-03-24 22:28:45 +00005718 // See if we can merge an empty landing pad block with another which is
5719 // equivalent.
5720 if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005721 for (++I; isa<DbgInfoIntrinsic>(I); ++I) {
5722 }
5723 if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
Philip Reames2b969d72015-03-24 22:28:45 +00005724 return true;
5725 }
5726
Manman Rend33f4ef2012-06-13 05:43:29 +00005727 // If this basic block is ONLY a compare and a branch, and if a predecessor
5728 // branches to us and our successor, fold the comparison into the
5729 // predecessor and use logical operations to update the incoming value
5730 // for PHI nodes in common successor.
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005731 if (FoldBranchToCommonDest(BI, Options.BonusInstThreshold))
5732 return SimplifyCFG(BB, TTI, AC, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005733 return false;
5734}
5735
James Molloy4de84dd2015-11-04 15:28:04 +00005736static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
5737 BasicBlock *PredPred = nullptr;
5738 for (auto *P : predecessors(BB)) {
5739 BasicBlock *PPred = P->getSinglePredecessor();
5740 if (!PPred || (PredPred && PredPred != PPred))
5741 return nullptr;
5742 PredPred = PPred;
5743 }
5744 return PredPred;
5745}
Chris Lattner25c3af32010-12-13 06:25:44 +00005746
Devang Patela7ec47d2011-05-18 20:35:38 +00005747bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005748 BasicBlock *BB = BI->getParent();
Andrew Trickf3cf1932012-08-29 21:46:36 +00005749
Chris Lattner25c3af32010-12-13 06:25:44 +00005750 // Conditional branch
5751 if (isValueEqualityComparison(BI)) {
5752 // If we only have one predecessor, and if it is a branch on this value,
5753 // see if that predecessor totally determines the outcome of this
5754 // switch.
5755 if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
Devang Patela7ec47d2011-05-18 20:35:38 +00005756 if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005757 return SimplifyCFG(BB, TTI, AC, Options) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005758
Chris Lattner25c3af32010-12-13 06:25:44 +00005759 // This block must be empty, except for the setcond inst, if it exists.
5760 // Ignore dbg intrinsics.
5761 BasicBlock::iterator I = BB->begin();
5762 // Ignore dbg intrinsics.
5763 while (isa<DbgInfoIntrinsic>(I))
5764 ++I;
5765 if (&*I == BI) {
Devang Patel58380552011-05-18 20:53:17 +00005766 if (FoldValueComparisonIntoPredecessors(BI, Builder))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005767 return SimplifyCFG(BB, TTI, AC, Options) | true;
Dehao Chenf6c00832016-05-18 19:44:21 +00005768 } else if (&*I == cast<Instruction>(BI->getCondition())) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005769 ++I;
5770 // Ignore dbg intrinsics.
5771 while (isa<DbgInfoIntrinsic>(I))
5772 ++I;
Devang Patel58380552011-05-18 20:53:17 +00005773 if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005774 return SimplifyCFG(BB, TTI, AC, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005775 }
5776 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005777
Chris Lattner25c3af32010-12-13 06:25:44 +00005778 // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005779 if (SimplifyBranchOnICmpChain(BI, Builder, DL))
Chris Lattner25c3af32010-12-13 06:25:44 +00005780 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005781
Chad Rosier4ab37c02016-05-06 14:25:14 +00005782 // If this basic block has a single dominating predecessor block and the
5783 // dominating block's condition implies BI's condition, we know the direction
5784 // of the BI branch.
5785 if (BasicBlock *Dom = BB->getSinglePredecessor()) {
5786 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
5787 if (PBI && PBI->isConditional() &&
Craig Topperdfd01ea2017-07-06 16:29:43 +00005788 PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
5789 assert(PBI->getSuccessor(0) == BB || PBI->getSuccessor(1) == BB);
Chad Rosierdfd1de62017-08-01 20:18:54 +00005790 bool CondIsTrue = PBI->getSuccessor(0) == BB;
Chad Rosier4ab37c02016-05-06 14:25:14 +00005791 Optional<bool> Implication = isImpliedCondition(
Chad Rosierdfd1de62017-08-01 20:18:54 +00005792 PBI->getCondition(), BI->getCondition(), DL, CondIsTrue);
Chad Rosier4ab37c02016-05-06 14:25:14 +00005793 if (Implication) {
5794 // Turn this into a branch on constant.
5795 auto *OldCond = BI->getCondition();
5796 ConstantInt *CI = *Implication
5797 ? ConstantInt::getTrue(BB->getContext())
5798 : ConstantInt::getFalse(BB->getContext());
5799 BI->setCondition(CI);
5800 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005801 return SimplifyCFG(BB, TTI, AC, Options) | true;
Chad Rosier4ab37c02016-05-06 14:25:14 +00005802 }
5803 }
5804 }
5805
Dan Gohman5ab9c0a2012-01-05 23:58:56 +00005806 // If this basic block is ONLY a compare and a branch, and if a predecessor
5807 // branches to us and one of our successors, fold the comparison into the
5808 // predecessor and use logical operations to pick the right destination.
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005809 if (FoldBranchToCommonDest(BI, Options.BonusInstThreshold))
5810 return SimplifyCFG(BB, TTI, AC, Options) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005811
Chris Lattner25c3af32010-12-13 06:25:44 +00005812 // We have a conditional branch to two blocks that are only reachable
5813 // from BI. We know that the condbr dominates the two blocks, so see if
5814 // there is any identical code in the "then" and "else" blocks. If so, we
5815 // can hoist it up to the branching block.
Craig Topperf40110f2014-04-25 05:29:35 +00005816 if (BI->getSuccessor(0)->getSinglePredecessor()) {
5817 if (BI->getSuccessor(1)->getSinglePredecessor()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005818 if (HoistThenElseCodeToIf(BI, TTI))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005819 return SimplifyCFG(BB, TTI, AC, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005820 } else {
5821 // If Successor #1 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005822 // execute Successor #0 if it branches to Successor #1.
Chris Lattner25c3af32010-12-13 06:25:44 +00005823 TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
5824 if (Succ0TI->getNumSuccessors() == 1 &&
5825 Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005826 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005827 return SimplifyCFG(BB, TTI, AC, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005828 }
Craig Topperf40110f2014-04-25 05:29:35 +00005829 } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
Chris Lattner25c3af32010-12-13 06:25:44 +00005830 // If Successor #0 has multiple preds, we may be able to conditionally
Sanjay Patel0a2ada72014-07-06 23:10:24 +00005831 // execute Successor #1 if it branches to Successor #0.
Chris Lattner25c3af32010-12-13 06:25:44 +00005832 TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
5833 if (Succ1TI->getNumSuccessors() == 1 &&
5834 Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005835 if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005836 return SimplifyCFG(BB, TTI, AC, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005837 }
Andrew Trickf3cf1932012-08-29 21:46:36 +00005838
Chris Lattner25c3af32010-12-13 06:25:44 +00005839 // If this is a branch on a phi node in the current block, thread control
5840 // through this block if any PHI node entries are constants.
5841 if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
5842 if (PN->getParent() == BI->getParent())
Peter Collingbourne0609acc2017-02-15 03:01:11 +00005843 if (FoldCondBranchOnPHI(BI, DL, AC))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005844 return SimplifyCFG(BB, TTI, AC, Options) | true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005845
Chris Lattner25c3af32010-12-13 06:25:44 +00005846 // Scan predecessor blocks for conditional branches.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00005847 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
5848 if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
Chris Lattner25c3af32010-12-13 06:25:44 +00005849 if (PBI != BI && PBI->isConditional())
Philip Reamesb42db212015-10-14 22:46:19 +00005850 if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005851 return SimplifyCFG(BB, TTI, AC, Options) | true;
Chris Lattner25c3af32010-12-13 06:25:44 +00005852
James Molloy4de84dd2015-11-04 15:28:04 +00005853 // Look for diamond patterns.
5854 if (MergeCondStores)
5855 if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
5856 if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
5857 if (PBI != BI && PBI->isConditional())
Alexey Bataev978e2e42017-08-29 20:06:24 +00005858 if (mergeConditionalStores(PBI, BI, DL))
Sanjay Patel0f9b4772017-09-27 14:54:16 +00005859 return SimplifyCFG(BB, TTI, AC, Options) | true;
Dehao Chenf6c00832016-05-18 19:44:21 +00005860
Chris Lattner25c3af32010-12-13 06:25:44 +00005861 return false;
5862}
5863
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005864/// Check if passing a value to an instruction will cause undefined behavior.
5865static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
5866 Constant *C = dyn_cast<Constant>(V);
5867 if (!C)
5868 return false;
5869
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005870 if (I->use_empty())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005871 return false;
5872
David Majnemer1fea77c2016-06-25 07:37:27 +00005873 if (C->isNullValue() || isa<UndefValue>(C)) {
Benjamin Kramerd12e82e2012-10-04 16:11:49 +00005874 // Only look at the first use, avoid hurting compile time with long uselists
Chandler Carruthcdf47882014-03-09 03:16:01 +00005875 User *Use = *I->user_begin();
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005876
5877 // Now make sure that there are no instructions in between that can alter
5878 // control flow (eg. calls)
Duncan P. N. Exon Smith0a12729f2016-08-16 23:57:56 +00005879 for (BasicBlock::iterator
5880 i = ++BasicBlock::iterator(I),
5881 UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
5882 i != UI; ++i)
Benjamin Kramer0655b782011-08-26 02:25:55 +00005883 if (i == I->getParent()->end() || i->mayHaveSideEffects())
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005884 return false;
5885
5886 // Look through GEPs. A load from a GEP derived from NULL is still undefined
5887 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
5888 if (GEP->getPointerOperand() == I)
5889 return passingValueIsAlwaysUndefined(V, GEP);
5890
5891 // Look through bitcasts.
5892 if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
5893 return passingValueIsAlwaysUndefined(V, BC);
5894
Benjamin Kramer0655b782011-08-26 02:25:55 +00005895 // Load from null is undefined.
5896 if (LoadInst *LI = dyn_cast<LoadInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005897 if (!LI->isVolatile())
5898 return LI->getPointerAddressSpace() == 0;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005899
Benjamin Kramer0655b782011-08-26 02:25:55 +00005900 // Store to null is undefined.
5901 if (StoreInst *SI = dyn_cast<StoreInst>(Use))
Andrew Tricka0a5ca02013-03-07 01:03:35 +00005902 if (!SI->isVolatile())
Dehao Chenf6c00832016-05-18 19:44:21 +00005903 return SI->getPointerAddressSpace() == 0 &&
5904 SI->getPointerOperand() == I;
David Majnemer1fea77c2016-06-25 07:37:27 +00005905
5906 // A call to null is undefined.
5907 if (auto CS = CallSite(Use))
5908 return CS.getCalledValue() == I;
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005909 }
5910 return false;
5911}
5912
5913/// If BB has an incoming value that will always trigger undefined behavior
Nick Lewyckye87d54c2011-12-26 20:37:40 +00005914/// (eg. null pointer dereference), remove the branch leading here.
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005915static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
5916 for (BasicBlock::iterator i = BB->begin();
5917 PHINode *PHI = dyn_cast<PHINode>(i); ++i)
5918 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
5919 if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
5920 TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
5921 IRBuilder<> Builder(T);
5922 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
5923 BB->removePredecessor(PHI->getIncomingBlock(i));
5924 // Turn uncoditional branches into unreachables and remove the dead
5925 // destination from conditional branches.
5926 if (BI->isUnconditional())
5927 Builder.CreateUnreachable();
5928 else
Dehao Chenf6c00832016-05-18 19:44:21 +00005929 Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
5930 : BI->getSuccessor(0));
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005931 BI->eraseFromParent();
5932 return true;
5933 }
5934 // TODO: SwitchInst.
5935 }
5936
5937 return false;
5938}
5939
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00005940bool SimplifyCFGOpt::run(BasicBlock *BB) {
Chris Lattner3f5823f2003-08-24 18:36:16 +00005941 bool Changed = false;
Chris Lattner466a0492002-05-21 20:50:24 +00005942
Chris Lattnerd7beca32010-12-14 06:17:25 +00005943 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner466a0492002-05-21 20:50:24 +00005944 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner466a0492002-05-21 20:50:24 +00005945
Dan Gohman4a63fad2010-08-14 00:29:42 +00005946 // Remove basic blocks that have no predecessors (except the entry block)...
5947 // or that just have themself as a predecessor. These are unreachable.
Dehao Chenf6c00832016-05-18 19:44:21 +00005948 if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
Dan Gohman4a63fad2010-08-14 00:29:42 +00005949 BB->getSinglePredecessor() == BB) {
David Majnemeree0cbbb2016-02-24 17:30:48 +00005950 DEBUG(dbgs() << "Removing BB: \n" << *BB);
5951 DeleteDeadBlock(BB);
5952 return true;
Chris Lattner466a0492002-05-21 20:50:24 +00005953 }
5954
Chris Lattner031340a2003-08-17 19:41:53 +00005955 // Check to see if we can constant propagate this terminator instruction
5956 // away...
Frits van Bommelad964552011-05-22 16:24:18 +00005957 Changed |= ConstantFoldTerminator(BB, true);
Chris Lattner031340a2003-08-17 19:41:53 +00005958
Dan Gohman1a951062009-10-30 22:39:04 +00005959 // Check for and eliminate duplicate PHI nodes in this block.
5960 Changed |= EliminateDuplicatePHINodes(BB);
5961
Benjamin Kramerfb212a62011-08-26 01:22:29 +00005962 // Check for and remove branches that will always cause undefined behavior.
5963 Changed |= removeUndefIntroducingPredecessor(BB);
5964
Chris Lattner2e3832d2010-12-13 05:10:48 +00005965 // Merge basic blocks into their predecessor if there is only one distinct
5966 // pred, and if there is only one distinct successor of the predecessor, and
5967 // if there are no PHI nodes.
5968 //
5969 if (MergeBlockIntoPredecessor(BB))
5970 return true;
Andrew Trickf3cf1932012-08-29 21:46:36 +00005971
Devang Patel15ad6762011-05-18 18:01:27 +00005972 IRBuilder<> Builder(BB);
5973
Dan Gohman20af5a02008-03-11 21:53:06 +00005974 // If there is a trivial two-entry PHI node in this basic block, and we can
5975 // eliminate it, do so now.
5976 if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
5977 if (PN->getNumIncomingValues() == 2)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005978 Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Dan Gohman20af5a02008-03-11 21:53:06 +00005979
Devang Patela7ec47d2011-05-18 20:35:38 +00005980 Builder.SetInsertPoint(BB->getTerminator());
Chris Lattner25c3af32010-12-13 06:25:44 +00005981 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
Chris Lattner1d057612010-12-13 06:36:51 +00005982 if (BI->isUnconditional()) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005983 if (SimplifyUncondBranch(BI, Builder))
5984 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005985 } else {
Dehao Chenf6c00832016-05-18 19:44:21 +00005986 if (SimplifyCondBranch(BI, Builder))
5987 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005988 }
5989 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005990 if (SimplifyReturn(RI, Builder))
5991 return true;
Bill Wendlingd5d95b02012-02-06 21:16:41 +00005992 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00005993 if (SimplifyResume(RI, Builder))
5994 return true;
Andrew Kaylor50e4e862015-09-04 23:39:40 +00005995 } else if (CleanupReturnInst *RI =
Dehao Chenf6c00832016-05-18 19:44:21 +00005996 dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
5997 if (SimplifyCleanupReturn(RI))
5998 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00005999 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
Dehao Chenf6c00832016-05-18 19:44:21 +00006000 if (SimplifySwitch(SI, Builder))
6001 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00006002 } else if (UnreachableInst *UI =
Dehao Chenf6c00832016-05-18 19:44:21 +00006003 dyn_cast<UnreachableInst>(BB->getTerminator())) {
6004 if (SimplifyUnreachable(UI))
6005 return true;
Chris Lattner1d057612010-12-13 06:36:51 +00006006 } else if (IndirectBrInst *IBI =
Dehao Chenf6c00832016-05-18 19:44:21 +00006007 dyn_cast<IndirectBrInst>(BB->getTerminator())) {
6008 if (SimplifyIndirectBr(IBI))
6009 return true;
Chris Lattnere42732e2004-02-16 06:35:48 +00006010 }
6011
Chris Lattner031340a2003-08-17 19:41:53 +00006012 return Changed;
Chris Lattner466a0492002-05-21 20:50:24 +00006013}
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00006014
Chandler Carruth0b4ef9c2013-01-07 03:53:25 +00006015bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
Sanjay Patel0f9b4772017-09-27 14:54:16 +00006016 AssumptionCache *AC, const SimplifyCFGOptions &Options,
6017 SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
6018 return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), AC, LoopHeaders,
6019 Options)
Dehao Chenf6c00832016-05-18 19:44:21 +00006020 .run(BB);
Jakob Stoklund Olesen916f48a2010-02-05 22:03:18 +00006021}