blob: 8062fe499083296c6f0b045783519def79cee66c [file] [log] [blame]
Chris Lattner1b094a02003-04-23 16:23:59 +00001//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Misha Brukmanb1c93172005-04-21 23:48:37 +00006//
John Criswell482202a2003-10-20 19:43:21 +00007//===----------------------------------------------------------------------===//
Chris Lattner1b094a02003-04-23 16:23:59 +00008//
Gordon Henriksend5687672007-11-04 16:15:04 +00009// The LowerSwitch transformation rewrites switch instructions with a sequence
10// of branches, which allows targets to get away with not implementing the
11// switch instruction until it is convenient.
Chris Lattner1b094a02003-04-23 16:23:59 +000012//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenkofce43572017-10-21 00:57:46 +000015#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/STLExtras.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000017#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallVector.h"
Roman Tereshin99a66722019-02-22 14:33:46 +000019#include "llvm/Analysis/AssumptionCache.h"
20#include "llvm/Analysis/LazyValueInfo.h"
21#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000022#include "llvm/IR/BasicBlock.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000023#include "llvm/IR/CFG.h"
Roman Tereshin99a66722019-02-22 14:33:46 +000024#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/Function.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000027#include "llvm/IR/InstrTypes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Instructions.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000029#include "llvm/IR/Value.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000030#include "llvm/Pass.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000031#include "llvm/Support/Casting.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000032#include "llvm/Support/Compiler.h"
Nick Lewycky974e12b2009-10-25 06:57:41 +000033#include "llvm/Support/Debug.h"
Roman Tereshin99a66722019-02-22 14:33:46 +000034#include "llvm/Support/KnownBits.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000035#include "llvm/Support/raw_ostream.h"
David Blaikiea373d182018-03-28 17:44:36 +000036#include "llvm/Transforms/Utils.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000038#include <algorithm>
Eugene Zelenkofce43572017-10-21 00:57:46 +000039#include <cassert>
40#include <cstdint>
41#include <iterator>
42#include <limits>
43#include <vector>
44
Chris Lattner49525f82004-01-09 06:02:20 +000045using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000046
Chandler Carruthe96dd892014-04-21 22:55:11 +000047#define DEBUG_TYPE "lower-switch"
48
Chris Lattner1b094a02003-04-23 16:23:59 +000049namespace {
Eugene Zelenkofce43572017-10-21 00:57:46 +000050
Hans Wennborgae9c9712015-01-23 20:43:51 +000051 struct IntRange {
52 int64_t Low, High;
53 };
Hans Wennborgae9c9712015-01-23 20:43:51 +000054
Eugene Zelenkofce43572017-10-21 00:57:46 +000055} // end anonymous namespace
56
57// Return true iff R is covered by Ranges.
58static bool IsInRanges(const IntRange &R,
59 const std::vector<IntRange> &Ranges) {
60 // Note: Ranges must be sorted, non-overlapping and non-adjacent.
61
62 // Find the first range whose High field is >= R.High,
63 // then check if the Low field is <= R.Low. If so, we
64 // have a Range that covers R.
Fangrui Songcecc4352019-04-12 02:02:06 +000065 auto I = llvm::lower_bound(
66 Ranges, R, [](IntRange A, IntRange B) { return A.High < B.High; });
Eugene Zelenkofce43572017-10-21 00:57:46 +000067 return I != Ranges.end() && I->Low <= R.Low;
68}
69
70namespace {
Hans Wennborgae9c9712015-01-23 20:43:51 +000071
Sanjay Patel815adac2015-09-16 16:21:08 +000072 /// Replace all SwitchInst instructions with chained branch instructions.
Nick Lewycky02d5f772009-10-25 06:33:48 +000073 class LowerSwitch : public FunctionPass {
Chris Lattnered922162003-10-07 18:46:23 +000074 public:
Eugene Zelenkofce43572017-10-21 00:57:46 +000075 // Pass identification, replacement for typeid
76 static char ID;
77
Owen Anderson6c18d1a2010-10-19 17:21:58 +000078 LowerSwitch() : FunctionPass(ID) {
79 initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
Karl-Johan Karlsson1ffeb5d2018-07-10 12:06:16 +000080 }
Devang Patel09f162c2007-05-01 21:15:47 +000081
Craig Topper3e4c6972014-03-05 09:10:37 +000082 bool runOnFunction(Function &F) override;
83
Roman Tereshin99a66722019-02-22 14:33:46 +000084 void getAnalysisUsage(AnalysisUsage &AU) const override {
85 AU.addRequired<LazyValueInfoWrapperPass>();
86 }
87
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000088 struct CaseRange {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +000089 ConstantInt* Low;
90 ConstantInt* High;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000091 BasicBlock* BB;
92
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +000093 CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
Hans Wennborg8c82fbc2015-02-05 16:50:27 +000094 : Low(low), High(high), BB(bb) {}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000095 };
96
Eugene Zelenkofce43572017-10-21 00:57:46 +000097 using CaseVector = std::vector<CaseRange>;
98 using CaseItr = std::vector<CaseRange>::iterator;
99
Chris Lattnered922162003-10-07 18:46:23 +0000100 private:
Roman Tereshin99a66722019-02-22 14:33:46 +0000101 void processSwitchInst(SwitchInst *SI,
102 SmallPtrSetImpl<BasicBlock *> &DeleteList,
103 AssumptionCache *AC, LazyValueInfo *LVI);
Chris Lattnered922162003-10-07 18:46:23 +0000104
Jim Grosbachfff56632014-06-16 16:55:20 +0000105 BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
106 ConstantInt *LowerBound, ConstantInt *UpperBound,
Marcello Maggioni78035b12014-07-11 10:34:36 +0000107 Value *Val, BasicBlock *Predecessor,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000108 BasicBlock *OrigBlock, BasicBlock *Default,
109 const std::vector<IntRange> &UnreachableRanges);
Roman Tereshin99a66722019-02-22 14:33:46 +0000110 BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val,
111 ConstantInt *LowerBound, ConstantInt *UpperBound,
112 BasicBlock *OrigBlock, BasicBlock *Default);
Jim Grosbachfff56632014-06-16 16:55:20 +0000113 unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +0000114 };
Bob Wilsone4077362013-09-09 19:14:35 +0000115
116 /// The comparison function for sorting the switch case values in the vector.
117 /// WARNING: Case ranges should be disjoint!
118 struct CaseCmp {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000119 bool operator()(const LowerSwitch::CaseRange& C1,
120 const LowerSwitch::CaseRange& C2) {
Bob Wilsone4077362013-09-09 19:14:35 +0000121 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
122 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
123 return CI1->getValue().slt(CI2->getValue());
124 }
125 };
Eugene Zelenkofce43572017-10-21 00:57:46 +0000126
127} // end anonymous namespace
Chris Lattner1b094a02003-04-23 16:23:59 +0000128
Dan Gohmand78c4002008-05-13 00:00:25 +0000129char LowerSwitch::ID = 0;
Dan Gohmand78c4002008-05-13 00:00:25 +0000130
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000131// Publicly exposed interface to pass...
Owen Andersona7aed182010-08-06 18:33:48 +0000132char &llvm::LowerSwitchID = LowerSwitch::ID;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000133
Roman Tereshin99a66722019-02-22 14:33:46 +0000134INITIALIZE_PASS_BEGIN(LowerSwitch, "lowerswitch",
135 "Lower SwitchInst's to branches", false, false)
136INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
137INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
138INITIALIZE_PASS_END(LowerSwitch, "lowerswitch",
139 "Lower SwitchInst's to branches", false, false)
Eugene Zelenkofce43572017-10-21 00:57:46 +0000140
Chris Lattner1b094a02003-04-23 16:23:59 +0000141// createLowerSwitchPass - Interface to this file...
Chris Lattner49525f82004-01-09 06:02:20 +0000142FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner1b094a02003-04-23 16:23:59 +0000143 return new LowerSwitch();
144}
145
146bool LowerSwitch::runOnFunction(Function &F) {
Roman Tereshin99a66722019-02-22 14:33:46 +0000147 LazyValueInfo *LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
148 auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>();
149 AssumptionCache *AC = ACT ? &ACT->getAssumptionCache(F) : nullptr;
150 // Prevent LazyValueInfo from using the DominatorTree as LowerSwitch does not
151 // preserve it and it becomes stale (when available) pretty much immediately.
152 // Currently the DominatorTree is only used by LowerSwitch indirectly via LVI
153 // and computeKnownBits to refine isValidAssumeForContext's results. Given
154 // that the latter can handle some of the simple cases w/o a DominatorTree,
155 // it's easier to refrain from using the tree than to keep it up to date.
156 LVI->disableDT();
157
Chris Lattner1b094a02003-04-23 16:23:59 +0000158 bool Changed = false;
Chen Li0786bc92015-08-11 20:16:17 +0000159 SmallPtrSet<BasicBlock*, 8> DeleteList;
Chris Lattner1b094a02003-04-23 16:23:59 +0000160
161 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000162 BasicBlock *Cur = &*I++; // Advance over block so we don't traverse new blocks
Chris Lattner1b094a02003-04-23 16:23:59 +0000163
Chen Li0786bc92015-08-11 20:16:17 +0000164 // If the block is a dead Default block that will be deleted later, don't
165 // waste time processing it.
166 if (DeleteList.count(Cur))
167 continue;
168
Chris Lattner1b094a02003-04-23 16:23:59 +0000169 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
170 Changed = true;
Roman Tereshin99a66722019-02-22 14:33:46 +0000171 processSwitchInst(SI, DeleteList, AC, LVI);
Chris Lattner1b094a02003-04-23 16:23:59 +0000172 }
173 }
174
Chen Li10f01bd2015-08-11 18:12:26 +0000175 for (BasicBlock* BB: DeleteList) {
Roman Tereshin99a66722019-02-22 14:33:46 +0000176 LVI->eraseBlock(BB);
Chen Li10f01bd2015-08-11 18:12:26 +0000177 DeleteDeadBlock(BB);
178 }
179
Chris Lattner1b094a02003-04-23 16:23:59 +0000180 return Changed;
181}
182
Sanjay Patel815adac2015-09-16 16:21:08 +0000183/// Used for debugging purposes.
Fangrui Song862eebb2018-05-05 20:14:38 +0000184LLVM_ATTRIBUTE_USED
185static raw_ostream &operator<<(raw_ostream &O,
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000186 const LowerSwitch::CaseVector &C) {
Chris Lattnered922162003-10-07 18:46:23 +0000187 O << "[";
188
Roman Tereshin99a66722019-02-22 14:33:46 +0000189 for (LowerSwitch::CaseVector::const_iterator B = C.begin(), E = C.end();
190 B != E;) {
191 O << "[" << B->Low->getValue() << ", " << B->High->getValue() << "]";
192 if (++B != E)
193 O << ", ";
Chris Lattnered922162003-10-07 18:46:23 +0000194 }
195
196 return O << "]";
197}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000198
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000199/// Update the first occurrence of the "switch statement" BB in the PHI
Sanjay Patel815adac2015-09-16 16:21:08 +0000200/// node with the "new" BB. The other occurrences will:
201///
202/// 1) Be updated by subsequent calls to this function. Switch statements may
203/// have more than one outcoming edge into the same BB if they all have the same
204/// value. When the switch statement is converted these incoming edges are now
205/// coming from multiple BBs.
206/// 2) Removed if subsequent incoming values now share the same case, i.e.,
207/// multiple outcome edges are condensed into one. This is necessary to keep the
208/// number of phi values equal to the number of branches to SuccBB.
Roman Tereshin99a66722019-02-22 14:33:46 +0000209static void
210fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
211 const unsigned NumMergedCases = std::numeric_limits<unsigned>::max()) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000212 for (BasicBlock::iterator I = SuccBB->begin(),
213 IE = SuccBB->getFirstNonPHI()->getIterator();
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000214 I != IE; ++I) {
Marcello Maggioni78035b12014-07-11 10:34:36 +0000215 PHINode *PN = cast<PHINode>(I);
216
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000217 // Only update the first occurrence.
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000218 unsigned Idx = 0, E = PN->getNumIncomingValues();
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000219 unsigned LocalNumMergedCases = NumMergedCases;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000220 for (; Idx != E; ++Idx) {
Juergen Ributzkad4417252014-11-10 21:05:27 +0000221 if (PN->getIncomingBlock(Idx) == OrigBB) {
222 PN->setIncomingBlock(Idx, NewBB);
223 break;
224 }
Marcello Maggioni78035b12014-07-11 10:34:36 +0000225 }
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000226
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000227 // Remove additional occurrences coming from condensed cases and keep the
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000228 // number of incoming values equal to the number of branches to SuccBB.
Michael Liao24fcae82015-03-17 18:03:10 +0000229 SmallVector<unsigned, 8> Indices;
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000230 for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000231 if (PN->getIncomingBlock(Idx) == OrigBB) {
Michael Liao24fcae82015-03-17 18:03:10 +0000232 Indices.push_back(Idx);
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000233 LocalNumMergedCases--;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000234 }
Michael Liao24fcae82015-03-17 18:03:10 +0000235 // Remove incoming values in the reverse order to prevent invalidating
236 // *successive* index.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000237 for (unsigned III : llvm::reverse(Indices))
David Majnemerd7708772016-06-24 04:05:21 +0000238 PN->removeIncomingValue(III);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000239 }
240}
241
Sanjay Patel815adac2015-09-16 16:21:08 +0000242/// Convert the switch statement into a binary lookup of the case values.
243/// The function recursively builds this tree. LowerBound and UpperBound are
244/// used to keep track of the bounds for Val that have already been checked by
245/// a block emitted by one of the previous calls to switchConvert in the call
246/// stack.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000247BasicBlock *
248LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
249 ConstantInt *UpperBound, Value *Val,
250 BasicBlock *Predecessor, BasicBlock *OrigBlock,
251 BasicBlock *Default,
252 const std::vector<IntRange> &UnreachableRanges) {
Roman Tereshin99a66722019-02-22 14:33:46 +0000253 assert(LowerBound && UpperBound && "Bounds must be initialized");
Chris Lattnered922162003-10-07 18:46:23 +0000254 unsigned Size = End - Begin;
255
Jim Grosbachfff56632014-06-16 16:55:20 +0000256 if (Size == 1) {
257 // Check if the Case Range is perfectly squeezed in between
258 // already checked Upper and Lower bounds. If it is then we can avoid
259 // emitting the code that checks if the value actually falls in the range
260 // because the bounds already tell us so.
261 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000262 unsigned NumMergedCases = 0;
Roman Tereshin99a66722019-02-22 14:33:46 +0000263 NumMergedCases = UpperBound->getSExtValue() - LowerBound->getSExtValue();
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000264 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
Jim Grosbachfff56632014-06-16 16:55:20 +0000265 return Begin->BB;
266 }
Roman Tereshin99a66722019-02-22 14:33:46 +0000267 return newLeafBlock(*Begin, Val, LowerBound, UpperBound, OrigBlock,
268 Default);
Jim Grosbachfff56632014-06-16 16:55:20 +0000269 }
Chris Lattnered922162003-10-07 18:46:23 +0000270
271 unsigned Mid = Size / 2;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000272 std::vector<CaseRange> LHS(Begin, Begin + Mid);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000273 LLVM_DEBUG(dbgs() << "LHS: " << LHS << "\n");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000274 std::vector<CaseRange> RHS(Begin + Mid, End);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000275 LLVM_DEBUG(dbgs() << "RHS: " << RHS << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000276
Jim Grosbachfff56632014-06-16 16:55:20 +0000277 CaseRange &Pivot = *(Begin + Mid);
Roman Tereshin99a66722019-02-22 14:33:46 +0000278 LLVM_DEBUG(dbgs() << "Pivot ==> [" << Pivot.Low->getValue() << ", "
279 << Pivot.High->getValue() << "]\n");
Chris Lattnered922162003-10-07 18:46:23 +0000280
Jim Grosbachfff56632014-06-16 16:55:20 +0000281 // NewLowerBound here should never be the integer minimal value.
282 // This is because it is computed from a case range that is never
283 // the smallest, so there is always a case range that has at least
284 // a smaller value.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000285 ConstantInt *NewLowerBound = Pivot.Low;
Jim Grosbachfff56632014-06-16 16:55:20 +0000286
Hans Wennborgae9c9712015-01-23 20:43:51 +0000287 // Because NewLowerBound is never the smallest representable integer
288 // it is safe here to subtract one.
289 ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
290 NewLowerBound->getValue() - 1);
291
292 if (!UnreachableRanges.empty()) {
293 // Check if the gap between LHS's highest and NewLowerBound is unreachable.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000294 int64_t GapLow = LHS.back().High->getSExtValue() + 1;
Hans Wennborgae9c9712015-01-23 20:43:51 +0000295 int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
296 IntRange Gap = { GapLow, GapHigh };
297 if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000298 NewUpperBound = LHS.back().High;
Jim Grosbachfff56632014-06-16 16:55:20 +0000299 }
300
Roman Tereshin99a66722019-02-22 14:33:46 +0000301 LLVM_DEBUG(dbgs() << "LHS Bounds ==> [" << LowerBound->getSExtValue() << ", "
302 << NewUpperBound->getSExtValue() << "]\n"
303 << "RHS Bounds ==> [" << NewLowerBound->getSExtValue()
304 << ", " << UpperBound->getSExtValue() << "]\n");
Jim Grosbachfff56632014-06-16 16:55:20 +0000305
Chris Lattnered922162003-10-07 18:46:23 +0000306 // Create a new node that checks if the value is < pivot. Go to the
307 // left branch if it is and right branch if not.
308 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000309 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Chris Lattnered922162003-10-07 18:46:23 +0000310
Bob Wilsone4077362013-09-09 19:14:35 +0000311 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000312 Val, Pivot.Low, "Pivot");
Marcello Maggioni78035b12014-07-11 10:34:36 +0000313
314 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
315 NewUpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000316 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000317 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
318 UpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000319 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000320
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000321 F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000322 NewNode->getInstList().push_back(Comp);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000323
Gabor Greife9ecc682008-04-06 20:25:17 +0000324 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000325 return NewNode;
326}
327
Sanjay Patel815adac2015-09-16 16:21:08 +0000328/// Create a new leaf block for the binary lookup tree. It checks if the
329/// switch's value == the case's value. If not, then it jumps to the default
330/// branch. At this point in the tree, the value can't be another valid case
331/// value, so the jump to the "default" branch is warranted.
Roman Tereshin99a66722019-02-22 14:33:46 +0000332BasicBlock *LowerSwitch::newLeafBlock(CaseRange &Leaf, Value *Val,
333 ConstantInt *LowerBound,
334 ConstantInt *UpperBound,
335 BasicBlock *OrigBlock,
336 BasicBlock *Default) {
Chris Lattnered922162003-10-07 18:46:23 +0000337 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000338 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000339 F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000340
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000341 // Emit comparison
Craig Topperf40110f2014-04-25 05:29:35 +0000342 ICmpInst* Comp = nullptr;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000343 if (Leaf.Low == Leaf.High) {
344 // Make the seteq instruction...
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000345 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
346 Leaf.Low, "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000347 } else {
348 // Make range comparison
Roman Tereshin99a66722019-02-22 14:33:46 +0000349 if (Leaf.Low == LowerBound) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000350 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000351 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
352 "SwitchLeaf");
Roman Tereshin99a66722019-02-22 14:33:46 +0000353 } else if (Leaf.High == UpperBound) {
354 // Val <= Max && Val >= Lo --> Val >= Lo
355 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SGE, Val, Leaf.Low,
356 "SwitchLeaf");
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000357 } else if (Leaf.Low->isZero()) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000358 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000359 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
Karl-Johan Karlsson1ffeb5d2018-07-10 12:06:16 +0000360 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000361 } else {
362 // Emit V-Lo <=u Hi-Lo
Owen Anderson487375e2009-07-29 18:55:55 +0000363 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000364 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000365 Val->getName()+".off",
366 NewLeaf);
Owen Anderson487375e2009-07-29 18:55:55 +0000367 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000368 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
369 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000370 }
371 }
Chris Lattnered922162003-10-07 18:46:23 +0000372
373 // Make the conditional branch...
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000374 BasicBlock* Succ = Leaf.BB;
Gabor Greife9ecc682008-04-06 20:25:17 +0000375 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000376
377 // If there were any PHI nodes in this successor, rewrite one entry
378 // from OrigBlock to come from NewLeaf.
Reid Spencer66149462004-09-15 17:06:42 +0000379 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
380 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000381 // Remove all but one incoming entries from the cluster
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000382 uint64_t Range = Leaf.High->getSExtValue() -
383 Leaf.Low->getSExtValue();
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000384 for (uint64_t j = 0; j < Range; ++j) {
385 PN->removeIncomingValue(OrigBlock);
386 }
Karl-Johan Karlsson1ffeb5d2018-07-10 12:06:16 +0000387
Chris Lattnered922162003-10-07 18:46:23 +0000388 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
389 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
390 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
391 }
392
393 return NewLeaf;
394}
395
Roman Tereshin99a66722019-02-22 14:33:46 +0000396/// Transform simple list of \p SI's cases into list of CaseRange's \p Cases.
397/// \post \p Cases wouldn't contain references to \p SI's default BB.
398/// \returns Number of \p SI's cases that do not reference \p SI's default BB.
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000399unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
Roman Tereshin99a66722019-02-22 14:33:46 +0000400 unsigned NumSimpleCases = 0;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000401
402 // Start with "simple" cases
Roman Tereshin99a66722019-02-22 14:33:46 +0000403 for (auto Case : SI->cases()) {
404 if (Case.getCaseSuccessor() == SI->getDefaultDest())
405 continue;
Chandler Carruth927d8e62017-04-12 07:27:28 +0000406 Cases.push_back(CaseRange(Case.getCaseValue(), Case.getCaseValue(),
407 Case.getCaseSuccessor()));
Roman Tereshin99a66722019-02-22 14:33:46 +0000408 ++NumSimpleCases;
409 }
Chandler Carruth927d8e62017-04-12 07:27:28 +0000410
Fangrui Song0cac7262018-09-27 02:13:45 +0000411 llvm::sort(Cases, CaseCmp());
Bob Wilsone4077362013-09-09 19:14:35 +0000412
413 // Merge case into clusters
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000414 if (Cases.size() >= 2) {
415 CaseItr I = Cases.begin();
416 for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000417 int64_t nextValue = J->Low->getSExtValue();
418 int64_t currentValue = I->High->getSExtValue();
Bob Wilsone4077362013-09-09 19:14:35 +0000419 BasicBlock* nextBB = J->BB;
420 BasicBlock* currentBB = I->BB;
421
422 // If the two neighboring cases go to the same destination, merge them
423 // into a single case.
Justin Bognere46d3792015-06-20 00:28:25 +0000424 assert(nextValue > currentValue && "Cases should be strictly ascending");
425 if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
Bob Wilsone4077362013-09-09 19:14:35 +0000426 I->High = J->High;
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000427 // FIXME: Combine branch weights.
428 } else if (++I != J) {
429 *I = *J;
Bob Wilsone4077362013-09-09 19:14:35 +0000430 }
431 }
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000432 Cases.erase(std::next(I), Cases.end());
433 }
Bob Wilsone4077362013-09-09 19:14:35 +0000434
Roman Tereshin99a66722019-02-22 14:33:46 +0000435 return NumSimpleCases;
436}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000437
Sanjay Patel815adac2015-09-16 16:21:08 +0000438/// Replace the specified switch instruction with a sequence of chained if-then
439/// insts in a balanced binary search.
Chen Li0786bc92015-08-11 20:16:17 +0000440void LowerSwitch::processSwitchInst(SwitchInst *SI,
Roman Tereshin99a66722019-02-22 14:33:46 +0000441 SmallPtrSetImpl<BasicBlock *> &DeleteList,
442 AssumptionCache *AC, LazyValueInfo *LVI) {
443 BasicBlock *OrigBlock = SI->getParent();
444 Function *F = OrigBlock->getParent();
Eli Friedman95031ed2011-09-29 20:21:17 +0000445 Value *Val = SI->getCondition(); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000446 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000447
Matt Arsenault01d17e72017-04-21 23:54:12 +0000448 // Don't handle unreachable blocks. If there are successors with phis, this
449 // would leave them behind with missing predecessors.
Roman Tereshin99a66722019-02-22 14:33:46 +0000450 if ((OrigBlock != &F->getEntryBlock() && pred_empty(OrigBlock)) ||
451 OrigBlock->getSinglePredecessor() == OrigBlock) {
452 DeleteList.insert(OrigBlock);
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000453 return;
454 }
455
Hans Wennborgae9c9712015-01-23 20:43:51 +0000456 // Prepare cases vector.
457 CaseVector Cases;
Roman Tereshin99a66722019-02-22 14:33:46 +0000458 const unsigned NumSimpleCases = Clusterify(Cases, SI);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000459 LLVM_DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Roman Tereshin99a66722019-02-22 14:33:46 +0000460 << ". Total non-default cases: " << NumSimpleCases
461 << "\nCase clusters: " << Cases << "\n");
462
463 // If there is only the default destination, just branch.
464 if (Cases.empty()) {
465 BranchInst::Create(Default, OrigBlock);
466 // Remove all the references from Default's PHIs to OrigBlock, but one.
467 fixPhis(Default, OrigBlock, OrigBlock);
468 SI->eraseFromParent();
469 return;
470 }
Hans Wennborgae9c9712015-01-23 20:43:51 +0000471
472 ConstantInt *LowerBound = nullptr;
473 ConstantInt *UpperBound = nullptr;
Roman Tereshin99a66722019-02-22 14:33:46 +0000474 bool DefaultIsUnreachableFromSwitch = false;
Hans Wennborgae9c9712015-01-23 20:43:51 +0000475
476 if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000477 // Make the bounds tightly fitted around the case value range, because we
Hans Wennborgae9c9712015-01-23 20:43:51 +0000478 // know that the value passed to the switch must be exactly one of the case
479 // values.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000480 LowerBound = Cases.front().Low;
481 UpperBound = Cases.back().High;
Roman Tereshin99a66722019-02-22 14:33:46 +0000482 DefaultIsUnreachableFromSwitch = true;
483 } else {
484 // Constraining the range of the value being switched over helps eliminating
485 // unreachable BBs and minimizing the number of `add` instructions
486 // newLeafBlock ends up emitting. Running CorrelatedValuePropagation after
487 // LowerSwitch isn't as good, and also much more expensive in terms of
488 // compile time for the following reasons:
489 // 1. it processes many kinds of instructions, not just switches;
490 // 2. even if limited to icmp instructions only, it will have to process
491 // roughly C icmp's per switch, where C is the number of cases in the
492 // switch, while LowerSwitch only needs to call LVI once per switch.
493 const DataLayout &DL = F->getParent()->getDataLayout();
494 KnownBits Known = computeKnownBits(Val, DL, /*Depth=*/0, AC, SI);
Nikita Popov0125e442019-03-23 12:48:54 +0000495 // TODO Shouldn't this create a signed range?
496 ConstantRange KnownBitsRange =
497 ConstantRange::fromKnownBits(Known, /*ForSigned=*/false);
Roman Tereshin99a66722019-02-22 14:33:46 +0000498 const ConstantRange LVIRange = LVI->getConstantRange(Val, OrigBlock, SI);
499 ConstantRange ValRange = KnownBitsRange.intersectWith(LVIRange);
500 // We delegate removal of unreachable non-default cases to other passes. In
501 // the unlikely event that some of them survived, we just conservatively
502 // maintain the invariant that all the cases lie between the bounds. This
503 // may, however, still render the default case effectively unreachable.
504 APInt Low = Cases.front().Low->getValue();
505 APInt High = Cases.back().High->getValue();
506 APInt Min = APIntOps::smin(ValRange.getSignedMin(), Low);
507 APInt Max = APIntOps::smax(ValRange.getSignedMax(), High);
Hans Wennborgae9c9712015-01-23 20:43:51 +0000508
Roman Tereshin99a66722019-02-22 14:33:46 +0000509 LowerBound = ConstantInt::get(SI->getContext(), Min);
510 UpperBound = ConstantInt::get(SI->getContext(), Max);
511 DefaultIsUnreachableFromSwitch = (Min + (NumSimpleCases - 1) == Max);
512 }
513
514 std::vector<IntRange> UnreachableRanges;
515
516 if (DefaultIsUnreachableFromSwitch) {
Hans Wennborgae9c9712015-01-23 20:43:51 +0000517 DenseMap<BasicBlock *, unsigned> Popularity;
518 unsigned MaxPop = 0;
519 BasicBlock *PopSucc = nullptr;
520
Eugene Zelenkofce43572017-10-21 00:57:46 +0000521 IntRange R = {std::numeric_limits<int64_t>::min(),
522 std::numeric_limits<int64_t>::max()};
Hans Wennborgae9c9712015-01-23 20:43:51 +0000523 UnreachableRanges.push_back(R);
524 for (const auto &I : Cases) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000525 int64_t Low = I.Low->getSExtValue();
526 int64_t High = I.High->getSExtValue();
Hans Wennborgae9c9712015-01-23 20:43:51 +0000527
528 IntRange &LastRange = UnreachableRanges.back();
529 if (LastRange.Low == Low) {
530 // There is nothing left of the previous range.
531 UnreachableRanges.pop_back();
532 } else {
533 // Terminate the previous range.
534 assert(Low > LastRange.Low);
535 LastRange.High = Low - 1;
536 }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000537 if (High != std::numeric_limits<int64_t>::max()) {
538 IntRange R = { High + 1, std::numeric_limits<int64_t>::max() };
Hans Wennborgae9c9712015-01-23 20:43:51 +0000539 UnreachableRanges.push_back(R);
540 }
541
542 // Count popularity.
543 int64_t N = High - Low + 1;
544 unsigned &Pop = Popularity[I.BB];
545 if ((Pop += N) > MaxPop) {
546 MaxPop = Pop;
547 PopSucc = I.BB;
548 }
549 }
550#ifndef NDEBUG
551 /* UnreachableRanges should be sorted and the ranges non-adjacent. */
552 for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
553 I != E; ++I) {
554 assert(I->Low <= I->High);
555 auto Next = I + 1;
556 if (Next != E) {
557 assert(Next->Low > I->High);
558 }
559 }
560#endif
561
Karl-Johan Karlsson1ffeb5d2018-07-10 12:06:16 +0000562 // As the default block in the switch is unreachable, update the PHI nodes
Roman Tereshin99a66722019-02-22 14:33:46 +0000563 // (remove all of the references to the default block) to reflect this.
564 const unsigned NumDefaultEdges = SI->getNumCases() + 1 - NumSimpleCases;
565 for (unsigned I = 0; I < NumDefaultEdges; ++I)
566 Default->removePredecessor(OrigBlock);
Karl-Johan Karlsson1ffeb5d2018-07-10 12:06:16 +0000567
Hans Wennborgae9c9712015-01-23 20:43:51 +0000568 // Use the most popular block as the new default, reducing the number of
569 // cases.
570 assert(MaxPop > 0 && PopSucc);
571 Default = PopSucc;
David Majnemerc7004902016-08-12 04:32:37 +0000572 Cases.erase(
Eugene Zelenkofce43572017-10-21 00:57:46 +0000573 llvm::remove_if(
574 Cases, [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }),
David Majnemerc7004902016-08-12 04:32:37 +0000575 Cases.end());
Hans Wennborgae9c9712015-01-23 20:43:51 +0000576
577 // If there are no cases left, just branch.
578 if (Cases.empty()) {
Roman Tereshin99a66722019-02-22 14:33:46 +0000579 BranchInst::Create(Default, OrigBlock);
Hans Wennborgae9c9712015-01-23 20:43:51 +0000580 SI->eraseFromParent();
Karl-Johan Karlsson1ffeb5d2018-07-10 12:06:16 +0000581 // As all the cases have been replaced with a single branch, only keep
582 // one entry in the PHI nodes.
583 for (unsigned I = 0 ; I < (MaxPop - 1) ; ++I)
584 PopSucc->removePredecessor(OrigBlock);
Hans Wennborgae9c9712015-01-23 20:43:51 +0000585 return;
586 }
Andrew Kaylor4172dba2019-06-03 17:54:15 +0000587
588 // If the condition was a PHI node with the switch block as a predecessor
589 // removing predecessors may have caused the condition to be erased.
590 // Getting the condition value again here protects against that.
591 Val = SI->getCondition();
Hans Wennborgae9c9712015-01-23 20:43:51 +0000592 }
593
Chris Lattnered922162003-10-07 18:46:23 +0000594 // Create a new, empty default block so that the new hierarchy of
595 // if-then statements go to this and the PHI nodes are happy.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000596 BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000597 F->getBasicBlockList().insert(Default->getIterator(), NewDefault);
Hans Wennborgae9c9712015-01-23 20:43:51 +0000598 BranchInst::Create(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000599
Jim Grosbachfff56632014-06-16 16:55:20 +0000600 BasicBlock *SwitchBlock =
601 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000602 OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
Chris Lattnered922162003-10-07 18:46:23 +0000603
Karl-Johan Karlsson11d68a62018-05-22 08:46:48 +0000604 // If there are entries in any PHI nodes for the default edge, make sure
605 // to update them as well.
Roman Tereshin99a66722019-02-22 14:33:46 +0000606 fixPhis(Default, OrigBlock, NewDefault);
Karl-Johan Karlsson11d68a62018-05-22 08:46:48 +0000607
Chris Lattnered922162003-10-07 18:46:23 +0000608 // Branch to our shiny new if-then stuff...
Gabor Greife9ecc682008-04-06 20:25:17 +0000609 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnered922162003-10-07 18:46:23 +0000610
Chris Lattner1b094a02003-04-23 16:23:59 +0000611 // We are now done with the switch instruction, delete it.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000612 BasicBlock *OldDefault = SI->getDefaultDest();
Roman Tereshin99a66722019-02-22 14:33:46 +0000613 OrigBlock->getInstList().erase(SI);
Jim Grosbachfff56632014-06-16 16:55:20 +0000614
Chen Li10f01bd2015-08-11 18:12:26 +0000615 // If the Default block has no more predecessors just add it to DeleteList.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000616 if (pred_begin(OldDefault) == pred_end(OldDefault))
Chen Li0786bc92015-08-11 20:16:17 +0000617 DeleteList.insert(OldDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000618}