blob: 5530b4700aac60ec65faa1b8f62eee0721b41e10 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
Gordon Henriksen79ed5872007-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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Transforms/Scalar.h"
17#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
18#include "llvm/Constants.h"
19#include "llvm/Function.h"
20#include "llvm/Instructions.h"
Owen Andersona09d2342009-07-05 22:41:43 +000021#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Pass.h"
Dan Gohman0bb8bdc2007-11-02 22:22:02 +000023#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/Support/Compiler.h"
Nick Lewycky5a44ef92009-10-25 06:57:41 +000025#include "llvm/Support/Debug.h"
Chris Lattner1fefaac2008-08-23 22:23:09 +000026#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000027#include <algorithm>
28using namespace llvm;
29
30namespace {
31 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
Chris Lattner1a9e8292010-08-18 02:41:56 +000032 /// instructions.
Nick Lewycky492d06e2009-10-25 06:33:48 +000033 class LowerSwitch : public FunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034 public:
35 static char ID; // Pass identification, replacement for typeid
Owen Anderson75693222010-08-06 18:33:48 +000036 LowerSwitch() : FunctionPass(ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000037
38 virtual bool runOnFunction(Function &F);
39
40 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41 // This is a cluster of orthogonal Transforms
42 AU.addPreserved<UnifyFunctionExitNodes>();
Dan Gohman6b1b2fd2010-08-06 21:48:06 +000043 AU.addPreserved("mem2reg");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044 AU.addPreservedID(LowerInvokePassID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000045 }
46
47 struct CaseRange {
48 Constant* Low;
49 Constant* High;
50 BasicBlock* BB;
51
Chris Lattner1a9e8292010-08-18 02:41:56 +000052 CaseRange(Constant *low = 0, Constant *high = 0, BasicBlock *bb = 0) :
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053 Low(low), High(high), BB(bb) { }
54 };
55
56 typedef std::vector<CaseRange> CaseVector;
57 typedef std::vector<CaseRange>::iterator CaseItr;
58 private:
59 void processSwitchInst(SwitchInst *SI);
60
61 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
62 BasicBlock* OrigBlock, BasicBlock* Default);
63 BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
64 BasicBlock* OrigBlock, BasicBlock* Default);
65 unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
66 };
67
68 /// The comparison function for sorting the switch case values in the vector.
69 /// WARNING: Case ranges should be disjoint!
70 struct CaseCmp {
71 bool operator () (const LowerSwitch::CaseRange& C1,
72 const LowerSwitch::CaseRange& C2) {
73
74 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
75 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
76 return CI1->getValue().slt(CI2->getValue());
77 }
78 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079}
80
Dan Gohman089efff2008-05-13 00:00:25 +000081char LowerSwitch::ID = 0;
Owen Anderson291fe212010-08-23 17:52:01 +000082INITIALIZE_PASS(LowerSwitch, "lowerswitch",
83 "Lower SwitchInst's to branches", false, false);
Dan Gohman089efff2008-05-13 00:00:25 +000084
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085// Publically exposed interface to pass...
Owen Anderson75693222010-08-06 18:33:48 +000086char &llvm::LowerSwitchID = LowerSwitch::ID;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087// createLowerSwitchPass - Interface to this file...
88FunctionPass *llvm::createLowerSwitchPass() {
89 return new LowerSwitch();
90}
91
92bool LowerSwitch::runOnFunction(Function &F) {
93 bool Changed = false;
94
95 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
96 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
97
98 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
99 Changed = true;
100 processSwitchInst(SI);
101 }
102 }
103
104 return Changed;
105}
106
107// operator<< - Used for debugging purposes.
108//
Daniel Dunbarf55f61f2009-07-24 10:36:58 +0000109static raw_ostream& operator<<(raw_ostream &O,
Mike Stumpf93a8fb2009-07-28 01:35:34 +0000110 const LowerSwitch::CaseVector &C) ATTRIBUTE_USED;
Mike Stumpf0fbc392009-07-27 23:33:34 +0000111static raw_ostream& operator<<(raw_ostream &O,
Daniel Dunbarf55f61f2009-07-24 10:36:58 +0000112 const LowerSwitch::CaseVector &C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113 O << "[";
114
115 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
116 E = C.end(); B != E; ) {
117 O << *B->Low << " -" << *B->High;
118 if (++B != E) O << ", ";
119 }
120
121 return O << "]";
122}
123
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000124// switchConvert - Convert the switch statement into a binary lookup of
125// the case values. The function recursively builds this tree.
126//
127BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
128 Value* Val, BasicBlock* OrigBlock,
129 BasicBlock* Default)
130{
131 unsigned Size = End - Begin;
132
133 if (Size == 1)
134 return newLeafBlock(*Begin, Val, OrigBlock, Default);
135
136 unsigned Mid = Size / 2;
137 std::vector<CaseRange> LHS(Begin, Begin + Mid);
David Greenef8b8ad22010-01-05 01:26:45 +0000138 DEBUG(dbgs() << "LHS: " << LHS << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139 std::vector<CaseRange> RHS(Begin + Mid, End);
David Greenef8b8ad22010-01-05 01:26:45 +0000140 DEBUG(dbgs() << "RHS: " << RHS << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141
142 CaseRange& Pivot = *(Begin + Mid);
David Greenef8b8ad22010-01-05 01:26:45 +0000143 DEBUG(dbgs() << "Pivot ==> "
Chris Lattner1fefaac2008-08-23 22:23:09 +0000144 << cast<ConstantInt>(Pivot.Low)->getValue() << " -"
Dan Gohmane7d7b0f2009-03-23 15:57:19 +0000145 << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146
147 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
148 OrigBlock, Default);
149 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
150 OrigBlock, Default);
151
152 // Create a new node that checks if the value is < pivot. Go to the
153 // left branch if it is and right branch if not.
154 Function* F = OrigBlock->getParent();
Owen Anderson35b47072009-08-13 21:58:54 +0000155 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 Function::iterator FI = OrigBlock;
157 F->getBasicBlockList().insert(++FI, NewNode);
158
Dan Gohmane6803b82009-08-25 23:17:54 +0000159 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson6601fcd2009-07-09 23:48:35 +0000160 Val, Pivot.Low, "Pivot");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 NewNode->getInstList().push_back(Comp);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000162 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 return NewNode;
164}
165
166// newLeafBlock - Create a new leaf block for the binary lookup tree. It
167// checks if the switch's value == the case's value. If not, then it
168// jumps to the default branch. At this point in the tree, the value
169// can't be another valid case value, so the jump to the "default" branch
170// is warranted.
171//
172BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
173 BasicBlock* OrigBlock,
174 BasicBlock* Default)
175{
176 Function* F = OrigBlock->getParent();
Owen Anderson35b47072009-08-13 21:58:54 +0000177 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 Function::iterator FI = OrigBlock;
179 F->getBasicBlockList().insert(++FI, NewLeaf);
180
181 // Emit comparison
182 ICmpInst* Comp = NULL;
183 if (Leaf.Low == Leaf.High) {
184 // Make the seteq instruction...
Owen Anderson6601fcd2009-07-09 23:48:35 +0000185 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
186 Leaf.Low, "SwitchLeaf");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 } else {
188 // Make range comparison
189 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
190 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson6601fcd2009-07-09 23:48:35 +0000191 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
192 "SwitchLeaf");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
194 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson6601fcd2009-07-09 23:48:35 +0000195 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
196 "SwitchLeaf");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 } else {
198 // Emit V-Lo <=u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +0000199 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greifa645dd32008-05-16 19:29:10 +0000200 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201 Val->getName()+".off",
202 NewLeaf);
Owen Anderson02b48c32009-07-29 18:55:55 +0000203 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson6601fcd2009-07-09 23:48:35 +0000204 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
205 "SwitchLeaf");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206 }
207 }
208
209 // Make the conditional branch...
210 BasicBlock* Succ = Leaf.BB;
Gabor Greifd6da1d02008-04-06 20:25:17 +0000211 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212
213 // If there were any PHI nodes in this successor, rewrite one entry
214 // from OrigBlock to come from NewLeaf.
215 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
216 PHINode* PN = cast<PHINode>(I);
217 // Remove all but one incoming entries from the cluster
218 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
219 cast<ConstantInt>(Leaf.Low)->getSExtValue();
220 for (uint64_t j = 0; j < Range; ++j) {
221 PN->removeIncomingValue(OrigBlock);
222 }
223
224 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
225 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
226 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
227 }
228
229 return NewLeaf;
230}
231
232// Clusterify - Transform simple list of Cases into list of CaseRange's
233unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
234 unsigned numCmps = 0;
235
236 // Start with "simple" cases
237 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
238 Cases.push_back(CaseRange(SI->getSuccessorValue(i),
239 SI->getSuccessorValue(i),
240 SI->getSuccessor(i)));
Dan Gohman68840702007-11-02 22:24:01 +0000241 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242
243 // Merge case into clusters
244 if (Cases.size()>=2)
Chris Lattnerb44b4292009-12-03 00:50:42 +0000245 for (CaseItr I=Cases.begin(), J=llvm::next(Cases.begin()); J!=Cases.end(); ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
247 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
248 BasicBlock* nextBB = J->BB;
249 BasicBlock* currentBB = I->BB;
250
251 // If the two neighboring cases go to the same destination, merge them
252 // into a single case.
253 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
254 I->High = J->High;
255 J = Cases.erase(J);
256 } else {
257 I = J++;
258 }
259 }
260
261 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
262 if (I->Low != I->High)
263 // A range counts double, since it requires two compares.
264 ++numCmps;
265 }
266
267 return numCmps;
268}
269
270// processSwitchInst - Replace the specified switch instruction with a sequence
271// of chained if-then insts in a balanced binary search.
272//
273void LowerSwitch::processSwitchInst(SwitchInst *SI) {
274 BasicBlock *CurBlock = SI->getParent();
275 BasicBlock *OrigBlock = CurBlock;
276 Function *F = CurBlock->getParent();
277 Value *Val = SI->getOperand(0); // The value we are switching on...
278 BasicBlock* Default = SI->getDefaultDest();
279
280 // If there is only the default destination, don't bother with the code below.
281 if (SI->getNumOperands() == 2) {
Gabor Greifd6da1d02008-04-06 20:25:17 +0000282 BranchInst::Create(SI->getDefaultDest(), CurBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 CurBlock->getInstList().erase(SI);
284 return;
285 }
286
287 // Create a new, empty default block so that the new hierarchy of
288 // if-then statements go to this and the PHI nodes are happy.
Owen Anderson35b47072009-08-13 21:58:54 +0000289 BasicBlock* NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 F->getBasicBlockList().insert(Default, NewDefault);
291
Gabor Greifd6da1d02008-04-06 20:25:17 +0000292 BranchInst::Create(Default, NewDefault);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293
294 // If there is an entry in any PHI nodes for the default edge, make sure
295 // to update them as well.
296 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
297 PHINode *PN = cast<PHINode>(I);
298 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
299 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
300 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
301 }
302
303 // Prepare cases vector.
304 CaseVector Cases;
305 unsigned numCmps = Clusterify(Cases, SI);
306
David Greenef8b8ad22010-01-05 01:26:45 +0000307 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Dan Gohmand3fdb152009-07-25 01:13:51 +0000308 << ". Total compares: " << numCmps << "\n");
David Greenef8b8ad22010-01-05 01:26:45 +0000309 DEBUG(dbgs() << "Cases: " << Cases << "\n");
Mike Stump011c7ac2009-07-27 23:14:11 +0000310 (void)numCmps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311
312 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
313 OrigBlock, NewDefault);
314
315 // Branch to our shiny new if-then stuff...
Gabor Greifd6da1d02008-04-06 20:25:17 +0000316 BranchInst::Create(SwitchBlock, OrigBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317
318 // We are now done with the switch instruction, delete it.
319 CurBlock->getInstList().erase(SI);
320}