blob: bcbadd0040ccc6c46a473e3a9a2252a9c069d7f4 [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//
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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner14383482003-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 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"
Chris Lattner14383482003-04-23 16:23:59 +000021#include "llvm/Pass.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000022#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000023#include "llvm/Support/Compiler.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000024#include <algorithm>
Chris Lattnerd7456022004-01-09 06:02:20 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Chris Lattner14383482003-04-23 16:23:59 +000027namespace {
Chris Lattner14383482003-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 Lattnerf4b54612006-06-28 22:08:15 +000031 class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000032 public:
Chris Lattner8d89e7b2006-05-09 04:13:41 +000033 virtual bool runOnFunction(Function &F);
Chris Lattnered96fe82006-05-17 21:05:27 +000034
Chris Lattner8d89e7b2006-05-09 04:13:41 +000035 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnered96fe82006-05-17 21:05:27 +000036 // This is a cluster of orthogonal Transforms
Chris Lattner8d89e7b2006-05-09 04:13:41 +000037 AU.addPreserved<UnifyFunctionExitNodes>();
38 AU.addPreservedID(PromoteMemoryToRegisterID);
39 AU.addPreservedID(LowerSelectID);
Chris Lattnered96fe82006-05-17 21:05:27 +000040 AU.addPreservedID(LowerInvokePassID);
41 AU.addPreservedID(LowerAllocationsID);
Chris Lattner8d89e7b2006-05-09 04:13:41 +000042 }
Chris Lattnered96fe82006-05-17 21:05:27 +000043
Chris Lattnerebbc1a52003-10-07 18:46:23 +000044 typedef std::pair<Constant*, BasicBlock*> Case;
45 typedef std::vector<Case>::iterator CaseItr;
46 private:
Chris Lattner14383482003-04-23 16:23:59 +000047 void processSwitchInst(SwitchInst *SI);
Chris Lattnerebbc1a52003-10-07 18:46:23 +000048
49 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
50 BasicBlock* OrigBlock, BasicBlock* Default);
51 BasicBlock* newLeafBlock(Case& Leaf, Value* Val,
52 BasicBlock* OrigBlock, BasicBlock* Default);
53 };
54
55 /// The comparison function for sorting the switch case values in the vector.
56 struct CaseCmp {
57 bool operator () (const LowerSwitch::Case& C1,
58 const LowerSwitch::Case& C2) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000059
Reid Spencerb83eb642006-10-20 07:07:24 +000060 const ConstantInt* CI1 = cast<const ConstantInt>(C1.first);
61 const ConstantInt* CI2 = cast<const ConstantInt>(C2.first);
Reid Spencerc5b206b2006-12-31 05:48:39 +000062 return CI1->getZExtValue() < CI2->getZExtValue();
Chris Lattnerebbc1a52003-10-07 18:46:23 +000063 }
Chris Lattner14383482003-04-23 16:23:59 +000064 };
65
Chris Lattner7f8897f2006-08-27 22:42:52 +000066 RegisterPass<LowerSwitch>
Chris Lattner14383482003-04-23 16:23:59 +000067 X("lowerswitch", "Lower SwitchInst's to branches");
68}
69
Chris Lattnerb3674e42006-05-02 04:24:36 +000070// Publically exposed interface to pass...
71const PassInfo *llvm::LowerSwitchID = X.getPassInfo();
Chris Lattner14383482003-04-23 16:23:59 +000072// createLowerSwitchPass - Interface to this file...
Chris Lattnerd7456022004-01-09 06:02:20 +000073FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner14383482003-04-23 16:23:59 +000074 return new LowerSwitch();
75}
76
77bool LowerSwitch::runOnFunction(Function &F) {
78 bool Changed = false;
79
80 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
81 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
82
83 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
84 Changed = true;
85 processSwitchInst(SI);
86 }
87 }
88
89 return Changed;
90}
91
Chris Lattnerebbc1a52003-10-07 18:46:23 +000092// operator<< - Used for debugging purposes.
93//
Bill Wendling5c7e3262006-12-17 05:15:13 +000094std::ostream& operator<<(std::ostream &O,
95 const std::vector<LowerSwitch::Case> &C) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000096 O << "[";
97
Chris Lattnerd7456022004-01-09 06:02:20 +000098 for (std::vector<LowerSwitch::Case>::const_iterator B = C.begin(),
99 E = C.end(); B != E; ) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000100 O << *B->first;
101 if (++B != E) O << ", ";
102 }
103
104 return O << "]";
105}
Bill Wendling5c7e3262006-12-17 05:15:13 +0000106OStream& operator<<(OStream &O, const std::vector<LowerSwitch::Case> &C) {
107 if (O.stream()) *O.stream() << C;
108 return O;
109}
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000110
111// switchConvert - Convert the switch statement into a binary lookup of
112// the case values. The function recursively builds this tree.
113//
114BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
115 Value* Val, BasicBlock* OrigBlock,
116 BasicBlock* Default)
117{
118 unsigned Size = End - Begin;
119
120 if (Size == 1)
121 return newLeafBlock(*Begin, Val, OrigBlock, Default);
122
123 unsigned Mid = Size / 2;
124 std::vector<Case> LHS(Begin, Begin + Mid);
Bill Wendling0d45a092006-11-26 10:17:54 +0000125 DOUT << "LHS: " << LHS << "\n";
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000126 std::vector<Case> RHS(Begin + Mid, End);
Bill Wendling0d45a092006-11-26 10:17:54 +0000127 DOUT << "RHS: " << RHS << "\n";
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000128
129 Case& Pivot = *(Begin + Mid);
Bill Wendling0d45a092006-11-26 10:17:54 +0000130 DOUT << "Pivot ==> "
131 << cast<ConstantInt>(Pivot.first)->getSExtValue() << "\n";
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000132
133 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
134 OrigBlock, Default);
135 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
136 OrigBlock, Default);
137
138 // Create a new node that checks if the value is < pivot. Go to the
139 // left branch if it is and right branch if not.
140 Function* F = OrigBlock->getParent();
141 BasicBlock* NewNode = new BasicBlock("NodeBlock");
142 F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode);
143
Reid Spencere4d87aa2006-12-23 06:05:41 +0000144 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_ULT, Val, Pivot.first, "Pivot");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000145 NewNode->getInstList().push_back(Comp);
Chris Lattnerf8485c62003-11-20 18:25:24 +0000146 new BranchInst(LBranch, RBranch, Comp, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000147 return NewNode;
148}
149
150// newLeafBlock - Create a new leaf block for the binary lookup tree. It
151// checks if the switch's value == the case's value. If not, then it
152// jumps to the default branch. At this point in the tree, the value
153// can't be another valid case value, so the jump to the "default" branch
154// is warranted.
155//
156BasicBlock* LowerSwitch::newLeafBlock(Case& Leaf, Value* Val,
157 BasicBlock* OrigBlock,
158 BasicBlock* Default)
159{
160 Function* F = OrigBlock->getParent();
161 BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
162 F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);
163
164 // Make the seteq instruction...
Reid Spencere4d87aa2006-12-23 06:05:41 +0000165 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_EQ, Val,
166 Leaf.first, "SwitchLeaf");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000167 NewLeaf->getInstList().push_back(Comp);
168
169 // Make the conditional branch...
170 BasicBlock* Succ = Leaf.second;
Chris Lattnerf8485c62003-11-20 18:25:24 +0000171 new BranchInst(Succ, Default, Comp, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000172
173 // If there were any PHI nodes in this successor, rewrite one entry
174 // from OrigBlock to come from NewLeaf.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000175 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
176 PHINode* PN = cast<PHINode>(I);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000177 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
178 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
179 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
180 }
181
182 return NewLeaf;
183}
184
Chris Lattner14383482003-04-23 16:23:59 +0000185// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000186// of chained if-then insts in a balanced binary search.
Chris Lattner14383482003-04-23 16:23:59 +0000187//
188void LowerSwitch::processSwitchInst(SwitchInst *SI) {
189 BasicBlock *CurBlock = SI->getParent();
190 BasicBlock *OrigBlock = CurBlock;
191 Function *F = CurBlock->getParent();
192 Value *Val = SI->getOperand(0); // The value we are switching on...
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000193 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner14383482003-04-23 16:23:59 +0000194
Chris Lattner44bb5412003-08-23 22:54:34 +0000195 // If there is only the default destination, don't bother with the code below.
196 if (SI->getNumOperands() == 2) {
Chris Lattner108e4ab2003-11-21 16:52:05 +0000197 new BranchInst(SI->getDefaultDest(), CurBlock);
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000198 CurBlock->getInstList().erase(SI);
Chris Lattner44bb5412003-08-23 22:54:34 +0000199 return;
200 }
201
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000202 // Create a new, empty default block so that the new hierarchy of
203 // if-then statements go to this and the PHI nodes are happy.
204 BasicBlock* NewDefault = new BasicBlock("NewDefault");
205 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000206
Chris Lattner108e4ab2003-11-21 16:52:05 +0000207 new BranchInst(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000208
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000209 // If there is an entry in any PHI nodes for the default edge, make sure
210 // to update them as well.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000211 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
212 PHINode *PN = cast<PHINode>(I);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000213 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
214 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
215 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000216 }
217
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000218 std::vector<Case> Cases;
219
220 // Expand comparisons for all of the non-default cases...
221 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
222 Cases.push_back(Case(SI->getSuccessorValue(i), SI->getSuccessor(i)));
223
224 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Bill Wendling0d45a092006-11-26 10:17:54 +0000225 DOUT << "Cases: " << Cases << "\n";
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000226 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
227 OrigBlock, NewDefault);
228
229 // Branch to our shiny new if-then stuff...
Chris Lattner108e4ab2003-11-21 16:52:05 +0000230 new BranchInst(SwitchBlock, OrigBlock);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000231
Chris Lattner14383482003-04-23 16:23:59 +0000232 // We are now done with the switch instruction, delete it.
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000233 CurBlock->getInstList().erase(SI);
Chris Lattner14383482003-04-23 16:23:59 +0000234}