blob: 70db29e1c0411775f30182dc386f0bdb55d8644c [file] [log] [blame]
Chris Lattner14383482003-04-23 16:23:59 +00001//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner14383482003-04-23 16:23:59 +00009//
Gordon Henriksenc86b6772007-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 Lattner14383482003-04-23 16:23:59 +000013//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Transforms/Scalar.h"
Chris Lattner8d89e7b2006-05-09 04:13:41 +000017#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
Chris Lattnerebbc1a52003-10-07 18:46:23 +000018#include "llvm/Constants.h"
Chris Lattner14383482003-04-23 16:23:59 +000019#include "llvm/Function.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000020#include "llvm/Instructions.h"
Owen Anderson0a205a42009-07-05 22:41:43 +000021#include "llvm/LLVMContext.h"
Chris Lattner14383482003-04-23 16:23:59 +000022#include "llvm/Pass.h"
Dan Gohmanb61f2f02007-11-02 22:22:02 +000023#include "llvm/ADT/STLExtras.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000024#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000025#include "llvm/Support/Compiler.h"
Chris Lattner944fac72008-08-23 22:23:09 +000026#include "llvm/Support/raw_ostream.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000027#include <algorithm>
Chris Lattnerd7456022004-01-09 06:02:20 +000028using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000029
Chris Lattner14383482003-04-23 16:23:59 +000030namespace {
Chris Lattner14383482003-04-23 16:23:59 +000031 /// 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!
Chris Lattnerf4b54612006-06-28 22:08:15 +000034 class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000035 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000036 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000037 LowerSwitch() : FunctionPass(&ID) {}
Devang Patel794fd752007-05-01 21:15:47 +000038
Chris Lattner8d89e7b2006-05-09 04:13:41 +000039 virtual bool runOnFunction(Function &F);
Chris Lattnered96fe82006-05-17 21:05:27 +000040
Chris Lattner8d89e7b2006-05-09 04:13:41 +000041 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Anton Korobeynikovbed29462007-04-16 18:10:23 +000042 // This is a cluster of orthogonal Transforms
Chris Lattner8d89e7b2006-05-09 04:13:41 +000043 AU.addPreserved<UnifyFunctionExitNodes>();
44 AU.addPreservedID(PromoteMemoryToRegisterID);
Chris Lattnered96fe82006-05-17 21:05:27 +000045 AU.addPreservedID(LowerInvokePassID);
46 AU.addPreservedID(LowerAllocationsID);
Chris Lattner8d89e7b2006-05-09 04:13:41 +000047 }
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000048
49 struct CaseRange {
50 Constant* Low;
51 Constant* High;
52 BasicBlock* BB;
53
Jeff Cohenc4558fd2007-03-12 17:56:27 +000054 CaseRange() : Low(0), High(0), BB(0) { }
55 CaseRange(Constant* low, Constant* high, BasicBlock* bb) :
56 Low(low), High(high), BB(bb) { }
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000057 };
58
59 typedef std::vector<CaseRange> CaseVector;
60 typedef std::vector<CaseRange>::iterator CaseItr;
Chris Lattnerebbc1a52003-10-07 18:46:23 +000061 private:
Chris Lattner14383482003-04-23 16:23:59 +000062 void processSwitchInst(SwitchInst *SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000063
64 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
65 BasicBlock* OrigBlock, BasicBlock* Default);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000066 BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnerebbc1a52003-10-07 18:46:23 +000067 BasicBlock* OrigBlock, BasicBlock* Default);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000068 unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000069 };
70
71 /// The comparison function for sorting the switch case values in the vector.
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000072 /// WARNING: Case ranges should be disjoint!
Chris Lattnerebbc1a52003-10-07 18:46:23 +000073 struct CaseCmp {
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000074 bool operator () (const LowerSwitch::CaseRange& C1,
75 const LowerSwitch::CaseRange& C2) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000076
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +000077 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
78 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
79 return CI1->getValue().slt(CI2->getValue());
Chris Lattnerebbc1a52003-10-07 18:46:23 +000080 }
Chris Lattner14383482003-04-23 16:23:59 +000081 };
Chris Lattner14383482003-04-23 16:23:59 +000082}
83
Dan Gohman844731a2008-05-13 00:00:25 +000084char LowerSwitch::ID = 0;
85static RegisterPass<LowerSwitch>
86X("lowerswitch", "Lower SwitchInst's to branches");
87
Chris Lattnerb3674e42006-05-02 04:24:36 +000088// Publically exposed interface to pass...
Dan Gohman6ddba2b2008-05-13 02:05:11 +000089const PassInfo *const llvm::LowerSwitchID = &X;
Chris Lattner14383482003-04-23 16:23:59 +000090// createLowerSwitchPass - Interface to this file...
Chris Lattnerd7456022004-01-09 06:02:20 +000091FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner14383482003-04-23 16:23:59 +000092 return new LowerSwitch();
93}
94
95bool LowerSwitch::runOnFunction(Function &F) {
96 bool Changed = false;
97
98 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
99 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
100
101 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
102 Changed = true;
103 processSwitchInst(SI);
104 }
105 }
106
107 return Changed;
108}
109
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000110// operator<< - Used for debugging purposes.
111//
Daniel Dunbar1cd1d982009-07-24 10:36:58 +0000112static raw_ostream& operator<<(raw_ostream &O,
113 const LowerSwitch::CaseVector &C) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000114 O << "[";
115
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000116 for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
Chris Lattnerd7456022004-01-09 06:02:20 +0000117 E = C.end(); B != E; ) {
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000118 O << *B->Low << " -" << *B->High;
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000119 if (++B != E) O << ", ";
120 }
121
122 return O << "]";
123}
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000124
125static OStream& operator<<(OStream &O, const LowerSwitch::CaseVector &C) {
Daniel Dunbar1cd1d982009-07-24 10:36:58 +0000126 if (O.stream()) {
127 raw_os_ostream OS(*O.stream());
128 OS << C;
129 }
Bill Wendling5c7e3262006-12-17 05:15:13 +0000130 return O;
131}
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000132
133// switchConvert - Convert the switch statement into a binary lookup of
134// the case values. The function recursively builds this tree.
135//
136BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
137 Value* Val, BasicBlock* OrigBlock,
138 BasicBlock* Default)
139{
140 unsigned Size = End - Begin;
141
142 if (Size == 1)
143 return newLeafBlock(*Begin, Val, OrigBlock, Default);
144
145 unsigned Mid = Size / 2;
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000146 std::vector<CaseRange> LHS(Begin, Begin + Mid);
Bill Wendling0d45a092006-11-26 10:17:54 +0000147 DOUT << "LHS: " << LHS << "\n";
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000148 std::vector<CaseRange> RHS(Begin + Mid, End);
Bill Wendling0d45a092006-11-26 10:17:54 +0000149 DOUT << "RHS: " << RHS << "\n";
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000150
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000151 CaseRange& Pivot = *(Begin + Mid);
Chris Lattner944fac72008-08-23 22:23:09 +0000152 DEBUG(errs() << "Pivot ==> "
153 << cast<ConstantInt>(Pivot.Low)->getValue() << " -"
Dan Gohmanf871ccb2009-03-23 15:57:19 +0000154 << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000155
156 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
157 OrigBlock, Default);
158 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
159 OrigBlock, Default);
160
161 // Create a new node that checks if the value is < pivot. Go to the
162 // left branch if it is and right branch if not.
163 Function* F = OrigBlock->getParent();
Gabor Greif051a9502008-04-06 20:25:17 +0000164 BasicBlock* NewNode = BasicBlock::Create("NodeBlock");
Chris Lattner261cdfb2007-04-17 18:09:47 +0000165 Function::iterator FI = OrigBlock;
166 F->getBasicBlockList().insert(++FI, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000167
Owen Andersone922c022009-07-22 00:24:57 +0000168 ICmpInst* Comp = new ICmpInst(Default->getContext(), ICmpInst::ICMP_SLT,
Owen Anderson333c4002009-07-09 23:48:35 +0000169 Val, Pivot.Low, "Pivot");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000170 NewNode->getInstList().push_back(Comp);
Gabor Greif051a9502008-04-06 20:25:17 +0000171 BranchInst::Create(LBranch, RBranch, Comp, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000172 return NewNode;
173}
174
175// newLeafBlock - Create a new leaf block for the binary lookup tree. It
176// checks if the switch's value == the case's value. If not, then it
177// jumps to the default branch. At this point in the tree, the value
178// can't be another valid case value, so the jump to the "default" branch
179// is warranted.
180//
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000181BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000182 BasicBlock* OrigBlock,
183 BasicBlock* Default)
184{
185 Function* F = OrigBlock->getParent();
Owen Andersone922c022009-07-22 00:24:57 +0000186 LLVMContext &Context = F->getContext();
Gabor Greif051a9502008-04-06 20:25:17 +0000187 BasicBlock* NewLeaf = BasicBlock::Create("LeafBlock");
Chris Lattner261cdfb2007-04-17 18:09:47 +0000188 Function::iterator FI = OrigBlock;
189 F->getBasicBlockList().insert(++FI, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000190
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000191 // Emit comparison
192 ICmpInst* Comp = NULL;
193 if (Leaf.Low == Leaf.High) {
194 // Make the seteq instruction...
Owen Anderson333c4002009-07-09 23:48:35 +0000195 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
196 Leaf.Low, "SwitchLeaf");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000197 } else {
198 // Make range comparison
199 if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
200 // Val >= Min && Val <= Hi --> Val <= Hi
Owen Anderson333c4002009-07-09 23:48:35 +0000201 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
202 "SwitchLeaf");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000203 } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
204 // Val >= 0 && Val <= Hi --> Val <=u Hi
Owen Anderson333c4002009-07-09 23:48:35 +0000205 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
206 "SwitchLeaf");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000207 } else {
208 // Emit V-Lo <=u Hi-Lo
Owen Andersone922c022009-07-22 00:24:57 +0000209 Constant* NegLo = Context.getConstantExprNeg(Leaf.Low);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000210 Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000211 Val->getName()+".off",
212 NewLeaf);
Owen Andersone922c022009-07-22 00:24:57 +0000213 Constant *UpperBound = Context.getConstantExprAdd(NegLo, Leaf.High);
Owen Anderson333c4002009-07-09 23:48:35 +0000214 Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
215 "SwitchLeaf");
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000216 }
217 }
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000218
219 // Make the conditional branch...
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000220 BasicBlock* Succ = Leaf.BB;
Gabor Greif051a9502008-04-06 20:25:17 +0000221 BranchInst::Create(Succ, Default, Comp, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000222
223 // If there were any PHI nodes in this successor, rewrite one entry
224 // from OrigBlock to come from NewLeaf.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000225 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
226 PHINode* PN = cast<PHINode>(I);
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000227 // Remove all but one incoming entries from the cluster
228 uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
229 cast<ConstantInt>(Leaf.Low)->getSExtValue();
230 for (uint64_t j = 0; j < Range; ++j) {
231 PN->removeIncomingValue(OrigBlock);
232 }
233
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000234 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
235 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
236 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
237 }
238
239 return NewLeaf;
240}
241
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000242// Clusterify - Transform simple list of Cases into list of CaseRange's
243unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
244 unsigned numCmps = 0;
245
246 // Start with "simple" cases
247 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
248 Cases.push_back(CaseRange(SI->getSuccessorValue(i),
249 SI->getSuccessorValue(i),
250 SI->getSuccessor(i)));
Dan Gohman111c4f82007-11-02 22:24:01 +0000251 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000252
253 // Merge case into clusters
254 if (Cases.size()>=2)
David Greene9dfb11d2007-12-17 17:42:03 +0000255 for (CaseItr I=Cases.begin(), J=next(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000256 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
257 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
258 BasicBlock* nextBB = J->BB;
259 BasicBlock* currentBB = I->BB;
260
261 // If the two neighboring cases go to the same destination, merge them
262 // into a single case.
263 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
264 I->High = J->High;
265 J = Cases.erase(J);
266 } else {
267 I = J++;
268 }
269 }
270
271 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
272 if (I->Low != I->High)
273 // A range counts double, since it requires two compares.
274 ++numCmps;
275 }
276
277 return numCmps;
278}
279
Chris Lattner14383482003-04-23 16:23:59 +0000280// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000281// of chained if-then insts in a balanced binary search.
Chris Lattner14383482003-04-23 16:23:59 +0000282//
283void LowerSwitch::processSwitchInst(SwitchInst *SI) {
284 BasicBlock *CurBlock = SI->getParent();
285 BasicBlock *OrigBlock = CurBlock;
286 Function *F = CurBlock->getParent();
287 Value *Val = SI->getOperand(0); // The value we are switching on...
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000288 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner14383482003-04-23 16:23:59 +0000289
Chris Lattner44bb5412003-08-23 22:54:34 +0000290 // If there is only the default destination, don't bother with the code below.
291 if (SI->getNumOperands() == 2) {
Gabor Greif051a9502008-04-06 20:25:17 +0000292 BranchInst::Create(SI->getDefaultDest(), CurBlock);
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000293 CurBlock->getInstList().erase(SI);
Chris Lattner44bb5412003-08-23 22:54:34 +0000294 return;
295 }
296
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000297 // Create a new, empty default block so that the new hierarchy of
298 // if-then statements go to this and the PHI nodes are happy.
Gabor Greif051a9502008-04-06 20:25:17 +0000299 BasicBlock* NewDefault = BasicBlock::Create("NewDefault");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000300 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000301
Gabor Greif051a9502008-04-06 20:25:17 +0000302 BranchInst::Create(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000303
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000304 // If there is an entry in any PHI nodes for the default edge, make sure
305 // to update them as well.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000306 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
307 PHINode *PN = cast<PHINode>(I);
Chris Lattnerebbc1a52003-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, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000311 }
312
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000313 // Prepare cases vector.
314 CaseVector Cases;
315 unsigned numCmps = Clusterify(Cases, SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000316
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000317 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
318 << ". Total compares: " << numCmps << "\n";
Bill Wendling0d45a092006-11-26 10:17:54 +0000319 DOUT << "Cases: " << Cases << "\n";
Anton Korobeynikove2ff29c2007-03-10 16:46:28 +0000320
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000321 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
322 OrigBlock, NewDefault);
323
324 // Branch to our shiny new if-then stuff...
Gabor Greif051a9502008-04-06 20:25:17 +0000325 BranchInst::Create(SwitchBlock, OrigBlock);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000326
Chris Lattner14383482003-04-23 16:23:59 +0000327 // We are now done with the switch instruction, delete it.
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000328 CurBlock->getInstList().erase(SI);
Chris Lattner14383482003-04-23 16:23:59 +0000329}