blob: f18bd2539a770fc36cc571c957630cda47ea1e3b [file] [log] [blame]
Chris Lattner1b094a02003-04-23 16:23:59 +00001//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
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 Lattner1b094a02003-04-23 16:23:59 +00009//
Gordon Henriksend5687672007-11-04 16:15:04 +000010// The LowerSwitch transformation rewrites switch instructions with a sequence
11// of branches, which allows targets to get away with not implementing the
12// switch instruction until it is convenient.
Chris Lattner1b094a02003-04-23 16:23:59 +000013//
14//===----------------------------------------------------------------------===//
15
Eugene Zelenkofce43572017-10-21 00:57:46 +000016#include "llvm/ADT/DenseMap.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000018#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/IR/BasicBlock.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000021#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/Function.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000024#include "llvm/IR/InstrTypes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Instructions.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000026#include "llvm/IR/Value.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000027#include "llvm/Pass.h"
Eugene Zelenkofce43572017-10-21 00:57:46 +000028#include "llvm/Support/Casting.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000029#include "llvm/Support/Compiler.h"
Nick Lewycky974e12b2009-10-25 06:57:41 +000030#include "llvm/Support/Debug.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000031#include "llvm/Support/raw_ostream.h"
David Blaikiea373d182018-03-28 17:44:36 +000032#include "llvm/Transforms/Utils.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000033#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000034#include <algorithm>
Eugene Zelenkofce43572017-10-21 00:57:46 +000035#include <cassert>
36#include <cstdint>
37#include <iterator>
38#include <limits>
39#include <vector>
40
Chris Lattner49525f82004-01-09 06:02:20 +000041using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000042
Chandler Carruthe96dd892014-04-21 22:55:11 +000043#define DEBUG_TYPE "lower-switch"
44
Chris Lattner1b094a02003-04-23 16:23:59 +000045namespace {
Eugene Zelenkofce43572017-10-21 00:57:46 +000046
Hans Wennborgae9c9712015-01-23 20:43:51 +000047 struct IntRange {
48 int64_t Low, High;
49 };
Hans Wennborgae9c9712015-01-23 20:43:51 +000050
Eugene Zelenkofce43572017-10-21 00:57:46 +000051} // end anonymous namespace
52
53// Return true iff R is covered by Ranges.
54static bool IsInRanges(const IntRange &R,
55 const std::vector<IntRange> &Ranges) {
56 // Note: Ranges must be sorted, non-overlapping and non-adjacent.
57
58 // Find the first range whose High field is >= R.High,
59 // then check if the Low field is <= R.Low. If so, we
60 // have a Range that covers R.
61 auto I = std::lower_bound(
62 Ranges.begin(), Ranges.end(), R,
63 [](const IntRange &A, const IntRange &B) { return A.High < B.High; });
64 return I != Ranges.end() && I->Low <= R.Low;
65}
66
67namespace {
Hans Wennborgae9c9712015-01-23 20:43:51 +000068
Sanjay Patel815adac2015-09-16 16:21:08 +000069 /// Replace all SwitchInst instructions with chained branch instructions.
Nick Lewycky02d5f772009-10-25 06:33:48 +000070 class LowerSwitch : public FunctionPass {
Chris Lattnered922162003-10-07 18:46:23 +000071 public:
Eugene Zelenkofce43572017-10-21 00:57:46 +000072 // Pass identification, replacement for typeid
73 static char ID;
74
Owen Anderson6c18d1a2010-10-19 17:21:58 +000075 LowerSwitch() : FunctionPass(ID) {
76 initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
77 }
Devang Patel09f162c2007-05-01 21:15:47 +000078
Craig Topper3e4c6972014-03-05 09:10:37 +000079 bool runOnFunction(Function &F) override;
80
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000081 struct CaseRange {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +000082 ConstantInt* Low;
83 ConstantInt* High;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000084 BasicBlock* BB;
85
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +000086 CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
Hans Wennborg8c82fbc2015-02-05 16:50:27 +000087 : Low(low), High(high), BB(bb) {}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000088 };
89
Eugene Zelenkofce43572017-10-21 00:57:46 +000090 using CaseVector = std::vector<CaseRange>;
91 using CaseItr = std::vector<CaseRange>::iterator;
92
Chris Lattnered922162003-10-07 18:46:23 +000093 private:
Chen Li0786bc92015-08-11 20:16:17 +000094 void processSwitchInst(SwitchInst *SI, SmallPtrSetImpl<BasicBlock*> &DeleteList);
Chris Lattnered922162003-10-07 18:46:23 +000095
Jim Grosbachfff56632014-06-16 16:55:20 +000096 BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
97 ConstantInt *LowerBound, ConstantInt *UpperBound,
Marcello Maggioni78035b12014-07-11 10:34:36 +000098 Value *Val, BasicBlock *Predecessor,
Hans Wennborgae9c9712015-01-23 20:43:51 +000099 BasicBlock *OrigBlock, BasicBlock *Default,
100 const std::vector<IntRange> &UnreachableRanges);
Jim Grosbachfff56632014-06-16 16:55:20 +0000101 BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
102 BasicBlock *Default);
103 unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +0000104 };
Bob Wilsone4077362013-09-09 19:14:35 +0000105
106 /// The comparison function for sorting the switch case values in the vector.
107 /// WARNING: Case ranges should be disjoint!
108 struct CaseCmp {
Eugene Zelenkofce43572017-10-21 00:57:46 +0000109 bool operator()(const LowerSwitch::CaseRange& C1,
110 const LowerSwitch::CaseRange& C2) {
Bob Wilsone4077362013-09-09 19:14:35 +0000111 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
112 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
113 return CI1->getValue().slt(CI2->getValue());
114 }
115 };
Eugene Zelenkofce43572017-10-21 00:57:46 +0000116
117} // end anonymous namespace
Chris Lattner1b094a02003-04-23 16:23:59 +0000118
Dan Gohmand78c4002008-05-13 00:00:25 +0000119char LowerSwitch::ID = 0;
Dan Gohmand78c4002008-05-13 00:00:25 +0000120
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000121// Publicly exposed interface to pass...
Owen Andersona7aed182010-08-06 18:33:48 +0000122char &llvm::LowerSwitchID = LowerSwitch::ID;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000123
124INITIALIZE_PASS(LowerSwitch, "lowerswitch",
125 "Lower SwitchInst's to branches", false, false)
126
Chris Lattner1b094a02003-04-23 16:23:59 +0000127// createLowerSwitchPass - Interface to this file...
Chris Lattner49525f82004-01-09 06:02:20 +0000128FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner1b094a02003-04-23 16:23:59 +0000129 return new LowerSwitch();
130}
131
132bool LowerSwitch::runOnFunction(Function &F) {
133 bool Changed = false;
Chen Li0786bc92015-08-11 20:16:17 +0000134 SmallPtrSet<BasicBlock*, 8> DeleteList;
Chris Lattner1b094a02003-04-23 16:23:59 +0000135
136 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000137 BasicBlock *Cur = &*I++; // Advance over block so we don't traverse new blocks
Chris Lattner1b094a02003-04-23 16:23:59 +0000138
Chen Li0786bc92015-08-11 20:16:17 +0000139 // If the block is a dead Default block that will be deleted later, don't
140 // waste time processing it.
141 if (DeleteList.count(Cur))
142 continue;
143
Chris Lattner1b094a02003-04-23 16:23:59 +0000144 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
145 Changed = true;
Chen Li10f01bd2015-08-11 18:12:26 +0000146 processSwitchInst(SI, DeleteList);
Chris Lattner1b094a02003-04-23 16:23:59 +0000147 }
148 }
149
Chen Li10f01bd2015-08-11 18:12:26 +0000150 for (BasicBlock* BB: DeleteList) {
151 DeleteDeadBlock(BB);
152 }
153
Chris Lattner1b094a02003-04-23 16:23:59 +0000154 return Changed;
155}
156
Sanjay Patel815adac2015-09-16 16:21:08 +0000157/// Used for debugging purposes.
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000158static raw_ostream& operator<<(raw_ostream &O,
Chandler Carruth88c54b82010-10-23 08:10:43 +0000159 const LowerSwitch::CaseVector &C)
160 LLVM_ATTRIBUTE_USED;
Eugene Zelenkofce43572017-10-21 00:57:46 +0000161
Mike Stump47987632009-07-27 23:33:34 +0000162static raw_ostream& operator<<(raw_ostream &O,
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000163 const LowerSwitch::CaseVector &C) {
Chris Lattnered922162003-10-07 18:46:23 +0000164 O << "[";
165
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000166 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
Chris Lattner49525f82004-01-09 06:02:20 +0000167 E = C.end(); B != E; ) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000168 O << *B->Low << " -" << *B->High;
Chris Lattnered922162003-10-07 18:46:23 +0000169 if (++B != E) O << ", ";
170 }
171
172 return O << "]";
173}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000174
Sanjay Patel815adac2015-09-16 16:21:08 +0000175/// \brief Update the first occurrence of the "switch statement" BB in the PHI
176/// node with the "new" BB. The other occurrences will:
177///
178/// 1) Be updated by subsequent calls to this function. Switch statements may
179/// have more than one outcoming edge into the same BB if they all have the same
180/// value. When the switch statement is converted these incoming edges are now
181/// coming from multiple BBs.
182/// 2) Removed if subsequent incoming values now share the same case, i.e.,
183/// multiple outcome edges are condensed into one. This is necessary to keep the
184/// number of phi values equal to the number of branches to SuccBB.
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000185static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
186 unsigned NumMergedCases) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000187 for (BasicBlock::iterator I = SuccBB->begin(),
188 IE = SuccBB->getFirstNonPHI()->getIterator();
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000189 I != IE; ++I) {
Marcello Maggioni78035b12014-07-11 10:34:36 +0000190 PHINode *PN = cast<PHINode>(I);
191
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000192 // Only update the first occurrence.
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000193 unsigned Idx = 0, E = PN->getNumIncomingValues();
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000194 unsigned LocalNumMergedCases = NumMergedCases;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000195 for (; Idx != E; ++Idx) {
Juergen Ributzkad4417252014-11-10 21:05:27 +0000196 if (PN->getIncomingBlock(Idx) == OrigBB) {
197 PN->setIncomingBlock(Idx, NewBB);
198 break;
199 }
Marcello Maggioni78035b12014-07-11 10:34:36 +0000200 }
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000201
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000202 // Remove additional occurrences coming from condensed cases and keep the
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000203 // number of incoming values equal to the number of branches to SuccBB.
Michael Liao24fcae82015-03-17 18:03:10 +0000204 SmallVector<unsigned, 8> Indices;
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000205 for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000206 if (PN->getIncomingBlock(Idx) == OrigBB) {
Michael Liao24fcae82015-03-17 18:03:10 +0000207 Indices.push_back(Idx);
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000208 LocalNumMergedCases--;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000209 }
Michael Liao24fcae82015-03-17 18:03:10 +0000210 // Remove incoming values in the reverse order to prevent invalidating
211 // *successive* index.
Eugene Zelenkofce43572017-10-21 00:57:46 +0000212 for (unsigned III : llvm::reverse(Indices))
David Majnemerd7708772016-06-24 04:05:21 +0000213 PN->removeIncomingValue(III);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000214 }
215}
216
Sanjay Patel815adac2015-09-16 16:21:08 +0000217/// Convert the switch statement into a binary lookup of the case values.
218/// The function recursively builds this tree. LowerBound and UpperBound are
219/// used to keep track of the bounds for Val that have already been checked by
220/// a block emitted by one of the previous calls to switchConvert in the call
221/// stack.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000222BasicBlock *
223LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
224 ConstantInt *UpperBound, Value *Val,
225 BasicBlock *Predecessor, BasicBlock *OrigBlock,
226 BasicBlock *Default,
227 const std::vector<IntRange> &UnreachableRanges) {
Chris Lattnered922162003-10-07 18:46:23 +0000228 unsigned Size = End - Begin;
229
Jim Grosbachfff56632014-06-16 16:55:20 +0000230 if (Size == 1) {
231 // Check if the Case Range is perfectly squeezed in between
232 // already checked Upper and Lower bounds. If it is then we can avoid
233 // emitting the code that checks if the value actually falls in the range
234 // because the bounds already tell us so.
235 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000236 unsigned NumMergedCases = 0;
237 if (LowerBound && UpperBound)
238 NumMergedCases =
239 UpperBound->getSExtValue() - LowerBound->getSExtValue();
240 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
Jim Grosbachfff56632014-06-16 16:55:20 +0000241 return Begin->BB;
242 }
Chris Lattnered922162003-10-07 18:46:23 +0000243 return newLeafBlock(*Begin, Val, OrigBlock, Default);
Jim Grosbachfff56632014-06-16 16:55:20 +0000244 }
Chris Lattnered922162003-10-07 18:46:23 +0000245
246 unsigned Mid = Size / 2;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000247 std::vector<CaseRange> LHS(Begin, Begin + Mid);
David Greene50c54232010-01-05 01:26:45 +0000248 DEBUG(dbgs() << "LHS: " << LHS << "\n");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000249 std::vector<CaseRange> RHS(Begin + Mid, End);
David Greene50c54232010-01-05 01:26:45 +0000250 DEBUG(dbgs() << "RHS: " << RHS << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000251
Jim Grosbachfff56632014-06-16 16:55:20 +0000252 CaseRange &Pivot = *(Begin + Mid);
253 DEBUG(dbgs() << "Pivot ==> "
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000254 << Pivot.Low->getValue()
255 << " -" << Pivot.High->getValue() << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000256
Jim Grosbachfff56632014-06-16 16:55:20 +0000257 // NewLowerBound here should never be the integer minimal value.
258 // This is because it is computed from a case range that is never
259 // the smallest, so there is always a case range that has at least
260 // a smaller value.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000261 ConstantInt *NewLowerBound = Pivot.Low;
Jim Grosbachfff56632014-06-16 16:55:20 +0000262
Hans Wennborgae9c9712015-01-23 20:43:51 +0000263 // Because NewLowerBound is never the smallest representable integer
264 // it is safe here to subtract one.
265 ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
266 NewLowerBound->getValue() - 1);
267
268 if (!UnreachableRanges.empty()) {
269 // Check if the gap between LHS's highest and NewLowerBound is unreachable.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000270 int64_t GapLow = LHS.back().High->getSExtValue() + 1;
Hans Wennborgae9c9712015-01-23 20:43:51 +0000271 int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
272 IntRange Gap = { GapLow, GapHigh };
273 if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000274 NewUpperBound = LHS.back().High;
Jim Grosbachfff56632014-06-16 16:55:20 +0000275 }
276
277 DEBUG(dbgs() << "LHS Bounds ==> ";
278 if (LowerBound) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000279 dbgs() << LowerBound->getSExtValue();
Jim Grosbachfff56632014-06-16 16:55:20 +0000280 } else {
281 dbgs() << "NONE";
282 }
283 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
284 dbgs() << "RHS Bounds ==> ";
285 dbgs() << NewLowerBound->getSExtValue() << " - ";
286 if (UpperBound) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000287 dbgs() << UpperBound->getSExtValue() << "\n";
Jim Grosbachfff56632014-06-16 16:55:20 +0000288 } else {
289 dbgs() << "NONE\n";
290 });
291
Chris Lattnered922162003-10-07 18:46:23 +0000292 // Create a new node that checks if the value is < pivot. Go to the
293 // left branch if it is and right branch if not.
294 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000295 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Chris Lattnered922162003-10-07 18:46:23 +0000296
Bob Wilsone4077362013-09-09 19:14:35 +0000297 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000298 Val, Pivot.Low, "Pivot");
Marcello Maggioni78035b12014-07-11 10:34:36 +0000299
300 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
301 NewUpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000302 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000303 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
304 UpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000305 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000306
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000307 F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000308 NewNode->getInstList().push_back(Comp);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000309
Gabor Greife9ecc682008-04-06 20:25:17 +0000310 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000311 return NewNode;
312}
313
Sanjay Patel815adac2015-09-16 16:21:08 +0000314/// Create a new leaf block for the binary lookup tree. It checks if the
315/// switch's value == the case's value. If not, then it jumps to the default
316/// branch. At this point in the tree, the value can't be another valid case
317/// value, so the jump to the "default" branch is warranted.
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000318BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnered922162003-10-07 18:46:23 +0000319 BasicBlock* OrigBlock,
Eugene Zelenkofce43572017-10-21 00:57:46 +0000320 BasicBlock* Default) {
Chris Lattnered922162003-10-07 18:46:23 +0000321 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000322 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000323 F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000324
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000325 // Emit comparison
Craig Topperf40110f2014-04-25 05:29:35 +0000326 ICmpInst* Comp = nullptr;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000327 if (Leaf.Low == Leaf.High) {
328 // Make the seteq instruction...
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000329 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
330 Leaf.Low, "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000331 } else {
332 // Make range comparison
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000333 if (Leaf.Low->isMinValue(true /*isSigned*/)) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000334 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000335 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
336 "SwitchLeaf");
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000337 } else if (Leaf.Low->isZero()) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000338 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000339 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
340 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000341 } else {
342 // Emit V-Lo <=u Hi-Lo
Owen Anderson487375e2009-07-29 18:55:55 +0000343 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000344 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000345 Val->getName()+".off",
346 NewLeaf);
Owen Anderson487375e2009-07-29 18:55:55 +0000347 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000348 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
349 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000350 }
351 }
Chris Lattnered922162003-10-07 18:46:23 +0000352
353 // Make the conditional branch...
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000354 BasicBlock* Succ = Leaf.BB;
Gabor Greife9ecc682008-04-06 20:25:17 +0000355 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000356
357 // If there were any PHI nodes in this successor, rewrite one entry
358 // from OrigBlock to come from NewLeaf.
Reid Spencer66149462004-09-15 17:06:42 +0000359 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
360 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000361 // Remove all but one incoming entries from the cluster
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000362 uint64_t Range = Leaf.High->getSExtValue() -
363 Leaf.Low->getSExtValue();
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000364 for (uint64_t j = 0; j < Range; ++j) {
365 PN->removeIncomingValue(OrigBlock);
366 }
367
Chris Lattnered922162003-10-07 18:46:23 +0000368 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
369 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
370 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
371 }
372
373 return NewLeaf;
374}
375
Sanjay Patel815adac2015-09-16 16:21:08 +0000376/// Transform simple list of Cases into list of CaseRange's.
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000377unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
Bob Wilsone4077362013-09-09 19:14:35 +0000378 unsigned numCmps = 0;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000379
380 // Start with "simple" cases
Chandler Carruth927d8e62017-04-12 07:27:28 +0000381 for (auto Case : SI->cases())
382 Cases.push_back(CaseRange(Case.getCaseValue(), Case.getCaseValue(),
383 Case.getCaseSuccessor()));
384
Mandeep Singh Grang636d94d2018-04-13 19:47:57 +0000385 llvm::sort(Cases.begin(), Cases.end(), CaseCmp());
Bob Wilsone4077362013-09-09 19:14:35 +0000386
387 // Merge case into clusters
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000388 if (Cases.size() >= 2) {
389 CaseItr I = Cases.begin();
390 for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000391 int64_t nextValue = J->Low->getSExtValue();
392 int64_t currentValue = I->High->getSExtValue();
Bob Wilsone4077362013-09-09 19:14:35 +0000393 BasicBlock* nextBB = J->BB;
394 BasicBlock* currentBB = I->BB;
395
396 // If the two neighboring cases go to the same destination, merge them
397 // into a single case.
Justin Bognere46d3792015-06-20 00:28:25 +0000398 assert(nextValue > currentValue && "Cases should be strictly ascending");
399 if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
Bob Wilsone4077362013-09-09 19:14:35 +0000400 I->High = J->High;
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000401 // FIXME: Combine branch weights.
402 } else if (++I != J) {
403 *I = *J;
Bob Wilsone4077362013-09-09 19:14:35 +0000404 }
405 }
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000406 Cases.erase(std::next(I), Cases.end());
407 }
Bob Wilsone4077362013-09-09 19:14:35 +0000408
409 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
410 if (I->Low != I->High)
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000411 // A range counts double, since it requires two compares.
412 ++numCmps;
413 }
414
Bob Wilsone4077362013-09-09 19:14:35 +0000415 return numCmps;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000416}
417
Sanjay Patel815adac2015-09-16 16:21:08 +0000418/// Replace the specified switch instruction with a sequence of chained if-then
419/// insts in a balanced binary search.
Chen Li0786bc92015-08-11 20:16:17 +0000420void LowerSwitch::processSwitchInst(SwitchInst *SI,
421 SmallPtrSetImpl<BasicBlock*> &DeleteList) {
Chris Lattner1b094a02003-04-23 16:23:59 +0000422 BasicBlock *CurBlock = SI->getParent();
423 BasicBlock *OrigBlock = CurBlock;
424 Function *F = CurBlock->getParent();
Eli Friedman95031ed2011-09-29 20:21:17 +0000425 Value *Val = SI->getCondition(); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000426 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000427
Matt Arsenault01d17e72017-04-21 23:54:12 +0000428 // Don't handle unreachable blocks. If there are successors with phis, this
429 // would leave them behind with missing predecessors.
430 if ((CurBlock != &F->getEntryBlock() && pred_empty(CurBlock)) ||
431 CurBlock->getSinglePredecessor() == CurBlock) {
432 DeleteList.insert(CurBlock);
433 return;
434 }
435
Hans Wennborgae9c9712015-01-23 20:43:51 +0000436 // If there is only the default destination, just branch.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000437 if (!SI->getNumCases()) {
Hans Wennborgae9c9712015-01-23 20:43:51 +0000438 BranchInst::Create(Default, CurBlock);
439 SI->eraseFromParent();
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000440 return;
441 }
442
Hans Wennborgae9c9712015-01-23 20:43:51 +0000443 // Prepare cases vector.
444 CaseVector Cases;
445 unsigned numCmps = Clusterify(Cases, SI);
446 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
447 << ". Total compares: " << numCmps << "\n");
448 DEBUG(dbgs() << "Cases: " << Cases << "\n");
449 (void)numCmps;
450
451 ConstantInt *LowerBound = nullptr;
452 ConstantInt *UpperBound = nullptr;
453 std::vector<IntRange> UnreachableRanges;
454
455 if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000456 // Make the bounds tightly fitted around the case value range, because we
Hans Wennborgae9c9712015-01-23 20:43:51 +0000457 // know that the value passed to the switch must be exactly one of the case
458 // values.
459 assert(!Cases.empty());
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000460 LowerBound = Cases.front().Low;
461 UpperBound = Cases.back().High;
Hans Wennborgae9c9712015-01-23 20:43:51 +0000462
463 DenseMap<BasicBlock *, unsigned> Popularity;
464 unsigned MaxPop = 0;
465 BasicBlock *PopSucc = nullptr;
466
Eugene Zelenkofce43572017-10-21 00:57:46 +0000467 IntRange R = {std::numeric_limits<int64_t>::min(),
468 std::numeric_limits<int64_t>::max()};
Hans Wennborgae9c9712015-01-23 20:43:51 +0000469 UnreachableRanges.push_back(R);
470 for (const auto &I : Cases) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000471 int64_t Low = I.Low->getSExtValue();
472 int64_t High = I.High->getSExtValue();
Hans Wennborgae9c9712015-01-23 20:43:51 +0000473
474 IntRange &LastRange = UnreachableRanges.back();
475 if (LastRange.Low == Low) {
476 // There is nothing left of the previous range.
477 UnreachableRanges.pop_back();
478 } else {
479 // Terminate the previous range.
480 assert(Low > LastRange.Low);
481 LastRange.High = Low - 1;
482 }
Eugene Zelenkofce43572017-10-21 00:57:46 +0000483 if (High != std::numeric_limits<int64_t>::max()) {
484 IntRange R = { High + 1, std::numeric_limits<int64_t>::max() };
Hans Wennborgae9c9712015-01-23 20:43:51 +0000485 UnreachableRanges.push_back(R);
486 }
487
488 // Count popularity.
489 int64_t N = High - Low + 1;
490 unsigned &Pop = Popularity[I.BB];
491 if ((Pop += N) > MaxPop) {
492 MaxPop = Pop;
493 PopSucc = I.BB;
494 }
495 }
496#ifndef NDEBUG
497 /* UnreachableRanges should be sorted and the ranges non-adjacent. */
498 for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
499 I != E; ++I) {
500 assert(I->Low <= I->High);
501 auto Next = I + 1;
502 if (Next != E) {
503 assert(Next->Low > I->High);
504 }
505 }
506#endif
507
508 // Use the most popular block as the new default, reducing the number of
509 // cases.
510 assert(MaxPop > 0 && PopSucc);
511 Default = PopSucc;
David Majnemerc7004902016-08-12 04:32:37 +0000512 Cases.erase(
Eugene Zelenkofce43572017-10-21 00:57:46 +0000513 llvm::remove_if(
514 Cases, [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }),
David Majnemerc7004902016-08-12 04:32:37 +0000515 Cases.end());
Hans Wennborgae9c9712015-01-23 20:43:51 +0000516
517 // If there are no cases left, just branch.
518 if (Cases.empty()) {
519 BranchInst::Create(Default, CurBlock);
520 SI->eraseFromParent();
521 return;
522 }
523 }
524
Chris Lattnered922162003-10-07 18:46:23 +0000525 // Create a new, empty default block so that the new hierarchy of
526 // if-then statements go to this and the PHI nodes are happy.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000527 BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000528 F->getBasicBlockList().insert(Default->getIterator(), NewDefault);
Hans Wennborgae9c9712015-01-23 20:43:51 +0000529 BranchInst::Create(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000530
Chris Lattnered922162003-10-07 18:46:23 +0000531 // If there is an entry in any PHI nodes for the default edge, make sure
532 // to update them as well.
Reid Spencer66149462004-09-15 17:06:42 +0000533 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
534 PHINode *PN = cast<PHINode>(I);
Chris Lattnered922162003-10-07 18:46:23 +0000535 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
536 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
537 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000538 }
539
Jim Grosbachfff56632014-06-16 16:55:20 +0000540 BasicBlock *SwitchBlock =
541 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000542 OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
Chris Lattnered922162003-10-07 18:46:23 +0000543
544 // Branch to our shiny new if-then stuff...
Gabor Greife9ecc682008-04-06 20:25:17 +0000545 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnered922162003-10-07 18:46:23 +0000546
Chris Lattner1b094a02003-04-23 16:23:59 +0000547 // We are now done with the switch instruction, delete it.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000548 BasicBlock *OldDefault = SI->getDefaultDest();
Chris Lattnerb6865952004-03-14 04:14:31 +0000549 CurBlock->getInstList().erase(SI);
Jim Grosbachfff56632014-06-16 16:55:20 +0000550
Chen Li10f01bd2015-08-11 18:12:26 +0000551 // If the Default block has no more predecessors just add it to DeleteList.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000552 if (pred_begin(OldDefault) == pred_end(OldDefault))
Chen Li0786bc92015-08-11 20:16:17 +0000553 DeleteList.insert(OldDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000554}