1. Sort switch cases using APInt safe comparison.
[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 <algorithm>
25 using namespace llvm;
26
27 namespace {
28   /// 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!
31   class VISIBILITY_HIDDEN LowerSwitch : public FunctionPass {
32   public:
33     virtual bool runOnFunction(Function &F);
34     
35     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
36       // This is a cluster of orthogonal Transforms     
37       AU.addPreserved<UnifyFunctionExitNodes>();
38       AU.addPreservedID(PromoteMemoryToRegisterID);
39       AU.addPreservedID(LowerSelectID);
40       AU.addPreservedID(LowerInvokePassID);
41       AU.addPreservedID(LowerAllocationsID);
42     }
43         
44     typedef std::pair<Constant*, BasicBlock*> Case;
45     typedef std::vector<Case>::iterator       CaseItr;
46   private:
47     void processSwitchInst(SwitchInst *SI);
48
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) {
59
60       const ConstantInt* CI1 = cast<const ConstantInt>(C1.first);
61       const ConstantInt* CI2 = cast<const ConstantInt>(C2.first);
62       return CI1->getValue().ult(CI2->getValue());
63     }
64   };
65
66   RegisterPass<LowerSwitch>
67   X("lowerswitch", "Lower SwitchInst's to branches");
68 }
69
70 // Publically exposed interface to pass...
71 const PassInfo *llvm::LowerSwitchID = X.getPassInfo();
72 // createLowerSwitchPass - Interface to this file...
73 FunctionPass *llvm::createLowerSwitchPass() {
74   return new LowerSwitch();
75 }
76
77 bool 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
92 // operator<< - Used for debugging purposes.
93 //
94 std::ostream& operator<<(std::ostream &O,
95                          const std::vector<LowerSwitch::Case> &C) {
96   O << "[";
97
98   for (std::vector<LowerSwitch::Case>::const_iterator B = C.begin(),
99          E = C.end(); B != E; ) {
100     O << *B->first;
101     if (++B != E) O << ", ";
102   }
103
104   return O << "]";
105 }
106 OStream& operator<<(OStream &O, const std::vector<LowerSwitch::Case> &C) {
107   if (O.stream()) *O.stream() << C;
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   DOUT << "LHS: " << LHS << "\n";
126   std::vector<Case> RHS(Begin + Mid, End);
127   DOUT << "RHS: " << RHS << "\n";
128
129   Case& Pivot = *(Begin + Mid);
130   DOUT << "Pivot ==> "
131        << cast<ConstantInt>(Pivot.first)->getValue().toStringSigned(10) << "\n";
132
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
144   ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_ULT, Val, Pivot.first, "Pivot");
145   NewNode->getInstList().push_back(Comp);
146   new BranchInst(LBranch, RBranch, Comp, NewNode);
147   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 //
156 BasicBlock* 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...
165   ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_EQ, Val,
166                                 Leaf.first, "SwitchLeaf");
167   NewLeaf->getInstList().push_back(Comp);
168
169   // Make the conditional branch...
170   BasicBlock* Succ = Leaf.second;
171   new BranchInst(Succ, Default, Comp, NewLeaf);
172
173   // If there were any PHI nodes in this successor, rewrite one entry
174   // from OrigBlock to come from NewLeaf.
175   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
176     PHINode* PN = cast<PHINode>(I);
177     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
185 // processSwitchInst - Replace the specified switch instruction with a sequence
186 // of chained if-then insts in a balanced binary search.
187 //
188 void 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...
193   BasicBlock* Default = SI->getDefaultDest();
194
195   // If there is only the default destination, don't bother with the code below.
196   if (SI->getNumOperands() == 2) {
197     new BranchInst(SI->getDefaultDest(), CurBlock);
198     CurBlock->getInstList().erase(SI);
199     return;
200   }
201
202   // 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);
206
207   new BranchInst(Default, NewDefault);
208
209   // If there is an entry in any PHI nodes for the default edge, make sure
210   // to update them as well.
211   for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
212     PHINode *PN = cast<PHINode>(I);
213     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
214     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
215     PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
216   }
217
218   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());
225   DOUT << "Cases: " << Cases << "\n";
226   BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
227                                           OrigBlock, NewDefault);
228
229   // Branch to our shiny new if-then stuff...
230   new BranchInst(SwitchBlock, OrigBlock);
231
232   // We are now done with the switch instruction, delete it.
233   CurBlock->getInstList().erase(SI);
234 }