blob: b2974a98c8028ea40dc2601bdd3294f79ad8dbac [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);
62 if (CI1->getType()->isUnsigned())
63 return CI1->getZExtValue() < CI2->getZExtValue();
64 return CI1->getSExtValue() < CI2->getSExtValue();
Chris Lattnerebbc1a52003-10-07 18:46:23 +000065 }
Chris Lattner14383482003-04-23 16:23:59 +000066 };
67
Chris Lattner7f8897f2006-08-27 22:42:52 +000068 RegisterPass<LowerSwitch>
Chris Lattner14383482003-04-23 16:23:59 +000069 X("lowerswitch", "Lower SwitchInst's to branches");
70}
71
Chris Lattnerb3674e42006-05-02 04:24:36 +000072// Publically exposed interface to pass...
73const PassInfo *llvm::LowerSwitchID = X.getPassInfo();
Chris Lattner14383482003-04-23 16:23:59 +000074// createLowerSwitchPass - Interface to this file...
Chris Lattnerd7456022004-01-09 06:02:20 +000075FunctionPass *llvm::createLowerSwitchPass() {
Chris Lattner14383482003-04-23 16:23:59 +000076 return new LowerSwitch();
77}
78
79bool LowerSwitch::runOnFunction(Function &F) {
80 bool Changed = false;
81
82 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
83 BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
84
85 if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
86 Changed = true;
87 processSwitchInst(SI);
88 }
89 }
90
91 return Changed;
92}
93
Chris Lattnerebbc1a52003-10-07 18:46:23 +000094// operator<< - Used for debugging purposes.
95//
Bill Wendling5c7e3262006-12-17 05:15:13 +000096std::ostream& operator<<(std::ostream &O,
97 const std::vector<LowerSwitch::Case> &C) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +000098 O << "[";
99
Chris Lattnerd7456022004-01-09 06:02:20 +0000100 for (std::vector<LowerSwitch::Case>::const_iterator B = C.begin(),
101 E = C.end(); B != E; ) {
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000102 O << *B->first;
103 if (++B != E) O << ", ";
104 }
105
106 return O << "]";
107}
Bill Wendling5c7e3262006-12-17 05:15:13 +0000108OStream& operator<<(OStream &O, const std::vector<LowerSwitch::Case> &C) {
109 if (O.stream()) *O.stream() << C;
110 return O;
111}
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000112
113// switchConvert - Convert the switch statement into a binary lookup of
114// the case values. The function recursively builds this tree.
115//
116BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
117 Value* Val, BasicBlock* OrigBlock,
118 BasicBlock* Default)
119{
120 unsigned Size = End - Begin;
121
122 if (Size == 1)
123 return newLeafBlock(*Begin, Val, OrigBlock, Default);
124
125 unsigned Mid = Size / 2;
126 std::vector<Case> LHS(Begin, Begin + Mid);
Bill Wendling0d45a092006-11-26 10:17:54 +0000127 DOUT << "LHS: " << LHS << "\n";
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000128 std::vector<Case> RHS(Begin + Mid, End);
Bill Wendling0d45a092006-11-26 10:17:54 +0000129 DOUT << "RHS: " << RHS << "\n";
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000130
131 Case& Pivot = *(Begin + Mid);
Bill Wendling0d45a092006-11-26 10:17:54 +0000132 DOUT << "Pivot ==> "
133 << cast<ConstantInt>(Pivot.first)->getSExtValue() << "\n";
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000134
135 BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
136 OrigBlock, Default);
137 BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
138 OrigBlock, Default);
139
140 // Create a new node that checks if the value is < pivot. Go to the
141 // left branch if it is and right branch if not.
142 Function* F = OrigBlock->getParent();
143 BasicBlock* NewNode = new BasicBlock("NodeBlock");
144 F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode);
145
Reid Spencere4d87aa2006-12-23 06:05:41 +0000146 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_ULT, Val, Pivot.first, "Pivot");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000147 NewNode->getInstList().push_back(Comp);
Chris Lattnerf8485c62003-11-20 18:25:24 +0000148 new BranchInst(LBranch, RBranch, Comp, NewNode);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000149 return NewNode;
150}
151
152// newLeafBlock - Create a new leaf block for the binary lookup tree. It
153// checks if the switch's value == the case's value. If not, then it
154// jumps to the default branch. At this point in the tree, the value
155// can't be another valid case value, so the jump to the "default" branch
156// is warranted.
157//
158BasicBlock* LowerSwitch::newLeafBlock(Case& Leaf, Value* Val,
159 BasicBlock* OrigBlock,
160 BasicBlock* Default)
161{
162 Function* F = OrigBlock->getParent();
163 BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
164 F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);
165
166 // Make the seteq instruction...
Reid Spencere4d87aa2006-12-23 06:05:41 +0000167 ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_EQ, Val,
168 Leaf.first, "SwitchLeaf");
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000169 NewLeaf->getInstList().push_back(Comp);
170
171 // Make the conditional branch...
172 BasicBlock* Succ = Leaf.second;
Chris Lattnerf8485c62003-11-20 18:25:24 +0000173 new BranchInst(Succ, Default, Comp, NewLeaf);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000174
175 // If there were any PHI nodes in this successor, rewrite one entry
176 // from OrigBlock to come from NewLeaf.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000177 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
178 PHINode* PN = cast<PHINode>(I);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000179 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
180 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
181 PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
182 }
183
184 return NewLeaf;
185}
186
Chris Lattner14383482003-04-23 16:23:59 +0000187// processSwitchInst - Replace the specified switch instruction with a sequence
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000188// of chained if-then insts in a balanced binary search.
Chris Lattner14383482003-04-23 16:23:59 +0000189//
190void LowerSwitch::processSwitchInst(SwitchInst *SI) {
191 BasicBlock *CurBlock = SI->getParent();
192 BasicBlock *OrigBlock = CurBlock;
193 Function *F = CurBlock->getParent();
194 Value *Val = SI->getOperand(0); // The value we are switching on...
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000195 BasicBlock* Default = SI->getDefaultDest();
Chris Lattner14383482003-04-23 16:23:59 +0000196
Chris Lattner44bb5412003-08-23 22:54:34 +0000197 // If there is only the default destination, don't bother with the code below.
198 if (SI->getNumOperands() == 2) {
Chris Lattner108e4ab2003-11-21 16:52:05 +0000199 new BranchInst(SI->getDefaultDest(), CurBlock);
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000200 CurBlock->getInstList().erase(SI);
Chris Lattner44bb5412003-08-23 22:54:34 +0000201 return;
202 }
203
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000204 // Create a new, empty default block so that the new hierarchy of
205 // if-then statements go to this and the PHI nodes are happy.
206 BasicBlock* NewDefault = new BasicBlock("NewDefault");
207 F->getBasicBlockList().insert(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000208
Chris Lattner108e4ab2003-11-21 16:52:05 +0000209 new BranchInst(Default, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000210
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000211 // If there is an entry in any PHI nodes for the default edge, make sure
212 // to update them as well.
Reid Spencer2da5c3d2004-09-15 17:06:42 +0000213 for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
214 PHINode *PN = cast<PHINode>(I);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000215 int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
216 assert(BlockIdx != -1 && "Switch didn't go to this successor??");
217 PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
Chris Lattner14383482003-04-23 16:23:59 +0000218 }
219
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000220 std::vector<Case> Cases;
221
222 // Expand comparisons for all of the non-default cases...
223 for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
224 Cases.push_back(Case(SI->getSuccessorValue(i), SI->getSuccessor(i)));
225
226 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Bill Wendling0d45a092006-11-26 10:17:54 +0000227 DOUT << "Cases: " << Cases << "\n";
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000228 BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
229 OrigBlock, NewDefault);
230
231 // Branch to our shiny new if-then stuff...
Chris Lattner108e4ab2003-11-21 16:52:05 +0000232 new BranchInst(SwitchBlock, OrigBlock);
Chris Lattnerebbc1a52003-10-07 18:46:23 +0000233
Chris Lattner14383482003-04-23 16:23:59 +0000234 // We are now done with the switch instruction, delete it.
Chris Lattnerbf9eadd2004-03-14 04:14:31 +0000235 CurBlock->getInstList().erase(SI);
Chris Lattner14383482003-04-23 16:23:59 +0000236}