blob: 4a2dd9a9e07333eb63acb3be6f406701c910ed99 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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//
10// The LowerSwitch transformation rewrites switch statements with a sequence of
11// branches, which allows targets to get away with not implementing the switch
12// statement until it is convenient.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Transforms/Scalar.h"
Chris Lattner4fe87d62006-05-09 04:13:41 +000017#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
Chris Lattnered922162003-10-07 18:46:23 +000018#include "llvm/Constants.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000019#include "llvm/Function.h"
Misha Brukman2b3387a2004-07-29 17:05:13 +000020#include "llvm/Instructions.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000021#include "llvm/Pass.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000022#include "llvm/Support/Debug.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000023#include "llvm/Support/Compiler.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000024#include <algorithm>
Chris Lattner49525f82004-01-09 06:02:20 +000025using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000026
Chris Lattner1b094a02003-04-23 16:23:59 +000027namespace {
Chris Lattner1b094a02003-04-23 16:23:59 +000028 /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
29 /// instructions. Note that this cannot be a BasicBlock pass because it
30 /// modifies the CFG!
Chris Lattner4a4c7fe2006-06-28 22:08:15 +000031 class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
Chris Lattnered922162003-10-07 18:46:23 +000032 public:
Chris Lattner4fe87d62006-05-09 04:13:41 +000033 virtual bool runOnFunction(Function &F);
Chris Lattnere4cb4762006-05-17 21:05:27 +000034
Chris Lattner4fe87d62006-05-09 04:13:41 +000035 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Anton Korobeynikovfb801512007-04-16 18:10:23 +000036 // This is a cluster of orthogonal Transforms
Chris Lattner4fe87d62006-05-09 04:13:41 +000037 AU.addPreserved<UnifyFunctionExitNodes>();
38 AU.addPreservedID(PromoteMemoryToRegisterID);
39 AU.addPreservedID(LowerSelectID);
Chris Lattnere4cb4762006-05-17 21:05:27 +000040 AU.addPreservedID(LowerInvokePassID);
41 AU.addPreservedID(LowerAllocationsID);
Chris Lattner4fe87d62006-05-09 04:13:41 +000042 }
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000043
44 struct CaseRange {
45 Constant* Low;
46 Constant* High;
47 BasicBlock* BB;
48
Jeff Cohen00227412007-03-12 17:56:27 +000049 CaseRange() : Low(0), High(0), BB(0) { }
50 CaseRange(Constant* low, Constant* high, BasicBlock* bb) :
51 Low(low), High(high), BB(bb) { }
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000052 };
53
54 typedef std::vector<CaseRange> CaseVector;
55 typedef std::vector<CaseRange>::iterator CaseItr;
Chris Lattnered922162003-10-07 18:46:23 +000056 private:
Chris Lattner1b094a02003-04-23 16:23:59 +000057 void processSwitchInst(SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000058
59 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
60 BasicBlock* OrigBlock, BasicBlock* Default);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000061 BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnered922162003-10-07 18:46:23 +000062 BasicBlock* OrigBlock, BasicBlock* Default);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000063 unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000064 };
65
66 /// The comparison function for sorting the switch case values in the vector.
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000067 /// WARNING: Case ranges should be disjoint!
Chris Lattnered922162003-10-07 18:46:23 +000068 struct CaseCmp {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000069 bool operator () (const LowerSwitch::CaseRange& C1,
70 const LowerSwitch::CaseRange& C2) {
Chris Lattnered922162003-10-07 18:46:23 +000071
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +000072 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
73 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
74 return CI1->getValue().slt(CI2->getValue());
Chris Lattnered922162003-10-07 18:46:23 +000075 }
Chris Lattner1b094a02003-04-23 16:23:59 +000076 };
77
Chris Lattnerc2d3d312006-08-27 22:42:52 +000078 RegisterPass<LowerSwitch>
Chris Lattner1b094a02003-04-23 16:23:59 +000079 X("lowerswitch", "Lower SwitchInst's to branches");
80}
81
Chris Lattner2d3a0272006-05-02 04:24:36 +000082// Publically exposed interface to pass...
83const PassInfo *llvm::LowerSwitchID = X.getPassInfo();
Chris Lattner1b094a02003-04-23 16:23:59 +000084// createLowerSwitchPass - Interface to this file...
Chris Lattner49525f82004-01-09 06:02:20 +000085FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner1b094a02003-04-23 16:23:59 +000086 return new LowerSwitch();
87}
88
89bool LowerSwitch::runOnFunction(Function &F) {
90 bool Changed = false;
91
92 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
93 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
94
95 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
96 Changed = true;
97 processSwitchInst(SI);
98 }
99 }
100
101 return Changed;
102}
103
Chris Lattnered922162003-10-07 18:46:23 +0000104// operator<< - Used for debugging purposes.
105//
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000106static std::ostream& operator<<(std::ostream &O,
107 const LowerSwitch::CaseVector &C) {
Chris Lattnered922162003-10-07 18:46:23 +0000108 O << "[";
109
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000110 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
Chris Lattner49525f82004-01-09 06:02:20 +0000111 E = C.end(); B != E; ) {
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000112 O << *B->Low << " -" << *B->High;
Chris Lattnered922162003-10-07 18:46:23 +0000113 if (++B != E) O << ", ";
114 }
115
116 return O << "]";
117}
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000118
119static OStream& operator<<(OStream &O, const LowerSwitch::CaseVector &C) {
Bill Wendlinga77f1422006-12-17 05:15:13 +0000120 if (O.stream()) *O.stream() << C;
121 return O;
122}
Chris Lattnered922162003-10-07 18:46:23 +0000123
124// 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;
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000137 std::vector<CaseRange> LHS(Begin, Begin + Mid);
Bill Wendling4ae40102006-11-26 10:17:54 +0000138 DOUT << "LHS: " << LHS << "\n";
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000139 std::vector<CaseRange> RHS(Begin + Mid, End);
Bill Wendling4ae40102006-11-26 10:17:54 +0000140 DOUT << "RHS: " << RHS << "\n";
Chris Lattnered922162003-10-07 18:46:23 +0000141
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000142 CaseRange& Pivot = *(Begin + Mid);
Reid Spencerdec03a02007-03-02 23:15:21 +0000143 DEBUG( DOUT << "Pivot ==> "
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000144 << cast<ConstantInt>(Pivot.Low)->getValue().toStringSigned(10)
145 << " -"
146 << cast<ConstantInt>(Pivot.High)->getValue().toStringSigned(10)
Reid Spencerdec03a02007-03-02 23:15:21 +0000147 << "\n");
Chris Lattnered922162003-10-07 18:46:23 +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();
157 BasicBlock* NewNode = new BasicBlock("NodeBlock");
158 F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode);
159
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000160 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT, Val, Pivot.Low, "Pivot");
Chris Lattnered922162003-10-07 18:46:23 +0000161 NewNode->getInstList().push_back(Comp);
Chris Lattner2af51722003-11-20 18:25:24 +0000162 new BranchInst(LBranch, RBranch, Comp, NewNode);
Chris Lattnered922162003-10-07 18:46:23 +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//
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000172BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnered922162003-10-07 18:46:23 +0000173 BasicBlock* OrigBlock,
174 BasicBlock* Default)
175{
176 Function* F = OrigBlock->getParent();
177 BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
178 F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);
179
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000180 // Emit comparison
181 ICmpInst* Comp = NULL;
182 if (Leaf.Low == Leaf.High) {
183 // Make the seteq instruction...
184 Comp = new ICmpInst(ICmpInst::ICMP_EQ, Val, Leaf.Low,
185 "SwitchLeaf", NewLeaf);
186 } else {
187 // Make range comparison
188 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
189 // Val >= Min && Val <= Hi --> Val <= Hi
190 Comp = new ICmpInst(ICmpInst::ICMP_SLE, Val, Leaf.High,
191 "SwitchLeaf", NewLeaf);
192 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
193 // Val >= 0 && Val <= Hi --> Val <=u Hi
194 Comp = new ICmpInst(ICmpInst::ICMP_ULE, Val, Leaf.High,
195 "SwitchLeaf", NewLeaf);
196 } else {
197 // Emit V-Lo <=u Hi-Lo
198 Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
199 Instruction* Add = BinaryOperator::createAdd(Val, NegLo,
200 Val->getName()+".off",
201 NewLeaf);
202 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
203 Comp = new ICmpInst(ICmpInst::ICMP_ULE, Add, UpperBound,
204 "SwitchLeaf", NewLeaf);
205 }
206 }
Chris Lattnered922162003-10-07 18:46:23 +0000207
208 // Make the conditional branch...
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000209 BasicBlock* Succ = Leaf.BB;
Chris Lattner2af51722003-11-20 18:25:24 +0000210 new BranchInst(Succ, Default, Comp, NewLeaf);
Chris Lattnered922162003-10-07 18:46:23 +0000211
212 // If there were any PHI nodes in this successor, rewrite one entry
213 // from OrigBlock to come from NewLeaf.
Reid Spencer66149462004-09-15 17:06:42 +0000214 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
215 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000216 // Remove all but one incoming entries from the cluster
217 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
218 cast<ConstantInt>(Leaf.Low)->getSExtValue();
219 for (uint64_t j = 0; j < Range; ++j) {
220 PN->removeIncomingValue(OrigBlock);
221 }
222
Chris Lattnered922162003-10-07 18:46:23 +0000223 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
224 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
225 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
226 }
227
228 return NewLeaf;
229}
230
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000231// Clusterify - Transform simple list of Cases into list of CaseRange's
232unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
233 unsigned numCmps = 0;
234
235 // Start with "simple" cases
236 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
237 Cases.push_back(CaseRange(SI->getSuccessorValue(i),
238 SI->getSuccessorValue(i),
239 SI->getSuccessor(i)));
240 sort(Cases.begin(), Cases.end(), CaseCmp());
241
242 // Merge case into clusters
243 if (Cases.size()>=2)
244 for (CaseItr I=Cases.begin(), J=++(Cases.begin()), E=Cases.end(); J!=E; ) {
245 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
246 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
247 BasicBlock* nextBB = J->BB;
248 BasicBlock* currentBB = I->BB;
249
250 // If the two neighboring cases go to the same destination, merge them
251 // into a single case.
252 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
253 I->High = J->High;
254 J = Cases.erase(J);
255 } else {
256 I = J++;
257 }
258 }
259
260 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
261 if (I->Low != I->High)
262 // A range counts double, since it requires two compares.
263 ++numCmps;
264 }
265
266 return numCmps;
267}
268
Chris Lattner1b094a02003-04-23 16:23:59 +0000269// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnered922162003-10-07 18:46:23 +0000270// of chained if-then insts in a balanced binary search.
Chris Lattner1b094a02003-04-23 16:23:59 +0000271//
272void LowerSwitch::processSwitchInst(SwitchInst *SI) {
273 BasicBlock *CurBlock = SI->getParent();
274 BasicBlock *OrigBlock = CurBlock;
275 Function *F = CurBlock->getParent();
276 Value *Val = SI->getOperand(0); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000277 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000278
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000279 // If there is only the default destination, don't bother with the code below.
280 if (SI->getNumOperands() == 2) {
Chris Lattnera2960002003-11-21 16:52:05 +0000281 new BranchInst(SI->getDefaultDest(), CurBlock);
Chris Lattnerb6865952004-03-14 04:14:31 +0000282 CurBlock->getInstList().erase(SI);
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000283 return;
284 }
285
Chris Lattnered922162003-10-07 18:46:23 +0000286 // Create a new, empty default block so that the new hierarchy of
287 // if-then statements go to this and the PHI nodes are happy.
288 BasicBlock* NewDefault = new BasicBlock("NewDefault");
289 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000290
Chris Lattnera2960002003-11-21 16:52:05 +0000291 new BranchInst(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000292
Chris Lattnered922162003-10-07 18:46:23 +0000293 // If there is an entry in any PHI nodes for the default edge, make sure
294 // to update them as well.
Reid Spencer66149462004-09-15 17:06:42 +0000295 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
296 PHINode *PN = cast<PHINode>(I);
Chris Lattnered922162003-10-07 18:46:23 +0000297 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
298 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
299 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000300 }
301
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000302 // Prepare cases vector.
303 CaseVector Cases;
304 unsigned numCmps = Clusterify(Cases, SI);
Chris Lattnered922162003-10-07 18:46:23 +0000305
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000306 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
307 << ". Total compares: " << numCmps << "\n";
Bill Wendling4ae40102006-11-26 10:17:54 +0000308 DOUT << "Cases: " << Cases << "\n";
Anton Korobeynikov8a6dc102007-03-10 16:46:28 +0000309
Chris Lattnered922162003-10-07 18:46:23 +0000310 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
311 OrigBlock, NewDefault);
312
313 // Branch to our shiny new if-then stuff...
Chris Lattnera2960002003-11-21 16:52:05 +0000314 new BranchInst(SwitchBlock, OrigBlock);
Chris Lattnered922162003-10-07 18:46:23 +0000315
Chris Lattner1b094a02003-04-23 16:23:59 +0000316 // We are now done with the switch instruction, delete it.
Chris Lattnerb6865952004-03-14 04:14:31 +0000317 CurBlock->getInstList().erase(SI);
Chris Lattner1b094a02003-04-23 16:23:59 +0000318}