Added an automatic cast to "std::ostream*" etc. from OStream. We then can
[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/Support/Compiler.h"
24 #include "llvm/ADT/Statistic.h"
25 #include <algorithm>
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 VISIBILITY_HIDDEN 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
63       const ConstantInt* CI1 = cast<const ConstantInt>(C1.first);
64       const ConstantInt* CI2 = cast<const ConstantInt>(C2.first);
65       if (CI1->getType()->isUnsigned()) 
66         return CI1->getZExtValue() < CI2->getZExtValue();
67       return CI1->getSExtValue() < CI2->getSExtValue();
68     }
69   };
70
71   RegisterPass<LowerSwitch>
72   X("lowerswitch", "Lower SwitchInst's to branches");
73 }
74
75 // Publically exposed interface to pass...
76 const PassInfo *llvm::LowerSwitchID = X.getPassInfo();
77 // createLowerSwitchPass - Interface to this file...
78 FunctionPass *llvm::createLowerSwitchPass() {
79   return new LowerSwitch();
80 }
81
82 bool LowerSwitch::runOnFunction(Function &F) {
83   bool Changed = false;
84
85   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
86     BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
87
88     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
89       Changed = true;
90       processSwitchInst(SI);
91     }
92   }
93
94   return Changed;
95 }
96
97 // operator<< - Used for debugging purposes.
98 //
99 std::ostream& operator<<(std::ostream &O,
100                          const std::vector<LowerSwitch::Case> &C) {
101   O << "[";
102
103   for (std::vector<LowerSwitch::Case>::const_iterator B = C.begin(),
104          E = C.end(); B != E; ) {
105     O << *B->first;
106     if (++B != E) O << ", ";
107   }
108
109   return O << "]";
110 }
111 OStream& operator<<(OStream &O, const std::vector<LowerSwitch::Case> &C) {
112   if (O.stream()) *O.stream() << C;
113   return O;
114 }
115
116 // switchConvert - Convert the switch statement into a binary lookup of
117 // the case values. The function recursively builds this tree.
118 //
119 BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
120                                        Value* Val, BasicBlock* OrigBlock,
121                                        BasicBlock* Default)
122 {
123   unsigned Size = End - Begin;
124
125   if (Size == 1)
126     return newLeafBlock(*Begin, Val, OrigBlock, Default);
127
128   unsigned Mid = Size / 2;
129   std::vector<Case> LHS(Begin, Begin + Mid);
130   DOUT << "LHS: " << LHS << "\n";
131   std::vector<Case> RHS(Begin + Mid, End);
132   DOUT << "RHS: " << RHS << "\n";
133
134   Case& Pivot = *(Begin + Mid);
135   DOUT << "Pivot ==> "
136        << cast<ConstantInt>(Pivot.first)->getSExtValue() << "\n";
137
138   BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
139                                       OrigBlock, Default);
140   BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
141                                       OrigBlock, Default);
142
143   // Create a new node that checks if the value is < pivot. Go to the
144   // left branch if it is and right branch if not.
145   Function* F = OrigBlock->getParent();
146   BasicBlock* NewNode = new BasicBlock("NodeBlock");
147   F->getBasicBlockList().insert(OrigBlock->getNext(), NewNode);
148
149   SetCondInst* Comp = new SetCondInst(Instruction::SetLT, Val, Pivot.first,
150                                       "Pivot");
151   NewNode->getInstList().push_back(Comp);
152   new BranchInst(LBranch, RBranch, Comp, NewNode);
153   return NewNode;
154 }
155
156 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
157 // checks if the switch's value == the case's value. If not, then it
158 // jumps to the default branch. At this point in the tree, the value
159 // can't be another valid case value, so the jump to the "default" branch
160 // is warranted.
161 //
162 BasicBlock* LowerSwitch::newLeafBlock(Case& Leaf, Value* Val,
163                                       BasicBlock* OrigBlock,
164                                       BasicBlock* Default)
165 {
166   Function* F = OrigBlock->getParent();
167   BasicBlock* NewLeaf = new BasicBlock("LeafBlock");
168   F->getBasicBlockList().insert(OrigBlock->getNext(), NewLeaf);
169
170   // Make the seteq instruction...
171   SetCondInst* Comp = new SetCondInst(Instruction::SetEQ, Val,
172                                       Leaf.first, "SwitchLeaf");
173   NewLeaf->getInstList().push_back(Comp);
174
175   // Make the conditional branch...
176   BasicBlock* Succ = Leaf.second;
177   new BranchInst(Succ, Default, Comp, NewLeaf);
178
179   // If there were any PHI nodes in this successor, rewrite one entry
180   // from OrigBlock to come from NewLeaf.
181   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
182     PHINode* PN = cast<PHINode>(I);
183     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
184     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
185     PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
186   }
187
188   return NewLeaf;
189 }
190
191 // processSwitchInst - Replace the specified switch instruction with a sequence
192 // of chained if-then insts in a balanced binary search.
193 //
194 void LowerSwitch::processSwitchInst(SwitchInst *SI) {
195   BasicBlock *CurBlock = SI->getParent();
196   BasicBlock *OrigBlock = CurBlock;
197   Function *F = CurBlock->getParent();
198   Value *Val = SI->getOperand(0);  // The value we are switching on...
199   BasicBlock* Default = SI->getDefaultDest();
200
201   // If there is only the default destination, don't bother with the code below.
202   if (SI->getNumOperands() == 2) {
203     new BranchInst(SI->getDefaultDest(), CurBlock);
204     CurBlock->getInstList().erase(SI);
205     return;
206   }
207
208   // Create a new, empty default block so that the new hierarchy of
209   // if-then statements go to this and the PHI nodes are happy.
210   BasicBlock* NewDefault = new BasicBlock("NewDefault");
211   F->getBasicBlockList().insert(Default, NewDefault);
212
213   new BranchInst(Default, NewDefault);
214
215   // If there is an entry in any PHI nodes for the default edge, make sure
216   // to update them as well.
217   for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
218     PHINode *PN = cast<PHINode>(I);
219     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
220     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
221     PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
222   }
223
224   std::vector<Case> Cases;
225
226   // Expand comparisons for all of the non-default cases...
227   for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
228     Cases.push_back(Case(SI->getSuccessorValue(i), SI->getSuccessor(i)));
229
230   std::sort(Cases.begin(), Cases.end(), CaseCmp());
231   DOUT << "Cases: " << Cases << "\n";
232   BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
233                                           OrigBlock, NewDefault);
234
235   // Branch to our shiny new if-then stuff...
236   new BranchInst(SwitchBlock, OrigBlock);
237
238   // We are now done with the switch instruction, delete it.
239   CurBlock->getInstList().erase(SI);
240 }