blob: a0105c23d75a0ac19bab1941d8e5a185eb001ac7 [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"
Jim Grosbachfff56632014-06-16 16:55:20 +000017#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/STLExtras.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"
Jim Grosbachfff56632014-06-16 16:55:20 +000023#include "llvm/IR/CFG.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000024#include "llvm/Pass.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000025#include "llvm/Support/Compiler.h"
Nick Lewycky974e12b2009-10-25 06:57:41 +000026#include "llvm/Support/Debug.h"
Chris Lattner0c19df42008-08-23 22:23:09 +000027#include "llvm/Support/raw_ostream.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 {
Chris Lattner1b094a02003-04-23 16:23:59 +000035 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
Chris Lattnerb45de952010-08-18 02:41:56 +000036 /// instructions.
Nick Lewycky02d5f772009-10-25 06:33:48 +000037 class LowerSwitch : public FunctionPass {
Chris Lattnered922162003-10-07 18:46:23 +000038 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +000039 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000040 LowerSwitch() : FunctionPass(ID) {
41 initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
42 }
Devang Patel09f162c2007-05-01 21:15:47 +000043
Craig Topper3e4c6972014-03-05 09:10:37 +000044 bool runOnFunction(Function &F) override;
45
46 void getAnalysisUsage(AnalysisUsage &AU) const override {
Anton Korobeynikovfb801512007-04-16 18:10:23 +000047 // This is a cluster of orthogonal Transforms
Chris Lattner4fe87d62006-05-09 04:13:41 +000048 AU.addPreserved<UnifyFunctionExitNodes>();
Dan Gohman0f7892b2010-08-06 21:48:06 +000049 AU.addPreserved("mem2reg");
Chris Lattnere4cb4762006-05-17 21:05:27 +000050 AU.addPreservedID(LowerInvokePassID);
Chris Lattner4fe87d62006-05-09 04:13:41 +000051 }
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000052
53 struct CaseRange {
54 Constant* Low;
55 Constant* High;
56 BasicBlock* BB;
57
Craig Topperf40110f2014-04-25 05:29:35 +000058 CaseRange(Constant *low = nullptr, Constant *high = nullptr,
59 BasicBlock *bb = nullptr) :
Jeff Cohen00227412007-03-12 17:56:27 +000060 Low(low), High(high), BB(bb) { }
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000061 };
62
Jim Grosbachfff56632014-06-16 16:55:20 +000063 typedef std::vector<CaseRange> CaseVector;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000064 typedef std::vector<CaseRange>::iterator CaseItr;
Chris Lattnered922162003-10-07 18:46:23 +000065 private:
Chris Lattner1b094a02003-04-23 16:23:59 +000066 void processSwitchInst(SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000067
Jim Grosbachfff56632014-06-16 16:55:20 +000068 BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
69 ConstantInt *LowerBound, ConstantInt *UpperBound,
Marcello Maggioni78035b12014-07-11 10:34:36 +000070 Value *Val, BasicBlock *Predecessor,
71 BasicBlock *OrigBlock, BasicBlock *Default);
Jim Grosbachfff56632014-06-16 16:55:20 +000072 BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
73 BasicBlock *Default);
74 unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000075 };
Bob Wilsone4077362013-09-09 19:14:35 +000076
77 /// The comparison function for sorting the switch case values in the vector.
78 /// WARNING: Case ranges should be disjoint!
79 struct CaseCmp {
80 bool operator () (const LowerSwitch::CaseRange& C1,
81 const LowerSwitch::CaseRange& C2) {
82
83 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
84 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
85 return CI1->getValue().slt(CI2->getValue());
86 }
87 };
Chris Lattner1b094a02003-04-23 16:23:59 +000088}
89
Dan Gohmand78c4002008-05-13 00:00:25 +000090char LowerSwitch::ID = 0;
Owen Andersond31d82d2010-08-23 17:52:01 +000091INITIALIZE_PASS(LowerSwitch, "lowerswitch",
Owen Andersondf7a4f22010-10-07 22:25:06 +000092 "Lower SwitchInst's to branches", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +000093
Chris Lattner0ab5e2c2011-04-15 05:18:47 +000094// Publicly exposed interface to pass...
Owen Andersona7aed182010-08-06 18:33:48 +000095char &llvm::LowerSwitchID = LowerSwitch::ID;
Chris Lattner1b094a02003-04-23 16:23:59 +000096// createLowerSwitchPass - Interface to this file...
Chris Lattner49525f82004-01-09 06:02:20 +000097FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner1b094a02003-04-23 16:23:59 +000098 return new LowerSwitch();
99}
100
101bool LowerSwitch::runOnFunction(Function &F) {
102 bool Changed = false;
103
104 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
105 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
106
107 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
108 Changed = true;
109 processSwitchInst(SI);
110 }
111 }
112
113 return Changed;
114}
115
Chris Lattnered922162003-10-07 18:46:23 +0000116// operator<< - Used for debugging purposes.
117//
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000118static raw_ostream& operator<<(raw_ostream &O,
Chandler Carruth88c54b82010-10-23 08:10:43 +0000119 const LowerSwitch::CaseVector &C)
120 LLVM_ATTRIBUTE_USED;
Mike Stump47987632009-07-27 23:33:34 +0000121static raw_ostream& operator<<(raw_ostream &O,
Daniel Dunbar796e43e2009-07-24 10:36:58 +0000122 const LowerSwitch::CaseVector &C) {
Chris Lattnered922162003-10-07 18:46:23 +0000123 O << "[";
124
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000125 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
Chris Lattner49525f82004-01-09 06:02:20 +0000126 E = C.end(); B != E; ) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000127 O << *B->Low << " -" << *B->High;
Chris Lattnered922162003-10-07 18:46:23 +0000128 if (++B != E) O << ", ";
129 }
130
131 return O << "]";
132}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000133
Juergen Ributzkad4417252014-11-10 21:05:27 +0000134/// \brief Update the first occurrence of the "switch statement" BB in the PHI
135/// node with the "new" BB. The other occurrences will be updated by subsequent
136/// calls to this function.
137///
138/// Switch statements may have more than one incoming edge into the same BB if
139/// they all have the same value. When the switch statement is converted these
140/// incoming edges are now coming from multiple BBs.
141static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB) {
142 for (BasicBlock::iterator I = SuccBB->begin(), E = SuccBB->getFirstNonPHI();
Marcello Maggioni78035b12014-07-11 10:34:36 +0000143 I != E; ++I) {
144 PHINode *PN = cast<PHINode>(I);
145
Juergen Ributzkad4417252014-11-10 21:05:27 +0000146 // Only update the first occurence.
147 for (unsigned Idx = 0, E = PN->getNumIncomingValues(); Idx != E; ++Idx) {
148 if (PN->getIncomingBlock(Idx) == OrigBB) {
149 PN->setIncomingBlock(Idx, NewBB);
150 break;
151 }
Marcello Maggioni78035b12014-07-11 10:34:36 +0000152 }
153 }
154}
155
Chris Lattnered922162003-10-07 18:46:23 +0000156// switchConvert - Convert the switch statement into a binary lookup of
157// the case values. The function recursively builds this tree.
Jim Grosbachfff56632014-06-16 16:55:20 +0000158// LowerBound and UpperBound are used to keep track of the bounds for Val
159// that have already been checked by a block emitted by one of the previous
160// calls to switchConvert in the call stack.
161BasicBlock *LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
162 ConstantInt *LowerBound,
163 ConstantInt *UpperBound, Value *Val,
Marcello Maggioni78035b12014-07-11 10:34:36 +0000164 BasicBlock *Predecessor,
Jim Grosbachfff56632014-06-16 16:55:20 +0000165 BasicBlock *OrigBlock,
166 BasicBlock *Default) {
Chris Lattnered922162003-10-07 18:46:23 +0000167 unsigned Size = End - Begin;
168
Jim Grosbachfff56632014-06-16 16:55:20 +0000169 if (Size == 1) {
170 // Check if the Case Range is perfectly squeezed in between
171 // already checked Upper and Lower bounds. If it is then we can avoid
172 // emitting the code that checks if the value actually falls in the range
173 // because the bounds already tell us so.
174 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
Marcello Maggioni78035b12014-07-11 10:34:36 +0000175 fixPhis(Begin->BB, OrigBlock, Predecessor);
Jim Grosbachfff56632014-06-16 16:55:20 +0000176 return Begin->BB;
177 }
Chris Lattnered922162003-10-07 18:46:23 +0000178 return newLeafBlock(*Begin, Val, OrigBlock, Default);
Jim Grosbachfff56632014-06-16 16:55:20 +0000179 }
Chris Lattnered922162003-10-07 18:46:23 +0000180
181 unsigned Mid = Size / 2;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000182 std::vector<CaseRange> LHS(Begin, Begin + Mid);
David Greene50c54232010-01-05 01:26:45 +0000183 DEBUG(dbgs() << "LHS: " << LHS << "\n");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000184 std::vector<CaseRange> RHS(Begin + Mid, End);
David Greene50c54232010-01-05 01:26:45 +0000185 DEBUG(dbgs() << "RHS: " << RHS << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000186
Jim Grosbachfff56632014-06-16 16:55:20 +0000187 CaseRange &Pivot = *(Begin + Mid);
188 DEBUG(dbgs() << "Pivot ==> "
189 << cast<ConstantInt>(Pivot.Low)->getValue()
190 << " -" << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000191
Jim Grosbachfff56632014-06-16 16:55:20 +0000192 // NewLowerBound here should never be the integer minimal value.
193 // This is because it is computed from a case range that is never
194 // the smallest, so there is always a case range that has at least
195 // a smaller value.
196 ConstantInt *NewLowerBound = cast<ConstantInt>(Pivot.Low);
197 ConstantInt *NewUpperBound;
198
199 // If we don't have a Default block then it means that we can never
200 // have a value outside of a case range, so set the UpperBound to the highest
201 // value in the LHS part of the case ranges.
202 if (Default != nullptr) {
203 // Because NewLowerBound is never the smallest representable integer
204 // it is safe here to subtract one.
205 NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
206 NewLowerBound->getValue() - 1);
207 } else {
208 CaseItr LastLHS = LHS.begin() + LHS.size() - 1;
209 NewUpperBound = cast<ConstantInt>(LastLHS->High);
210 }
211
212 DEBUG(dbgs() << "LHS Bounds ==> ";
213 if (LowerBound) {
214 dbgs() << cast<ConstantInt>(LowerBound)->getSExtValue();
215 } else {
216 dbgs() << "NONE";
217 }
218 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
219 dbgs() << "RHS Bounds ==> ";
220 dbgs() << NewLowerBound->getSExtValue() << " - ";
221 if (UpperBound) {
222 dbgs() << cast<ConstantInt>(UpperBound)->getSExtValue() << "\n";
223 } else {
224 dbgs() << "NONE\n";
225 });
226
Chris Lattnered922162003-10-07 18:46:23 +0000227 // Create a new node that checks if the value is < pivot. Go to the
228 // left branch if it is and right branch if not.
229 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000230 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Chris Lattnered922162003-10-07 18:46:23 +0000231
Bob Wilsone4077362013-09-09 19:14:35 +0000232 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000233 Val, Pivot.Low, "Pivot");
Marcello Maggioni78035b12014-07-11 10:34:36 +0000234
235 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
236 NewUpperBound, Val, NewNode, OrigBlock,
237 Default);
238 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
239 UpperBound, Val, NewNode, OrigBlock,
240 Default);
241
242 Function::iterator FI = OrigBlock;
243 F->getBasicBlockList().insert(++FI, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000244 NewNode->getInstList().push_back(Comp);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000245
Gabor Greife9ecc682008-04-06 20:25:17 +0000246 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000247 return NewNode;
248}
249
250// newLeafBlock - Create a new leaf block for the binary lookup tree. It
251// checks if the switch's value == the case's value. If not, then it
252// jumps to the default branch. At this point in the tree, the value
253// can't be another valid case value, so the jump to the "default" branch
254// is warranted.
255//
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000256BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnered922162003-10-07 18:46:23 +0000257 BasicBlock* OrigBlock,
258 BasicBlock* Default)
259{
260 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000261 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Chris Lattner233f97a2007-04-17 18:09:47 +0000262 Function::iterator FI = OrigBlock;
263 F->getBasicBlockList().insert(++FI, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000264
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000265 // Emit comparison
Craig Topperf40110f2014-04-25 05:29:35 +0000266 ICmpInst* Comp = nullptr;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000267 if (Leaf.Low == Leaf.High) {
268 // Make the seteq instruction...
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000269 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
270 Leaf.Low, "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000271 } else {
272 // Make range comparison
273 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
274 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000275 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
276 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000277 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
278 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000279 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
280 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000281 } else {
282 // Emit V-Lo <=u Hi-Lo
Owen Anderson487375e2009-07-29 18:55:55 +0000283 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000284 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000285 Val->getName()+".off",
286 NewLeaf);
Owen Anderson487375e2009-07-29 18:55:55 +0000287 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000288 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
289 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000290 }
291 }
Chris Lattnered922162003-10-07 18:46:23 +0000292
293 // Make the conditional branch...
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000294 BasicBlock* Succ = Leaf.BB;
Gabor Greife9ecc682008-04-06 20:25:17 +0000295 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000296
297 // If there were any PHI nodes in this successor, rewrite one entry
298 // from OrigBlock to come from NewLeaf.
Reid Spencer66149462004-09-15 17:06:42 +0000299 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
300 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000301 // Remove all but one incoming entries from the cluster
302 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
303 cast<ConstantInt>(Leaf.Low)->getSExtValue();
304 for (uint64_t j = 0; j < Range; ++j) {
305 PN->removeIncomingValue(OrigBlock);
306 }
307
Chris Lattnered922162003-10-07 18:46:23 +0000308 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
309 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
310 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
311 }
312
313 return NewLeaf;
314}
315
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000316// Clusterify - Transform simple list of Cases into list of CaseRange's
317unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
Bob Wilsone4077362013-09-09 19:14:35 +0000318 unsigned numCmps = 0;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000319
320 // Start with "simple" cases
Bob Wilsone4077362013-09-09 19:14:35 +0000321 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
322 Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
323 i.getCaseSuccessor()));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000324
Bob Wilsone4077362013-09-09 19:14:35 +0000325 std::sort(Cases.begin(), Cases.end(), CaseCmp());
326
327 // Merge case into clusters
328 if (Cases.size()>=2)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000329 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
330 J != Cases.end();) {
Bob Wilsone4077362013-09-09 19:14:35 +0000331 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
332 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
333 BasicBlock* nextBB = J->BB;
334 BasicBlock* currentBB = I->BB;
335
336 // If the two neighboring cases go to the same destination, merge them
337 // into a single case.
338 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
339 I->High = J->High;
340 J = Cases.erase(J);
341 } else {
342 I = J++;
343 }
344 }
345
346 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
347 if (I->Low != I->High)
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000348 // A range counts double, since it requires two compares.
349 ++numCmps;
350 }
351
Bob Wilsone4077362013-09-09 19:14:35 +0000352 return numCmps;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000353}
354
Chris Lattner1b094a02003-04-23 16:23:59 +0000355// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnered922162003-10-07 18:46:23 +0000356// of chained if-then insts in a balanced binary search.
Chris Lattner1b094a02003-04-23 16:23:59 +0000357//
358void LowerSwitch::processSwitchInst(SwitchInst *SI) {
359 BasicBlock *CurBlock = SI->getParent();
360 BasicBlock *OrigBlock = CurBlock;
361 Function *F = CurBlock->getParent();
Eli Friedman95031ed2011-09-29 20:21:17 +0000362 Value *Val = SI->getCondition(); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000363 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000364
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000365 // If there is only the default destination, don't bother with the code below.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000366 if (!SI->getNumCases()) {
Gabor Greife9ecc682008-04-06 20:25:17 +0000367 BranchInst::Create(SI->getDefaultDest(), CurBlock);
Chris Lattnerb6865952004-03-14 04:14:31 +0000368 CurBlock->getInstList().erase(SI);
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000369 return;
370 }
371
Jim Grosbachfff56632014-06-16 16:55:20 +0000372 const bool DefaultIsUnreachable =
373 Default->size() == 1 && isa<UnreachableInst>(Default->getTerminator());
Chris Lattnered922162003-10-07 18:46:23 +0000374 // Create a new, empty default block so that the new hierarchy of
375 // if-then statements go to this and the PHI nodes are happy.
Jim Grosbachfff56632014-06-16 16:55:20 +0000376 // if the default block is set as an unreachable we avoid creating one
377 // because will never be a valid target.
378 BasicBlock *NewDefault = nullptr;
379 if (!DefaultIsUnreachable) {
380 NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
381 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000382
Jim Grosbachfff56632014-06-16 16:55:20 +0000383 BranchInst::Create(Default, NewDefault);
384 }
Chris Lattnered922162003-10-07 18:46:23 +0000385 // If there is an entry in any PHI nodes for the default edge, make sure
386 // to update them as well.
Reid Spencer66149462004-09-15 17:06:42 +0000387 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
388 PHINode *PN = cast<PHINode>(I);
Chris Lattnered922162003-10-07 18:46:23 +0000389 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
390 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
391 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000392 }
393
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000394 // Prepare cases vector.
395 CaseVector Cases;
396 unsigned numCmps = Clusterify(Cases, SI);
Chris Lattnered922162003-10-07 18:46:23 +0000397
David Greene50c54232010-01-05 01:26:45 +0000398 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Dan Gohman29f2baf2009-07-25 01:13:51 +0000399 << ". Total compares: " << numCmps << "\n");
David Greene50c54232010-01-05 01:26:45 +0000400 DEBUG(dbgs() << "Cases: " << Cases << "\n");
Mike Stumpd934cc02009-07-27 23:14:11 +0000401 (void)numCmps;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000402
Jim Grosbachfff56632014-06-16 16:55:20 +0000403 ConstantInt *UpperBound = nullptr;
404 ConstantInt *LowerBound = nullptr;
405
406 // Optimize the condition where Default is an unreachable block. In this case
407 // we can make the bounds tightly fitted around the case value ranges,
408 // because we know that the value passed to the switch should always be
409 // exactly one of the case values.
410 if (DefaultIsUnreachable) {
411 CaseItr LastCase = Cases.begin() + Cases.size() - 1;
412 UpperBound = cast<ConstantInt>(LastCase->High);
413 LowerBound = cast<ConstantInt>(Cases.begin()->Low);
414 }
415 BasicBlock *SwitchBlock =
416 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
Marcello Maggioni78035b12014-07-11 10:34:36 +0000417 OrigBlock, OrigBlock, NewDefault);
Chris Lattnered922162003-10-07 18:46:23 +0000418
419 // Branch to our shiny new if-then stuff...
Gabor Greife9ecc682008-04-06 20:25:17 +0000420 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnered922162003-10-07 18:46:23 +0000421
Chris Lattner1b094a02003-04-23 16:23:59 +0000422 // We are now done with the switch instruction, delete it.
Chris Lattnerb6865952004-03-14 04:14:31 +0000423 CurBlock->getInstList().erase(SI);
Jim Grosbachfff56632014-06-16 16:55:20 +0000424
425 pred_iterator PI = pred_begin(Default), E = pred_end(Default);
426 // If the Default block has no more predecessors just remove it
427 if (PI == E) {
428 DeleteDeadBlock(Default);
429 }
Chris Lattner1b094a02003-04-23 16:23:59 +0000430}