blob: e73d28fd98e2b6f83d2214098292e0943c60bb06 [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
16#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/STLExtras.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000018#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
20#include "llvm/IR/Function.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/LLVMContext.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000023#include "llvm/Pass.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000024#include "llvm/Support/Compiler.h"
Nick Lewycky974e12b2009-10-25 06:57:41 +000025#include "llvm/Support/Debug.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000026#include "llvm/Support/raw_ostream.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000029#include <algorithm>
Chris Lattner49525f82004-01-09 06:02:20 +000030using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000031
Chandler Carruthe96dd892014-04-21 22:55:11 +000032#define DEBUG_TYPE "lower-switch"
33
Chris Lattner1b094a02003-04-23 16:23:59 +000034namespace {
Hans Wennborgae9c9712015-01-23 20:43:51 +000035 struct IntRange {
36 int64_t Low, High;
37 };
38 // Return true iff R is covered by Ranges.
39 static bool IsInRanges(const IntRange &R,
40 const std::vector<IntRange> &Ranges) {
41 // Note: Ranges must be sorted, non-overlapping and non-adjacent.
42
43 // Find the first range whose High field is >= R.High,
44 // then check if the Low field is <= R.Low. If so, we
45 // have a Range that covers R.
46 auto I = std::lower_bound(
47 Ranges.begin(), Ranges.end(), R,
48 [](const IntRange &A, const IntRange &B) { return A.High < B.High; });
49 return I != Ranges.end() && I->Low <= R.Low;
50 }
51
Sanjay Patel815adac2015-09-16 16:21:08 +000052 /// Replace all SwitchInst instructions with chained branch instructions.
Nick Lewycky02d5f772009-10-25 06:33:48 +000053 class LowerSwitch : public FunctionPass {
Chris Lattnered922162003-10-07 18:46:23 +000054 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +000055 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000056 LowerSwitch() : FunctionPass(ID) {
57 initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
58 }
Devang Patel09f162c2007-05-01 21:15:47 +000059
Craig Topper3e4c6972014-03-05 09:10:37 +000060 bool runOnFunction(Function &F) override;
61
62 void getAnalysisUsage(AnalysisUsage &AU) const override {
Anton Korobeynikovfb801512007-04-16 18:10:23 +000063 // This is a cluster of orthogonal Transforms
Chris Lattner4fe87d62006-05-09 04:13:41 +000064 AU.addPreserved<UnifyFunctionExitNodes>();
Chris Lattnere4cb4762006-05-17 21:05:27 +000065 AU.addPreservedID(LowerInvokePassID);
Chris Lattner4fe87d62006-05-09 04:13:41 +000066 }
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000067
68 struct CaseRange {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +000069 ConstantInt* Low;
70 ConstantInt* High;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000071 BasicBlock* BB;
72
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +000073 CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
Hans Wennborg8c82fbc2015-02-05 16:50:27 +000074 : Low(low), High(high), BB(bb) {}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000075 };
76
Jim Grosbachfff56632014-06-16 16:55:20 +000077 typedef std::vector<CaseRange> CaseVector;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000078 typedef std::vector<CaseRange>::iterator CaseItr;
Chris Lattnered922162003-10-07 18:46:23 +000079 private:
Chen Li0786bc92015-08-11 20:16:17 +000080 void processSwitchInst(SwitchInst *SI, SmallPtrSetImpl<BasicBlock*> &DeleteList);
Chris Lattnered922162003-10-07 18:46:23 +000081
Jim Grosbachfff56632014-06-16 16:55:20 +000082 BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
83 ConstantInt *LowerBound, ConstantInt *UpperBound,
Marcello Maggioni78035b12014-07-11 10:34:36 +000084 Value *Val, BasicBlock *Predecessor,
Hans Wennborgae9c9712015-01-23 20:43:51 +000085 BasicBlock *OrigBlock, BasicBlock *Default,
86 const std::vector<IntRange> &UnreachableRanges);
Jim Grosbachfff56632014-06-16 16:55:20 +000087 BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
88 BasicBlock *Default);
89 unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000090 };
Bob Wilsone4077362013-09-09 19:14:35 +000091
92 /// The comparison function for sorting the switch case values in the vector.
93 /// WARNING: Case ranges should be disjoint!
94 struct CaseCmp {
95 bool operator () (const LowerSwitch::CaseRange& C1,
96 const LowerSwitch::CaseRange& C2) {
97
98 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
99 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
100 return CI1->getValue().slt(CI2->getValue());
101 }
102 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000103}
Chris Lattner1b094a02003-04-23 16:23:59 +0000104
Dan Gohmand78c4002008-05-13 00:00:25 +0000105char LowerSwitch::ID = 0;
Owen Andersond31d82d2010-08-23 17:52:01 +0000106INITIALIZE_PASS(LowerSwitch, "lowerswitch",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000107 "Lower SwitchInst's to branches", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000108
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000109// Publicly exposed interface to pass...
Owen Andersona7aed182010-08-06 18:33:48 +0000110char &llvm::LowerSwitchID = LowerSwitch::ID;
Chris Lattner1b094a02003-04-23 16:23:59 +0000111// createLowerSwitchPass - Interface to this file...
Chris Lattner49525f82004-01-09 06:02:20 +0000112FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner1b094a02003-04-23 16:23:59 +0000113 return new LowerSwitch();
114}
115
116bool LowerSwitch::runOnFunction(Function &F) {
117 bool Changed = false;
Chen Li0786bc92015-08-11 20:16:17 +0000118 SmallPtrSet<BasicBlock*, 8> DeleteList;
Chris Lattner1b094a02003-04-23 16:23:59 +0000119
120 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000121 BasicBlock *Cur = &*I++; // Advance over block so we don't traverse new blocks
Chris Lattner1b094a02003-04-23 16:23:59 +0000122
Chen Li0786bc92015-08-11 20:16:17 +0000123 // If the block is a dead Default block that will be deleted later, don't
124 // waste time processing it.
125 if (DeleteList.count(Cur))
126 continue;
127
Chris Lattner1b094a02003-04-23 16:23:59 +0000128 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
129 Changed = true;
Chen Li10f01bd2015-08-11 18:12:26 +0000130 processSwitchInst(SI, DeleteList);
Chris Lattner1b094a02003-04-23 16:23:59 +0000131 }
132 }
133
Chen Li10f01bd2015-08-11 18:12:26 +0000134 for (BasicBlock* BB: DeleteList) {
135 DeleteDeadBlock(BB);
136 }
137
Chris Lattner1b094a02003-04-23 16:23:59 +0000138 return Changed;
139}
140
Sanjay Patel815adac2015-09-16 16:21:08 +0000141/// Used for debugging purposes.
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000142static raw_ostream& operator<<(raw_ostream &O,
Chandler Carruth88c54b82010-10-23 08:10:43 +0000143 const LowerSwitch::CaseVector &C)
144 LLVM_ATTRIBUTE_USED;
Mike Stump47987632009-07-27 23:33:34 +0000145static raw_ostream& operator<<(raw_ostream &O,
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000146 const LowerSwitch::CaseVector &C) {
Chris Lattnered922162003-10-07 18:46:23 +0000147 O << "[";
148
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000149 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
Chris Lattner49525f82004-01-09 06:02:20 +0000150 E = C.end(); B != E; ) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000151 O << *B->Low << " -" << *B->High;
Chris Lattnered922162003-10-07 18:46:23 +0000152 if (++B != E) O << ", ";
153 }
154
155 return O << "]";
156}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000157
Sanjay Patel815adac2015-09-16 16:21:08 +0000158/// \brief Update the first occurrence of the "switch statement" BB in the PHI
159/// node with the "new" BB. The other occurrences will:
160///
161/// 1) Be updated by subsequent calls to this function. Switch statements may
162/// have more than one outcoming edge into the same BB if they all have the same
163/// value. When the switch statement is converted these incoming edges are now
164/// coming from multiple BBs.
165/// 2) Removed if subsequent incoming values now share the same case, i.e.,
166/// multiple outcome edges are condensed into one. This is necessary to keep the
167/// number of phi values equal to the number of branches to SuccBB.
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000168static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
169 unsigned NumMergedCases) {
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000170 for (BasicBlock::iterator I = SuccBB->begin(),
171 IE = SuccBB->getFirstNonPHI()->getIterator();
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000172 I != IE; ++I) {
Marcello Maggioni78035b12014-07-11 10:34:36 +0000173 PHINode *PN = cast<PHINode>(I);
174
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000175 // Only update the first occurrence.
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000176 unsigned Idx = 0, E = PN->getNumIncomingValues();
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000177 unsigned LocalNumMergedCases = NumMergedCases;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000178 for (; Idx != E; ++Idx) {
Juergen Ributzkad4417252014-11-10 21:05:27 +0000179 if (PN->getIncomingBlock(Idx) == OrigBB) {
180 PN->setIncomingBlock(Idx, NewBB);
181 break;
182 }
Marcello Maggioni78035b12014-07-11 10:34:36 +0000183 }
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000184
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000185 // Remove additional occurrences coming from condensed cases and keep the
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000186 // number of incoming values equal to the number of branches to SuccBB.
Michael Liao24fcae82015-03-17 18:03:10 +0000187 SmallVector<unsigned, 8> Indices;
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000188 for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000189 if (PN->getIncomingBlock(Idx) == OrigBB) {
Michael Liao24fcae82015-03-17 18:03:10 +0000190 Indices.push_back(Idx);
Bruno Cardoso Lopes15520db2014-12-02 18:31:53 +0000191 LocalNumMergedCases--;
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000192 }
Michael Liao24fcae82015-03-17 18:03:10 +0000193 // Remove incoming values in the reverse order to prevent invalidating
194 // *successive* index.
David Majnemerd7708772016-06-24 04:05:21 +0000195 for (unsigned III : reverse(Indices))
196 PN->removeIncomingValue(III);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000197 }
198}
199
Sanjay Patel815adac2015-09-16 16:21:08 +0000200/// Convert the switch statement into a binary lookup of the case values.
201/// The function recursively builds this tree. LowerBound and UpperBound are
202/// used to keep track of the bounds for Val that have already been checked by
203/// a block emitted by one of the previous calls to switchConvert in the call
204/// stack.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000205BasicBlock *
206LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
207 ConstantInt *UpperBound, Value *Val,
208 BasicBlock *Predecessor, BasicBlock *OrigBlock,
209 BasicBlock *Default,
210 const std::vector<IntRange> &UnreachableRanges) {
Chris Lattnered922162003-10-07 18:46:23 +0000211 unsigned Size = End - Begin;
212
Jim Grosbachfff56632014-06-16 16:55:20 +0000213 if (Size == 1) {
214 // Check if the Case Range is perfectly squeezed in between
215 // already checked Upper and Lower bounds. If it is then we can avoid
216 // emitting the code that checks if the value actually falls in the range
217 // because the bounds already tell us so.
218 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000219 unsigned NumMergedCases = 0;
220 if (LowerBound && UpperBound)
221 NumMergedCases =
222 UpperBound->getSExtValue() - LowerBound->getSExtValue();
223 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
Jim Grosbachfff56632014-06-16 16:55:20 +0000224 return Begin->BB;
225 }
Chris Lattnered922162003-10-07 18:46:23 +0000226 return newLeafBlock(*Begin, Val, OrigBlock, Default);
Jim Grosbachfff56632014-06-16 16:55:20 +0000227 }
Chris Lattnered922162003-10-07 18:46:23 +0000228
229 unsigned Mid = Size / 2;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000230 std::vector<CaseRange> LHS(Begin, Begin + Mid);
David Greene50c54232010-01-05 01:26:45 +0000231 DEBUG(dbgs() << "LHS: " << LHS << "\n");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000232 std::vector<CaseRange> RHS(Begin + Mid, End);
David Greene50c54232010-01-05 01:26:45 +0000233 DEBUG(dbgs() << "RHS: " << RHS << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000234
Jim Grosbachfff56632014-06-16 16:55:20 +0000235 CaseRange &Pivot = *(Begin + Mid);
236 DEBUG(dbgs() << "Pivot ==> "
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000237 << Pivot.Low->getValue()
238 << " -" << Pivot.High->getValue() << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000239
Jim Grosbachfff56632014-06-16 16:55:20 +0000240 // NewLowerBound here should never be the integer minimal value.
241 // This is because it is computed from a case range that is never
242 // the smallest, so there is always a case range that has at least
243 // a smaller value.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000244 ConstantInt *NewLowerBound = Pivot.Low;
Jim Grosbachfff56632014-06-16 16:55:20 +0000245
Hans Wennborgae9c9712015-01-23 20:43:51 +0000246 // Because NewLowerBound is never the smallest representable integer
247 // it is safe here to subtract one.
248 ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
249 NewLowerBound->getValue() - 1);
250
251 if (!UnreachableRanges.empty()) {
252 // Check if the gap between LHS's highest and NewLowerBound is unreachable.
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000253 int64_t GapLow = LHS.back().High->getSExtValue() + 1;
Hans Wennborgae9c9712015-01-23 20:43:51 +0000254 int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
255 IntRange Gap = { GapLow, GapHigh };
256 if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000257 NewUpperBound = LHS.back().High;
Jim Grosbachfff56632014-06-16 16:55:20 +0000258 }
259
260 DEBUG(dbgs() << "LHS Bounds ==> ";
261 if (LowerBound) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000262 dbgs() << LowerBound->getSExtValue();
Jim Grosbachfff56632014-06-16 16:55:20 +0000263 } else {
264 dbgs() << "NONE";
265 }
266 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
267 dbgs() << "RHS Bounds ==> ";
268 dbgs() << NewLowerBound->getSExtValue() << " - ";
269 if (UpperBound) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000270 dbgs() << UpperBound->getSExtValue() << "\n";
Jim Grosbachfff56632014-06-16 16:55:20 +0000271 } else {
272 dbgs() << "NONE\n";
273 });
274
Chris Lattnered922162003-10-07 18:46:23 +0000275 // Create a new node that checks if the value is < pivot. Go to the
276 // left branch if it is and right branch if not.
277 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000278 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Chris Lattnered922162003-10-07 18:46:23 +0000279
Bob Wilsone4077362013-09-09 19:14:35 +0000280 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000281 Val, Pivot.Low, "Pivot");
Marcello Maggioni78035b12014-07-11 10:34:36 +0000282
283 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
284 NewUpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000285 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000286 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
287 UpperBound, Val, NewNode, OrigBlock,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000288 Default, UnreachableRanges);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000289
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000290 F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000291 NewNode->getInstList().push_back(Comp);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000292
Gabor Greife9ecc682008-04-06 20:25:17 +0000293 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000294 return NewNode;
295}
296
Sanjay Patel815adac2015-09-16 16:21:08 +0000297/// Create a new leaf block for the binary lookup tree. It checks if the
298/// switch's value == the case's value. If not, then it jumps to the default
299/// branch. At this point in the tree, the value can't be another valid case
300/// value, so the jump to the "default" branch is warranted.
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000301BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnered922162003-10-07 18:46:23 +0000302 BasicBlock* OrigBlock,
303 BasicBlock* Default)
304{
305 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000306 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000307 F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000308
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000309 // Emit comparison
Craig Topperf40110f2014-04-25 05:29:35 +0000310 ICmpInst* Comp = nullptr;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000311 if (Leaf.Low == Leaf.High) {
312 // Make the seteq instruction...
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000313 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
314 Leaf.Low, "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000315 } else {
316 // Make range comparison
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000317 if (Leaf.Low->isMinValue(true /*isSigned*/)) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000318 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000319 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
320 "SwitchLeaf");
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000321 } else if (Leaf.Low->isZero()) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000322 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000323 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
324 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000325 } else {
326 // Emit V-Lo <=u Hi-Lo
Owen Anderson487375e2009-07-29 18:55:55 +0000327 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000328 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000329 Val->getName()+".off",
330 NewLeaf);
Owen Anderson487375e2009-07-29 18:55:55 +0000331 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000332 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
333 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000334 }
335 }
Chris Lattnered922162003-10-07 18:46:23 +0000336
337 // Make the conditional branch...
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000338 BasicBlock* Succ = Leaf.BB;
Gabor Greife9ecc682008-04-06 20:25:17 +0000339 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000340
341 // If there were any PHI nodes in this successor, rewrite one entry
342 // from OrigBlock to come from NewLeaf.
Reid Spencer66149462004-09-15 17:06:42 +0000343 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
344 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000345 // Remove all but one incoming entries from the cluster
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000346 uint64_t Range = Leaf.High->getSExtValue() -
347 Leaf.Low->getSExtValue();
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000348 for (uint64_t j = 0; j < Range; ++j) {
349 PN->removeIncomingValue(OrigBlock);
350 }
351
Chris Lattnered922162003-10-07 18:46:23 +0000352 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
353 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
354 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
355 }
356
357 return NewLeaf;
358}
359
Sanjay Patel815adac2015-09-16 16:21:08 +0000360/// Transform simple list of Cases into list of CaseRange's.
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000361unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
Bob Wilsone4077362013-09-09 19:14:35 +0000362 unsigned numCmps = 0;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000363
364 // Start with "simple" cases
Bob Wilsone4077362013-09-09 19:14:35 +0000365 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
366 Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
367 i.getCaseSuccessor()));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000368
Bob Wilsone4077362013-09-09 19:14:35 +0000369 std::sort(Cases.begin(), Cases.end(), CaseCmp());
370
371 // Merge case into clusters
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000372 if (Cases.size() >= 2) {
373 CaseItr I = Cases.begin();
374 for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000375 int64_t nextValue = J->Low->getSExtValue();
376 int64_t currentValue = I->High->getSExtValue();
Bob Wilsone4077362013-09-09 19:14:35 +0000377 BasicBlock* nextBB = J->BB;
378 BasicBlock* currentBB = I->BB;
379
380 // If the two neighboring cases go to the same destination, merge them
381 // into a single case.
Justin Bognere46d3792015-06-20 00:28:25 +0000382 assert(nextValue > currentValue && "Cases should be strictly ascending");
383 if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
Bob Wilsone4077362013-09-09 19:14:35 +0000384 I->High = J->High;
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000385 // FIXME: Combine branch weights.
386 } else if (++I != J) {
387 *I = *J;
Bob Wilsone4077362013-09-09 19:14:35 +0000388 }
389 }
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000390 Cases.erase(std::next(I), Cases.end());
391 }
Bob Wilsone4077362013-09-09 19:14:35 +0000392
393 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
394 if (I->Low != I->High)
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000395 // A range counts double, since it requires two compares.
396 ++numCmps;
397 }
398
Bob Wilsone4077362013-09-09 19:14:35 +0000399 return numCmps;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000400}
401
Sanjay Patel815adac2015-09-16 16:21:08 +0000402/// Replace the specified switch instruction with a sequence of chained if-then
403/// insts in a balanced binary search.
Chen Li0786bc92015-08-11 20:16:17 +0000404void LowerSwitch::processSwitchInst(SwitchInst *SI,
405 SmallPtrSetImpl<BasicBlock*> &DeleteList) {
Chris Lattner1b094a02003-04-23 16:23:59 +0000406 BasicBlock *CurBlock = SI->getParent();
407 BasicBlock *OrigBlock = CurBlock;
408 Function *F = CurBlock->getParent();
Eli Friedman95031ed2011-09-29 20:21:17 +0000409 Value *Val = SI->getCondition(); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000410 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000411
Hans Wennborgae9c9712015-01-23 20:43:51 +0000412 // If there is only the default destination, just branch.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000413 if (!SI->getNumCases()) {
Hans Wennborgae9c9712015-01-23 20:43:51 +0000414 BranchInst::Create(Default, CurBlock);
415 SI->eraseFromParent();
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000416 return;
417 }
418
Hans Wennborgae9c9712015-01-23 20:43:51 +0000419 // Prepare cases vector.
420 CaseVector Cases;
421 unsigned numCmps = Clusterify(Cases, SI);
422 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
423 << ". Total compares: " << numCmps << "\n");
424 DEBUG(dbgs() << "Cases: " << Cases << "\n");
425 (void)numCmps;
426
427 ConstantInt *LowerBound = nullptr;
428 ConstantInt *UpperBound = nullptr;
429 std::vector<IntRange> UnreachableRanges;
430
431 if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000432 // Make the bounds tightly fitted around the case value range, because we
Hans Wennborgae9c9712015-01-23 20:43:51 +0000433 // know that the value passed to the switch must be exactly one of the case
434 // values.
435 assert(!Cases.empty());
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000436 LowerBound = Cases.front().Low;
437 UpperBound = Cases.back().High;
Hans Wennborgae9c9712015-01-23 20:43:51 +0000438
439 DenseMap<BasicBlock *, unsigned> Popularity;
440 unsigned MaxPop = 0;
441 BasicBlock *PopSucc = nullptr;
442
443 IntRange R = { INT64_MIN, INT64_MAX };
444 UnreachableRanges.push_back(R);
445 for (const auto &I : Cases) {
Hans Wennborg8b4dbdf2015-02-05 16:58:10 +0000446 int64_t Low = I.Low->getSExtValue();
447 int64_t High = I.High->getSExtValue();
Hans Wennborgae9c9712015-01-23 20:43:51 +0000448
449 IntRange &LastRange = UnreachableRanges.back();
450 if (LastRange.Low == Low) {
451 // There is nothing left of the previous range.
452 UnreachableRanges.pop_back();
453 } else {
454 // Terminate the previous range.
455 assert(Low > LastRange.Low);
456 LastRange.High = Low - 1;
457 }
458 if (High != INT64_MAX) {
459 IntRange R = { High + 1, INT64_MAX };
460 UnreachableRanges.push_back(R);
461 }
462
463 // Count popularity.
464 int64_t N = High - Low + 1;
465 unsigned &Pop = Popularity[I.BB];
466 if ((Pop += N) > MaxPop) {
467 MaxPop = Pop;
468 PopSucc = I.BB;
469 }
470 }
471#ifndef NDEBUG
472 /* UnreachableRanges should be sorted and the ranges non-adjacent. */
473 for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
474 I != E; ++I) {
475 assert(I->Low <= I->High);
476 auto Next = I + 1;
477 if (Next != E) {
478 assert(Next->Low > I->High);
479 }
480 }
481#endif
482
483 // Use the most popular block as the new default, reducing the number of
484 // cases.
485 assert(MaxPop > 0 && PopSucc);
486 Default = PopSucc;
Benjamin Kramer00a477f2015-06-20 15:59:34 +0000487 Cases.erase(std::remove_if(
488 Cases.begin(), Cases.end(),
489 [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }),
490 Cases.end());
Hans Wennborgae9c9712015-01-23 20:43:51 +0000491
492 // If there are no cases left, just branch.
493 if (Cases.empty()) {
494 BranchInst::Create(Default, CurBlock);
495 SI->eraseFromParent();
496 return;
497 }
498 }
499
Chris Lattnered922162003-10-07 18:46:23 +0000500 // Create a new, empty default block so that the new hierarchy of
501 // if-then statements go to this and the PHI nodes are happy.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000502 BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
Duncan P. N. Exon Smith5b4c8372015-10-13 02:39:05 +0000503 F->getBasicBlockList().insert(Default->getIterator(), NewDefault);
Hans Wennborgae9c9712015-01-23 20:43:51 +0000504 BranchInst::Create(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000505
Chris Lattnered922162003-10-07 18:46:23 +0000506 // If there is an entry in any PHI nodes for the default edge, make sure
507 // to update them as well.
Reid Spencer66149462004-09-15 17:06:42 +0000508 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
509 PHINode *PN = cast<PHINode>(I);
Chris Lattnered922162003-10-07 18:46:23 +0000510 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
511 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
512 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000513 }
514
Jim Grosbachfff56632014-06-16 16:55:20 +0000515 BasicBlock *SwitchBlock =
516 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
Hans Wennborgae9c9712015-01-23 20:43:51 +0000517 OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
Chris Lattnered922162003-10-07 18:46:23 +0000518
519 // Branch to our shiny new if-then stuff...
Gabor Greife9ecc682008-04-06 20:25:17 +0000520 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnered922162003-10-07 18:46:23 +0000521
Chris Lattner1b094a02003-04-23 16:23:59 +0000522 // We are now done with the switch instruction, delete it.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000523 BasicBlock *OldDefault = SI->getDefaultDest();
Chris Lattnerb6865952004-03-14 04:14:31 +0000524 CurBlock->getInstList().erase(SI);
Jim Grosbachfff56632014-06-16 16:55:20 +0000525
Chen Li10f01bd2015-08-11 18:12:26 +0000526 // If the Default block has no more predecessors just add it to DeleteList.
Hans Wennborgae9c9712015-01-23 20:43:51 +0000527 if (pred_begin(OldDefault) == pred_end(OldDefault))
Chen Li0786bc92015-08-11 20:16:17 +0000528 DeleteList.insert(OldDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000529}