blob: e25956299c651ad40697b6aa9034811bbb67c0ff [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
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000134// \brief Update the first occurrence of the "switch statement" BB in the PHI
135// node with the "new" BB. The other occurrences will:
136//
137// 1) Be updated by subsequent calls to this function. Switch statements may
138// have more than one outcoming edge into the same BB if they all have the same
139// value. When the switch statement is converted these incoming edges are now
140// coming from multiple BBs.
141// 2) Removed if subsequent incoming values now share the same case, i.e.,
142// multiple outcome edges are condensed into one. This is necessary to keep the
143// number of phi values equal to the number of branches to SuccBB.
144static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
145 unsigned NumMergedCases) {
146 for (BasicBlock::iterator I = SuccBB->begin(), IE = SuccBB->getFirstNonPHI();
147 I != IE; ++I) {
Marcello Maggioni78035b12014-07-11 10:34:36 +0000148 PHINode *PN = cast<PHINode>(I);
149
Juergen Ributzkad4417252014-11-10 21:05:27 +0000150 // Only update the first occurence.
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000151 unsigned Idx = 0, E = PN->getNumIncomingValues();
152 for (; Idx != E; ++Idx) {
Juergen Ributzkad4417252014-11-10 21:05:27 +0000153 if (PN->getIncomingBlock(Idx) == OrigBB) {
154 PN->setIncomingBlock(Idx, NewBB);
155 break;
156 }
Marcello Maggioni78035b12014-07-11 10:34:36 +0000157 }
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000158
159 // Remove additional occurences coming from condensed cases and keep the
160 // number of incoming values equal to the number of branches to SuccBB.
161 for (++Idx; NumMergedCases > 0 && Idx != E; ++Idx)
162 if (PN->getIncomingBlock(Idx) == OrigBB) {
163 PN->removeIncomingValue(Idx);
164 NumMergedCases--;
165 }
Marcello Maggioni78035b12014-07-11 10:34:36 +0000166 }
167}
168
Chris Lattnered922162003-10-07 18:46:23 +0000169// switchConvert - Convert the switch statement into a binary lookup of
170// the case values. The function recursively builds this tree.
Jim Grosbachfff56632014-06-16 16:55:20 +0000171// LowerBound and UpperBound are used to keep track of the bounds for Val
172// that have already been checked by a block emitted by one of the previous
173// calls to switchConvert in the call stack.
174BasicBlock *LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
175 ConstantInt *LowerBound,
176 ConstantInt *UpperBound, Value *Val,
Marcello Maggioni78035b12014-07-11 10:34:36 +0000177 BasicBlock *Predecessor,
Jim Grosbachfff56632014-06-16 16:55:20 +0000178 BasicBlock *OrigBlock,
179 BasicBlock *Default) {
Chris Lattnered922162003-10-07 18:46:23 +0000180 unsigned Size = End - Begin;
181
Jim Grosbachfff56632014-06-16 16:55:20 +0000182 if (Size == 1) {
183 // Check if the Case Range is perfectly squeezed in between
184 // already checked Upper and Lower bounds. If it is then we can avoid
185 // emitting the code that checks if the value actually falls in the range
186 // because the bounds already tell us so.
187 if (Begin->Low == LowerBound && Begin->High == UpperBound) {
Bruno Cardoso Lopesbc7ba2c2014-11-28 19:47:33 +0000188 unsigned NumMergedCases = 0;
189 if (LowerBound && UpperBound)
190 NumMergedCases =
191 UpperBound->getSExtValue() - LowerBound->getSExtValue();
192 fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
Jim Grosbachfff56632014-06-16 16:55:20 +0000193 return Begin->BB;
194 }
Chris Lattnered922162003-10-07 18:46:23 +0000195 return newLeafBlock(*Begin, Val, OrigBlock, Default);
Jim Grosbachfff56632014-06-16 16:55:20 +0000196 }
Chris Lattnered922162003-10-07 18:46:23 +0000197
198 unsigned Mid = Size / 2;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000199 std::vector<CaseRange> LHS(Begin, Begin + Mid);
David Greene50c54232010-01-05 01:26:45 +0000200 DEBUG(dbgs() << "LHS: " << LHS << "\n");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000201 std::vector<CaseRange> RHS(Begin + Mid, End);
David Greene50c54232010-01-05 01:26:45 +0000202 DEBUG(dbgs() << "RHS: " << RHS << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000203
Jim Grosbachfff56632014-06-16 16:55:20 +0000204 CaseRange &Pivot = *(Begin + Mid);
205 DEBUG(dbgs() << "Pivot ==> "
206 << cast<ConstantInt>(Pivot.Low)->getValue()
207 << " -" << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
Chris Lattnered922162003-10-07 18:46:23 +0000208
Jim Grosbachfff56632014-06-16 16:55:20 +0000209 // NewLowerBound here should never be the integer minimal value.
210 // This is because it is computed from a case range that is never
211 // the smallest, so there is always a case range that has at least
212 // a smaller value.
213 ConstantInt *NewLowerBound = cast<ConstantInt>(Pivot.Low);
214 ConstantInt *NewUpperBound;
215
216 // If we don't have a Default block then it means that we can never
217 // have a value outside of a case range, so set the UpperBound to the highest
218 // value in the LHS part of the case ranges.
219 if (Default != nullptr) {
220 // Because NewLowerBound is never the smallest representable integer
221 // it is safe here to subtract one.
222 NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
223 NewLowerBound->getValue() - 1);
224 } else {
225 CaseItr LastLHS = LHS.begin() + LHS.size() - 1;
226 NewUpperBound = cast<ConstantInt>(LastLHS->High);
227 }
228
229 DEBUG(dbgs() << "LHS Bounds ==> ";
230 if (LowerBound) {
231 dbgs() << cast<ConstantInt>(LowerBound)->getSExtValue();
232 } else {
233 dbgs() << "NONE";
234 }
235 dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
236 dbgs() << "RHS Bounds ==> ";
237 dbgs() << NewLowerBound->getSExtValue() << " - ";
238 if (UpperBound) {
239 dbgs() << cast<ConstantInt>(UpperBound)->getSExtValue() << "\n";
240 } else {
241 dbgs() << "NONE\n";
242 });
243
Chris Lattnered922162003-10-07 18:46:23 +0000244 // Create a new node that checks if the value is < pivot. Go to the
245 // left branch if it is and right branch if not.
246 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000247 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Chris Lattnered922162003-10-07 18:46:23 +0000248
Bob Wilsone4077362013-09-09 19:14:35 +0000249 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000250 Val, Pivot.Low, "Pivot");
Marcello Maggioni78035b12014-07-11 10:34:36 +0000251
252 BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
253 NewUpperBound, Val, NewNode, OrigBlock,
254 Default);
255 BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
256 UpperBound, Val, NewNode, OrigBlock,
257 Default);
258
259 Function::iterator FI = OrigBlock;
260 F->getBasicBlockList().insert(++FI, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000261 NewNode->getInstList().push_back(Comp);
Marcello Maggioni78035b12014-07-11 10:34:36 +0000262
Gabor Greife9ecc682008-04-06 20:25:17 +0000263 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +0000264 return NewNode;
265}
266
267// newLeafBlock - Create a new leaf block for the binary lookup tree. It
268// checks if the switch's value == the case's value. If not, then it
269// jumps to the default branch. At this point in the tree, the value
270// can't be another valid case value, so the jump to the "default" branch
271// is warranted.
272//
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000273BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnered922162003-10-07 18:46:23 +0000274 BasicBlock* OrigBlock,
275 BasicBlock* Default)
276{
277 Function* F = OrigBlock->getParent();
Owen Anderson55f1c092009-08-13 21:58:54 +0000278 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Chris Lattner233f97a2007-04-17 18:09:47 +0000279 Function::iterator FI = OrigBlock;
280 F->getBasicBlockList().insert(++FI, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000281
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000282 // Emit comparison
Craig Topperf40110f2014-04-25 05:29:35 +0000283 ICmpInst* Comp = nullptr;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000284 if (Leaf.Low == Leaf.High) {
285 // Make the seteq instruction...
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000286 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
287 Leaf.Low, "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000288 } else {
289 // Make range comparison
290 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
291 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000292 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
293 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000294 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
295 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000296 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
297 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000298 } else {
299 // Emit V-Lo <=u Hi-Lo
Owen Anderson487375e2009-07-29 18:55:55 +0000300 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greife1f6e4b2008-05-16 19:29:10 +0000301 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000302 Val->getName()+".off",
303 NewLeaf);
Owen Anderson487375e2009-07-29 18:55:55 +0000304 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000305 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
306 "SwitchLeaf");
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000307 }
308 }
Chris Lattnered922162003-10-07 18:46:23 +0000309
310 // Make the conditional branch...
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000311 BasicBlock* Succ = Leaf.BB;
Gabor Greife9ecc682008-04-06 20:25:17 +0000312 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000313
314 // If there were any PHI nodes in this successor, rewrite one entry
315 // from OrigBlock to come from NewLeaf.
Reid Spencer66149462004-09-15 17:06:42 +0000316 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
317 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000318 // Remove all but one incoming entries from the cluster
319 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
320 cast<ConstantInt>(Leaf.Low)->getSExtValue();
321 for (uint64_t j = 0; j < Range; ++j) {
322 PN->removeIncomingValue(OrigBlock);
323 }
324
Chris Lattnered922162003-10-07 18:46:23 +0000325 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
326 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
327 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
328 }
329
330 return NewLeaf;
331}
332
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000333// Clusterify - Transform simple list of Cases into list of CaseRange's
334unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
Bob Wilsone4077362013-09-09 19:14:35 +0000335 unsigned numCmps = 0;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000336
337 // Start with "simple" cases
Bob Wilsone4077362013-09-09 19:14:35 +0000338 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
339 Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
340 i.getCaseSuccessor()));
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +0000341
Bob Wilsone4077362013-09-09 19:14:35 +0000342 std::sort(Cases.begin(), Cases.end(), CaseCmp());
343
344 // Merge case into clusters
345 if (Cases.size()>=2)
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000346 for (CaseItr I = Cases.begin(), J = std::next(Cases.begin());
347 J != Cases.end();) {
Bob Wilsone4077362013-09-09 19:14:35 +0000348 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
349 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
350 BasicBlock* nextBB = J->BB;
351 BasicBlock* currentBB = I->BB;
352
353 // If the two neighboring cases go to the same destination, merge them
354 // into a single case.
355 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
356 I->High = J->High;
357 J = Cases.erase(J);
358 } else {
359 I = J++;
360 }
361 }
362
363 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
364 if (I->Low != I->High)
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000365 // A range counts double, since it requires two compares.
366 ++numCmps;
367 }
368
Bob Wilsone4077362013-09-09 19:14:35 +0000369 return numCmps;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000370}
371
Chris Lattner1b094a02003-04-23 16:23:59 +0000372// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnered922162003-10-07 18:46:23 +0000373// of chained if-then insts in a balanced binary search.
Chris Lattner1b094a02003-04-23 16:23:59 +0000374//
375void LowerSwitch::processSwitchInst(SwitchInst *SI) {
376 BasicBlock *CurBlock = SI->getParent();
377 BasicBlock *OrigBlock = CurBlock;
378 Function *F = CurBlock->getParent();
Eli Friedman95031ed2011-09-29 20:21:17 +0000379 Value *Val = SI->getCondition(); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000380 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000381
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000382 // If there is only the default destination, don't bother with the code below.
Stepan Dyatkovskiy513aaa52012-02-01 07:49:51 +0000383 if (!SI->getNumCases()) {
Gabor Greife9ecc682008-04-06 20:25:17 +0000384 BranchInst::Create(SI->getDefaultDest(), CurBlock);
Chris Lattnerb6865952004-03-14 04:14:31 +0000385 CurBlock->getInstList().erase(SI);
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000386 return;
387 }
388
Jim Grosbachfff56632014-06-16 16:55:20 +0000389 const bool DefaultIsUnreachable =
390 Default->size() == 1 && isa<UnreachableInst>(Default->getTerminator());
Chris Lattnered922162003-10-07 18:46:23 +0000391 // Create a new, empty default block so that the new hierarchy of
392 // if-then statements go to this and the PHI nodes are happy.
Jim Grosbachfff56632014-06-16 16:55:20 +0000393 // if the default block is set as an unreachable we avoid creating one
394 // because will never be a valid target.
395 BasicBlock *NewDefault = nullptr;
396 if (!DefaultIsUnreachable) {
397 NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
398 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000399
Jim Grosbachfff56632014-06-16 16:55:20 +0000400 BranchInst::Create(Default, NewDefault);
401 }
Chris Lattnered922162003-10-07 18:46:23 +0000402 // If there is an entry in any PHI nodes for the default edge, make sure
403 // to update them as well.
Reid Spencer66149462004-09-15 17:06:42 +0000404 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
405 PHINode *PN = cast<PHINode>(I);
Chris Lattnered922162003-10-07 18:46:23 +0000406 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
407 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
408 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000409 }
410
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000411 // Prepare cases vector.
412 CaseVector Cases;
413 unsigned numCmps = Clusterify(Cases, SI);
Chris Lattnered922162003-10-07 18:46:23 +0000414
David Greene50c54232010-01-05 01:26:45 +0000415 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Dan Gohman29f2baf2009-07-25 01:13:51 +0000416 << ". Total compares: " << numCmps << "\n");
David Greene50c54232010-01-05 01:26:45 +0000417 DEBUG(dbgs() << "Cases: " << Cases << "\n");
Mike Stumpd934cc02009-07-27 23:14:11 +0000418 (void)numCmps;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000419
Jim Grosbachfff56632014-06-16 16:55:20 +0000420 ConstantInt *UpperBound = nullptr;
421 ConstantInt *LowerBound = nullptr;
422
423 // Optimize the condition where Default is an unreachable block. In this case
424 // we can make the bounds tightly fitted around the case value ranges,
425 // because we know that the value passed to the switch should always be
426 // exactly one of the case values.
427 if (DefaultIsUnreachable) {
428 CaseItr LastCase = Cases.begin() + Cases.size() - 1;
429 UpperBound = cast<ConstantInt>(LastCase->High);
430 LowerBound = cast<ConstantInt>(Cases.begin()->Low);
431 }
432 BasicBlock *SwitchBlock =
433 switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
Marcello Maggioni78035b12014-07-11 10:34:36 +0000434 OrigBlock, OrigBlock, NewDefault);
Chris Lattnered922162003-10-07 18:46:23 +0000435
436 // Branch to our shiny new if-then stuff...
Gabor Greife9ecc682008-04-06 20:25:17 +0000437 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnered922162003-10-07 18:46:23 +0000438
Chris Lattner1b094a02003-04-23 16:23:59 +0000439 // We are now done with the switch instruction, delete it.
Chris Lattnerb6865952004-03-14 04:14:31 +0000440 CurBlock->getInstList().erase(SI);
Jim Grosbachfff56632014-06-16 16:55:20 +0000441
442 pred_iterator PI = pred_begin(Default), E = pred_end(Default);
443 // If the Default block has no more predecessors just remove it
444 if (PI == E) {
445 DeleteDeadBlock(Default);
446 }
Chris Lattner1b094a02003-04-23 16:23:59 +0000447}