379a2e45703e591a0890495cfcf26346486f78ca
[oota-llvm.git] / lib / Transforms / Utils / LowerSwitch.cpp
1 //===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
2 //
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 //===----------------------------------------------------------------------===//
9 //
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"
17 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/ADT/Statistic.h"
24 #include <algorithm>
25 #include <iostream>
26 using namespace llvm;
27
28 namespace {
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!
34   class LowerSwitch : public FunctionPass {
35   public:
36     virtual bool runOnFunction(Function &F);
37     
38     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
39       // This is a cluster of orthogonal Transforms     
40       AU.addPreserved<UnifyFunctionExitNodes>();
41       AU.addPreservedID(PromoteMemoryToRegisterID);
42       AU.addPreservedID(LowerSelectID);
43       AU.addPreservedID(LowerInvokePassID);
44       AU.addPreservedID(LowerAllocationsID);
45     }
46         
47     typedef std::pair<Constant*, BasicBlock*> Case;
48     typedef std::vector<Case>::iterator       CaseItr;
49   private:
50     void processSwitchInst(SwitchInst *SI);
51
52     BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
53                               BasicBlock* OrigBlock, BasicBlock* Default);
54     BasicBlock* newLeafBlock(Case& Leaf, Value* Val,
55                              BasicBlock* OrigBlock, BasicBlock* Default);
56   };
57
58   /// The comparison function for sorting the switch case values in the vector.
59   struct CaseCmp {
60     bool operator () (const LowerSwitch::Case& C1,
61                       const LowerSwitch::Case& C2) {
62       if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
63         return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
64
65       const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
66       return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
67     }
68   };
69
70   RegisterOpt<LowerSwitch>
71   X("lowerswitch", "Lower SwitchInst's to branches");
72 }
73
74 // Publically exposed interface to pass...
75 const PassInfo *llvm::LowerSwitchID = X.getPassInfo();
76 // createLowerSwitchPass - Interface to this file...
77 FunctionPass *llvm::createLowerSwitchPass() {
78   return new LowerSwitch();
79 }
80
81 bool LowerSwitch::runOnFunction(Function &F) {
82   bool Changed = false;
83
84   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
85     BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
86
87     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
88       Changed = true;
89       processSwitchInst(SI);
90     }
91   }
92
93   return Changed;
94 }
95
96 // operator<< - Used for debugging purposes.
97 //
98 std::ostream& operator<<(std::ostream &O,
99                          const std::vector<LowerSwitch::Case> &C) {
100   O << "[";
101
102   for (std::vector<LowerSwitch::Case>::const_iterator B = C.begin(),
103          E = C.end(); B != E; ) {
104     O << *B->first;
105     if (++B != E) O << ", ";
106   }
107
108   return O << "]";
109 }
110
111 // switchConvert - Convert the switch statement into a binary lookup of
112 // the case values. The function recursively builds this tree.
113 //
114 BasicBlock* 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);
125   DEBUG(std::cerr << "LHS: " << LHS << "\n");
126   std::vector<Case> RHS(Begin + Mid, End);
127   DEBUG(std::cerr << "RHS: " << RHS << "\n");
128
129   Case& Pivot = *(Begin + Mid);
130   DEBUG(std::cerr << "Pivot ==> "
131                   << (int64_t)cast<ConstantInt>(Pivot.first)->getRawValue()
132                   << "\n");
133
134   BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
135                                       OrigBlock, Default);
136   BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
137                                       OrigBlock, Default);
138
139   // Create a new node that checks if the value is < pivot. Go to the
140   // left branch if it is and right branch if not.
141   Function* F = OrigBlock->getParent();
142   BasicBlock* NewNode = new BasicBlock("NodeBlock");
143   F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode);
144
145   SetCondInst* Comp = new SetCondInst(Instruction::SetLT, Val, Pivot.first,
146                                       "Pivot");
147   NewNode->getInstList().push_back(Comp);
148   new BranchInst(LBranch, RBranch, Comp, NewNode);
149   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 //
158 BasicBlock* 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...
167   SetCondInst* Comp = new SetCondInst(Instruction::SetEQ, Val,
168                                       Leaf.first, "SwitchLeaf");
169   NewLeaf->getInstList().push_back(Comp);
170
171   // Make the conditional branch...
172   BasicBlock* Succ = Leaf.second;
173   new BranchInst(Succ, Default, Comp, NewLeaf);
174
175   // If there were any PHI nodes in this successor, rewrite one entry
176   // from OrigBlock to come from NewLeaf.
177   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
178     PHINode* PN = cast<PHINode>(I);
179     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
187 // processSwitchInst - Replace the specified switch instruction with a sequence
188 // of chained if-then insts in a balanced binary search.
189 //
190 void 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...
195   BasicBlock* Default = SI->getDefaultDest();
196
197   // If there is only the default destination, don't bother with the code below.
198   if (SI->getNumOperands() == 2) {
199     new BranchInst(SI->getDefaultDest(), CurBlock);
200     CurBlock->getInstList().erase(SI);
201     return;
202   }
203
204   // 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);
208
209   new BranchInst(Default, NewDefault);
210
211   // If there is an entry in any PHI nodes for the default edge, make sure
212   // to update them as well.
213   for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
214     PHINode *PN = cast<PHINode>(I);
215     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
216     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
217     PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
218   }
219
220   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());
227   DEBUG(std::cerr << "Cases: " << Cases << "\n");
228   BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
229                                           OrigBlock, NewDefault);
230
231   // Branch to our shiny new if-then stuff...
232   new BranchInst(SwitchBlock, OrigBlock);
233
234   // We are now done with the switch instruction, delete it.
235   CurBlock->getInstList().erase(SI);
236 }