blob: 1d0e47145ac26e6734879d2406a114763d1b1933 [file] [log] [blame]
Chris Lattner1b094a02003-04-23 16:23:59 +00001//===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
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 Lattnered922162003-10-07 18:46:23 +000017#include "llvm/Constants.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000018#include "llvm/Function.h"
19#include "llvm/iTerminators.h"
20#include "llvm/iOperators.h"
21#include "llvm/iPHINode.h"
22#include "llvm/Pass.h"
Chris Lattnered922162003-10-07 18:46:23 +000023#include "Support/Debug.h"
Chris Lattner1b094a02003-04-23 16:23:59 +000024#include "Support/Statistic.h"
25
Brian Gaeke960707c2003-11-11 22:41:34 +000026namespace llvm {
27
Chris Lattner1b094a02003-04-23 16:23:59 +000028namespace {
29 Statistic<> NumLowered("lowerswitch", "Number of SwitchInst's replaced");
30
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!
Chris Lattnered922162003-10-07 18:46:23 +000034 class LowerSwitch : public FunctionPass {
35 public:
Chris Lattner1b094a02003-04-23 16:23:59 +000036 bool runOnFunction(Function &F);
Chris Lattnered922162003-10-07 18:46:23 +000037 typedef std::pair<Constant*, BasicBlock*> Case;
38 typedef std::vector<Case>::iterator CaseItr;
39 private:
Chris Lattner1b094a02003-04-23 16:23:59 +000040 void processSwitchInst(SwitchInst *SI);
Chris Lattnered922162003-10-07 18:46:23 +000041
42 BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
43 BasicBlock* OrigBlock, BasicBlock* Default);
44 BasicBlock* newLeafBlock(Case& Leaf, Value* Val,
45 BasicBlock* OrigBlock, BasicBlock* Default);
46 };
47
48 /// The comparison function for sorting the switch case values in the vector.
49 struct CaseCmp {
50 bool operator () (const LowerSwitch::Case& C1,
51 const LowerSwitch::Case& C2) {
52 if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
53 return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
54
55 const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
56 return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
57 }
Chris Lattner1b094a02003-04-23 16:23:59 +000058 };
59
60 RegisterOpt<LowerSwitch>
61 X("lowerswitch", "Lower SwitchInst's to branches");
62}
63
64// createLowerSwitchPass - Interface to this file...
Brian Gaeke89207942003-08-13 18:18:15 +000065FunctionPass *createLowerSwitchPass() {
Chris Lattner1b094a02003-04-23 16:23:59 +000066 return new LowerSwitch();
67}
68
69bool LowerSwitch::runOnFunction(Function &F) {
70 bool Changed = false;
71
72 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
73 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
74
75 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
76 Changed = true;
77 processSwitchInst(SI);
78 }
79 }
80
81 return Changed;
82}
83
Chris Lattnered922162003-10-07 18:46:23 +000084// operator<< - Used for debugging purposes.
85//
86std::ostream& operator << (std::ostream& O, std::vector<LowerSwitch::Case>& C)
87{
88 O << "[";
89
90 for (std::vector<LowerSwitch::Case>::iterator B = C.begin(), E = C.end();
91 B != E; ) {
92 O << *B->first;
93 if (++B != E) O << ", ";
94 }
95
96 return O << "]";
97}
98
99// switchConvert - Convert the switch statement into a binary lookup of
100// the case values. The function recursively builds this tree.
101//
102BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
103 Value* Val, BasicBlock* OrigBlock,
104 BasicBlock* Default)
105{
106 unsigned Size = End - Begin;
107
108 if (Size == 1)
109 return newLeafBlock(*Begin, Val, OrigBlock, Default);
110
111 unsigned Mid = Size / 2;
112 std::vector<Case> LHS(Begin, Begin + Mid);
113 DEBUG(std::cerr << "LHS: " << LHS << "\n");
114 std::vector<Case> RHS(Begin + Mid, End);
115 DEBUG(std::cerr << "RHS: " << RHS << "\n");
116
117 Case& Pivot = *(Begin + Mid);
118 DEBUG(std::cerr << "Pivot ==> "
119 << cast<ConstantUInt>(Pivot.first)->getValue() << "\n");
120
121 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
122 OrigBlock, Default);
123 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
124 OrigBlock, Default);
125
126 // Create a new node that checks if the value is < pivot. Go to the
127 // left branch if it is and right branch if not.
128 Function* F = OrigBlock->getParent();
129 BasicBlock* NewNode = new BasicBlock("NodeBlock");
130 F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode);
131
132 SetCondInst* Comp = new SetCondInst(Instruction::SetLT, Val, Pivot.first,
133 "Pivot");
134 NewNode->getInstList().push_back(Comp);
135 BranchInst* Br = new BranchInst(LBranch, RBranch, Comp);
136 NewNode->getInstList().push_back(Br);
137 return NewNode;
138}
139
140// newLeafBlock - Create a new leaf block for the binary lookup tree. It
141// checks if the switch's value == the case's value. If not, then it
142// jumps to the default branch. At this point in the tree, the value
143// can't be another valid case value, so the jump to the "default" branch
144// is warranted.
145//
146BasicBlock* LowerSwitch::newLeafBlock(Case& Leaf, Value* Val,
147 BasicBlock* OrigBlock,
148 BasicBlock* Default)
149{
150 Function* F = OrigBlock->getParent();
151 BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
152 F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);
153
154 // Make the seteq instruction...
155 SetCondInst* Comp = new SetCondInst(Instruction::SetEQ, Val,
156 Leaf.first, "SwitchLeaf");
157 NewLeaf->getInstList().push_back(Comp);
158
159 // Make the conditional branch...
160 BasicBlock* Succ = Leaf.second;
161 Instruction* Br = new BranchInst(Succ, Default, Comp);
162 NewLeaf->getInstList().push_back(Br);
163
164 // If there were any PHI nodes in this successor, rewrite one entry
165 // from OrigBlock to come from NewLeaf.
166 for (BasicBlock::iterator I = Succ->begin();
167 PHINode* PN = dyn_cast<PHINode>(I); ++I) {
168 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
169 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
170 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
171 }
172
173 return NewLeaf;
174}
175
Chris Lattner1b094a02003-04-23 16:23:59 +0000176// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnered922162003-10-07 18:46:23 +0000177// of chained if-then insts in a balanced binary search.
Chris Lattner1b094a02003-04-23 16:23:59 +0000178//
179void LowerSwitch::processSwitchInst(SwitchInst *SI) {
180 BasicBlock *CurBlock = SI->getParent();
181 BasicBlock *OrigBlock = CurBlock;
182 Function *F = CurBlock->getParent();
183 Value *Val = SI->getOperand(0); // The value we are switching on...
Chris Lattnered922162003-10-07 18:46:23 +0000184 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner1b094a02003-04-23 16:23:59 +0000185
186 // Unlink the switch instruction from it's block.
187 CurBlock->getInstList().remove(SI);
188
Chris Lattnerf1b1c5e2003-08-23 22:54:34 +0000189 // If there is only the default destination, don't bother with the code below.
190 if (SI->getNumOperands() == 2) {
191 CurBlock->getInstList().push_back(new BranchInst(SI->getDefaultDest()));
192 delete SI;
193 return;
194 }
195
Chris Lattnered922162003-10-07 18:46:23 +0000196 // Create a new, empty default block so that the new hierarchy of
197 // if-then statements go to this and the PHI nodes are happy.
198 BasicBlock* NewDefault = new BasicBlock("NewDefault");
199 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000200
Chris Lattnered922162003-10-07 18:46:23 +0000201 NewDefault->getInstList().push_back(new BranchInst(Default));
Chris Lattner1b094a02003-04-23 16:23:59 +0000202
Chris Lattnered922162003-10-07 18:46:23 +0000203 // If there is an entry in any PHI nodes for the default edge, make sure
204 // to update them as well.
205 for (BasicBlock::iterator I = Default->begin();
206 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
207 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
208 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
209 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner1b094a02003-04-23 16:23:59 +0000210 }
211
Chris Lattnered922162003-10-07 18:46:23 +0000212 std::vector<Case> Cases;
213
214 // Expand comparisons for all of the non-default cases...
215 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
216 Cases.push_back(Case(SI->getSuccessorValue(i), SI->getSuccessor(i)));
217
218 std::sort(Cases.begin(), Cases.end(), CaseCmp());
219 DEBUG(std::cerr << "Cases: " << Cases << "\n");
220 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
221 OrigBlock, NewDefault);
222
223 // Branch to our shiny new if-then stuff...
224 OrigBlock->getInstList().push_back(new BranchInst(SwitchBlock));
225
Chris Lattner1b094a02003-04-23 16:23:59 +0000226 // We are now done with the switch instruction, delete it.
227 delete SI;
228}
Brian Gaeke960707c2003-11-11 22:41:34 +0000229
230} // End llvm namespace