blob: 468a5fe4c5e5dc709083bceec5088fb6d15c2e9e [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
32 /// instructions. Note that this cannot be a BasicBlock pass because it
33 /// modifies the CFG!
Nick Lewycky492d06e2009-10-25 06:33:48 +000034 class LowerSwitch : public FunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035 public:
36 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000037 LowerSwitch() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038
39 virtual bool runOnFunction(Function &F);
40
41 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
42 // This is a cluster of orthogonal Transforms
43 AU.addPreserved<UnifyFunctionExitNodes>();
44 AU.addPreservedID(PromoteMemoryToRegisterID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000045 AU.addPreservedID(LowerInvokePassID);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046 }
47
48 struct CaseRange {
49 Constant* Low;
50 Constant* High;
51 BasicBlock* BB;
52
53 CaseRange() : Low(0), High(0), BB(0) { }
54 CaseRange(Constant* low, Constant* high, BasicBlock* bb) :
55 Low(low), High(high), BB(bb) { }
56 };
57
58 typedef std::vector<CaseRange> CaseVector;
59 typedef std::vector<CaseRange>::iterator CaseItr;
60 private:
61 void processSwitchInst(SwitchInst *SI);
62
63 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
64 BasicBlock* OrigBlock, BasicBlock* Default);
65 BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
66 BasicBlock* OrigBlock, BasicBlock* Default);
67 unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
68 };
69
70 /// The comparison function for sorting the switch case values in the vector.
71 /// WARNING: Case ranges should be disjoint!
72 struct CaseCmp {
73 bool operator () (const LowerSwitch::CaseRange& C1,
74 const LowerSwitch::CaseRange& C2) {
75
76 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
77 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
78 return CI1->getValue().slt(CI2->getValue());
79 }
80 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081}
82
Dan Gohman089efff2008-05-13 00:00:25 +000083char LowerSwitch::ID = 0;
84static RegisterPass<LowerSwitch>
85X("lowerswitch", "Lower SwitchInst's to branches");
86
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087// Publically exposed interface to pass...
Dan Gohman66a636e2008-05-13 02:05:11 +000088const PassInfo *const llvm::LowerSwitchID = &X;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089// createLowerSwitchPass - Interface to this file...
90FunctionPass *llvm::createLowerSwitchPass() {
91 return new LowerSwitch();
92}
93
94bool LowerSwitch::runOnFunction(Function &F) {
95 bool Changed = false;
96
97 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
98 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
99
100 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
101 Changed = true;
102 processSwitchInst(SI);
103 }
104 }
105
106 return Changed;
107}
108
109// operator<< - Used for debugging purposes.
110//
Daniel Dunbarf55f61f2009-07-24 10:36:58 +0000111static raw_ostream& operator<<(raw_ostream &O,
Mike Stumpf93a8fb2009-07-28 01:35:34 +0000112 const LowerSwitch::CaseVector &C) ATTRIBUTE_USED;
Mike Stumpf0fbc392009-07-27 23:33:34 +0000113static raw_ostream& operator<<(raw_ostream &O,
Daniel Dunbarf55f61f2009-07-24 10:36:58 +0000114 const LowerSwitch::CaseVector &C) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000115 O << "[";
116
117 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
118 E = C.end(); B != E; ) {
119 O << *B->Low << " -" << *B->High;
120 if (++B != E) O << ", ";
121 }
122
123 return O << "]";
124}
125
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000126// switchConvert - Convert the switch statement into a binary lookup of
127// the case values. The function recursively builds this tree.
128//
129BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
130 Value* Val, BasicBlock* OrigBlock,
131 BasicBlock* Default)
132{
133 unsigned Size = End - Begin;
134
135 if (Size == 1)
136 return newLeafBlock(*Begin, Val, OrigBlock, Default);
137
138 unsigned Mid = Size / 2;
139 std::vector<CaseRange> LHS(Begin, Begin + Mid);
David Greenef8b8ad22010-01-05 01:26:45 +0000140 DEBUG(dbgs() << "LHS: " << LHS << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 std::vector<CaseRange> RHS(Begin + Mid, End);
David Greenef8b8ad22010-01-05 01:26:45 +0000142 DEBUG(dbgs() << "RHS: " << RHS << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143
144 CaseRange& Pivot = *(Begin + Mid);
David Greenef8b8ad22010-01-05 01:26:45 +0000145 DEBUG(dbgs() << "Pivot ==> "
Chris Lattner1fefaac2008-08-23 22:23:09 +0000146 << cast<ConstantInt>(Pivot.Low)->getValue() << " -"
Dan Gohmane7d7b0f2009-03-23 15:57:19 +0000147 << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148
149 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
150 OrigBlock, Default);
151 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
152 OrigBlock, Default);
153
154 // Create a new node that checks if the value is < pivot. Go to the
155 // left branch if it is and right branch if not.
156 Function* F = OrigBlock->getParent();
Owen Anderson35b47072009-08-13 21:58:54 +0000157 BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 Function::iterator FI = OrigBlock;
159 F->getBasicBlockList().insert(++FI, NewNode);
160
Dan Gohmane6803b82009-08-25 23:17:54 +0000161 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
Owen Anderson6601fcd2009-07-09 23:48:35 +0000162 Val, Pivot.Low, "Pivot");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 NewNode->getInstList().push_back(Comp);
Gabor Greifd6da1d02008-04-06 20:25:17 +0000164 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165 return NewNode;
166}
167
168// newLeafBlock - Create a new leaf block for the binary lookup tree. It
169// checks if the switch's value == the case's value. If not, then it
170// jumps to the default branch. At this point in the tree, the value
171// can't be another valid case value, so the jump to the "default" branch
172// is warranted.
173//
174BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
175 BasicBlock* OrigBlock,
176 BasicBlock* Default)
177{
178 Function* F = OrigBlock->getParent();
Owen Anderson35b47072009-08-13 21:58:54 +0000179 BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 Function::iterator FI = OrigBlock;
181 F->getBasicBlockList().insert(++FI, NewLeaf);
182
183 // Emit comparison
184 ICmpInst* Comp = NULL;
185 if (Leaf.Low == Leaf.High) {
186 // Make the seteq instruction...
Owen Anderson6601fcd2009-07-09 23:48:35 +0000187 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
188 Leaf.Low, "SwitchLeaf");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189 } else {
190 // Make range comparison
191 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
192 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson6601fcd2009-07-09 23:48:35 +0000193 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
194 "SwitchLeaf");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
196 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson6601fcd2009-07-09 23:48:35 +0000197 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
198 "SwitchLeaf");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 } else {
200 // Emit V-Lo <=u Hi-Lo
Owen Anderson02b48c32009-07-29 18:55:55 +0000201 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
Gabor Greifa645dd32008-05-16 19:29:10 +0000202 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 Val->getName()+".off",
204 NewLeaf);
Owen Anderson02b48c32009-07-29 18:55:55 +0000205 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
Owen Anderson6601fcd2009-07-09 23:48:35 +0000206 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
207 "SwitchLeaf");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 }
209 }
210
211 // Make the conditional branch...
212 BasicBlock* Succ = Leaf.BB;
Gabor Greifd6da1d02008-04-06 20:25:17 +0000213 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214
215 // If there were any PHI nodes in this successor, rewrite one entry
216 // from OrigBlock to come from NewLeaf.
217 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
218 PHINode* PN = cast<PHINode>(I);
219 // Remove all but one incoming entries from the cluster
220 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
221 cast<ConstantInt>(Leaf.Low)->getSExtValue();
222 for (uint64_t j = 0; j < Range; ++j) {
223 PN->removeIncomingValue(OrigBlock);
224 }
225
226 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
227 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
228 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
229 }
230
231 return NewLeaf;
232}
233
234// Clusterify - Transform simple list of Cases into list of CaseRange's
235unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
236 unsigned numCmps = 0;
237
238 // Start with "simple" cases
239 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
240 Cases.push_back(CaseRange(SI->getSuccessorValue(i),
241 SI->getSuccessorValue(i),
242 SI->getSuccessor(i)));
Dan Gohman68840702007-11-02 22:24:01 +0000243 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244
245 // Merge case into clusters
246 if (Cases.size()>=2)
Chris Lattnerb44b4292009-12-03 00:50:42 +0000247 for (CaseItr I=Cases.begin(), J=llvm::next(Cases.begin()); J!=Cases.end(); ) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
249 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
250 BasicBlock* nextBB = J->BB;
251 BasicBlock* currentBB = I->BB;
252
253 // If the two neighboring cases go to the same destination, merge them
254 // into a single case.
255 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
256 I->High = J->High;
257 J = Cases.erase(J);
258 } else {
259 I = J++;
260 }
261 }
262
263 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
264 if (I->Low != I->High)
265 // A range counts double, since it requires two compares.
266 ++numCmps;
267 }
268
269 return numCmps;
270}
271
272// processSwitchInst - Replace the specified switch instruction with a sequence
273// of chained if-then insts in a balanced binary search.
274//
275void LowerSwitch::processSwitchInst(SwitchInst *SI) {
276 BasicBlock *CurBlock = SI->getParent();
277 BasicBlock *OrigBlock = CurBlock;
278 Function *F = CurBlock->getParent();
279 Value *Val = SI->getOperand(0); // The value we are switching on...
280 BasicBlock* Default = SI->getDefaultDest();
281
282 // If there is only the default destination, don't bother with the code below.
283 if (SI->getNumOperands() == 2) {
Gabor Greifd6da1d02008-04-06 20:25:17 +0000284 BranchInst::Create(SI->getDefaultDest(), CurBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285 CurBlock->getInstList().erase(SI);
286 return;
287 }
288
289 // Create a new, empty default block so that the new hierarchy of
290 // if-then statements go to this and the PHI nodes are happy.
Owen Anderson35b47072009-08-13 21:58:54 +0000291 BasicBlock* NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 F->getBasicBlockList().insert(Default, NewDefault);
293
Gabor Greifd6da1d02008-04-06 20:25:17 +0000294 BranchInst::Create(Default, NewDefault);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295
296 // If there is an entry in any PHI nodes for the default edge, make sure
297 // to update them as well.
298 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
299 PHINode *PN = cast<PHINode>(I);
300 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
301 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
302 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
303 }
304
305 // Prepare cases vector.
306 CaseVector Cases;
307 unsigned numCmps = Clusterify(Cases, SI);
308
David Greenef8b8ad22010-01-05 01:26:45 +0000309 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Dan Gohmand3fdb152009-07-25 01:13:51 +0000310 << ". Total compares: " << numCmps << "\n");
David Greenef8b8ad22010-01-05 01:26:45 +0000311 DEBUG(dbgs() << "Cases: " << Cases << "\n");
Mike Stump011c7ac2009-07-27 23:14:11 +0000312 (void)numCmps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313
314 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
315 OrigBlock, NewDefault);
316
317 // Branch to our shiny new if-then stuff...
Gabor Greifd6da1d02008-04-06 20:25:17 +0000318 BranchInst::Create(SwitchBlock, OrigBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319
320 // We are now done with the switch instruction, delete it.
321 CurBlock->getInstList().erase(SI);
322}