Move more to raw_ostream, provide support for writing MachineBasicBlock,
[oota-llvm.git] / lib / Transforms / Utils / LowerSwitch.cpp
1 //===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // The LowerSwitch transformation rewrites switch instructions with a sequence
11 // of branches, which allows targets to get away with not implementing the
12 // switch instruction 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/LLVMContext.h"
22 #include "llvm/Pass.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 using namespace llvm;
29
30 namespace {
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     static char ID; // Pass identification, replacement for typeid
37     LowerSwitch() : FunctionPass(&ID) {} 
38
39     virtual bool runOnFunction(Function &F);
40     
41     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
42       // This is a cluster of orthogonal Transforms
43       AU.addPreserved<UnifyFunctionExitNodes>();
44       AU.addPreservedID(PromoteMemoryToRegisterID);
45       AU.addPreservedID(LowerInvokePassID);
46       AU.addPreservedID(LowerAllocationsID);
47     }
48
49     struct CaseRange {
50       Constant* Low;
51       Constant* High;
52       BasicBlock* BB;
53
54       CaseRange() : Low(0), High(0), BB(0) { }
55       CaseRange(Constant* low, Constant* high, BasicBlock* bb) :
56         Low(low), High(high), BB(bb) { }
57     };
58
59     typedef std::vector<CaseRange>           CaseVector;
60     typedef std::vector<CaseRange>::iterator CaseItr;
61   private:
62     void processSwitchInst(SwitchInst *SI);
63
64     BasicBlock* switchConvert(CaseItr Begin, CaseItr End, Value* Val,
65                               BasicBlock* OrigBlock, BasicBlock* Default);
66     BasicBlock* newLeafBlock(CaseRange& Leaf, Value* Val,
67                              BasicBlock* OrigBlock, BasicBlock* Default);
68     unsigned Clusterify(CaseVector& Cases, SwitchInst *SI);
69   };
70
71   /// The comparison function for sorting the switch case values in the vector.
72   /// WARNING: Case ranges should be disjoint!
73   struct CaseCmp {
74     bool operator () (const LowerSwitch::CaseRange& C1,
75                       const LowerSwitch::CaseRange& C2) {
76
77       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
78       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
79       return CI1->getValue().slt(CI2->getValue());
80     }
81   };
82 }
83
84 char LowerSwitch::ID = 0;
85 static RegisterPass<LowerSwitch>
86 X("lowerswitch", "Lower SwitchInst's to branches");
87
88 // Publically exposed interface to pass...
89 const PassInfo *const llvm::LowerSwitchID = &X;
90 // createLowerSwitchPass - Interface to this file...
91 FunctionPass *llvm::createLowerSwitchPass() {
92   return new LowerSwitch();
93 }
94
95 bool LowerSwitch::runOnFunction(Function &F) {
96   bool Changed = false;
97
98   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
99     BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
100
101     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
102       Changed = true;
103       processSwitchInst(SI);
104     }
105   }
106
107   return Changed;
108 }
109
110 // operator<< - Used for debugging purposes.
111 //
112 static raw_ostream& operator<<(raw_ostream &O,
113                                const LowerSwitch::CaseVector &C) {
114   O << "[";
115
116   for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
117          E = C.end(); B != E; ) {
118     O << *B->Low << " -" << *B->High;
119     if (++B != E) O << ", ";
120   }
121
122   return O << "]";
123 }
124
125 static OStream& operator<<(OStream &O, const LowerSwitch::CaseVector &C) {
126   if (O.stream()) {
127     raw_os_ostream OS(*O.stream());
128     OS << C;
129   }
130   return O;
131 }
132
133 // switchConvert - Convert the switch statement into a binary lookup of
134 // the case values. The function recursively builds this tree.
135 //
136 BasicBlock* LowerSwitch::switchConvert(CaseItr Begin, CaseItr End,
137                                        Value* Val, BasicBlock* OrigBlock,
138                                        BasicBlock* Default)
139 {
140   unsigned Size = End - Begin;
141
142   if (Size == 1)
143     return newLeafBlock(*Begin, Val, OrigBlock, Default);
144
145   unsigned Mid = Size / 2;
146   std::vector<CaseRange> LHS(Begin, Begin + Mid);
147   DOUT << "LHS: " << LHS << "\n";
148   std::vector<CaseRange> RHS(Begin + Mid, End);
149   DOUT << "RHS: " << RHS << "\n";
150
151   CaseRange& Pivot = *(Begin + Mid);
152   DEBUG(errs() << "Pivot ==> " 
153                << cast<ConstantInt>(Pivot.Low)->getValue() << " -"
154                << cast<ConstantInt>(Pivot.High)->getValue() << "\n");
155
156   BasicBlock* LBranch = switchConvert(LHS.begin(), LHS.end(), Val,
157                                       OrigBlock, Default);
158   BasicBlock* RBranch = switchConvert(RHS.begin(), RHS.end(), Val,
159                                       OrigBlock, Default);
160
161   // Create a new node that checks if the value is < pivot. Go to the
162   // left branch if it is and right branch if not.
163   Function* F = OrigBlock->getParent();
164   BasicBlock* NewNode = BasicBlock::Create("NodeBlock");
165   Function::iterator FI = OrigBlock;
166   F->getBasicBlockList().insert(++FI, NewNode);
167
168   ICmpInst* Comp = new ICmpInst(Default->getContext(), ICmpInst::ICMP_SLT,
169                                 Val, Pivot.Low, "Pivot");
170   NewNode->getInstList().push_back(Comp);
171   BranchInst::Create(LBranch, RBranch, Comp, NewNode);
172   return NewNode;
173 }
174
175 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
176 // checks if the switch's value == the case's value. If not, then it
177 // jumps to the default branch. At this point in the tree, the value
178 // can't be another valid case value, so the jump to the "default" branch
179 // is warranted.
180 //
181 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
182                                       BasicBlock* OrigBlock,
183                                       BasicBlock* Default)
184 {
185   Function* F = OrigBlock->getParent();
186   LLVMContext &Context = F->getContext();
187   BasicBlock* NewLeaf = BasicBlock::Create("LeafBlock");
188   Function::iterator FI = OrigBlock;
189   F->getBasicBlockList().insert(++FI, NewLeaf);
190
191   // Emit comparison
192   ICmpInst* Comp = NULL;
193   if (Leaf.Low == Leaf.High) {
194     // Make the seteq instruction...
195     Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
196                         Leaf.Low, "SwitchLeaf");
197   } else {
198     // Make range comparison
199     if (cast<ConstantInt>(Leaf.Low)->isMinValue(true /*isSigned*/)) {
200       // Val >= Min && Val <= Hi --> Val <= Hi
201       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
202                           "SwitchLeaf");
203     } else if (cast<ConstantInt>(Leaf.Low)->isZero()) {
204       // Val >= 0 && Val <= Hi --> Val <=u Hi
205       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
206                           "SwitchLeaf");      
207     } else {
208       // Emit V-Lo <=u Hi-Lo
209       Constant* NegLo = Context.getConstantExprNeg(Leaf.Low);
210       Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
211                                                    Val->getName()+".off",
212                                                    NewLeaf);
213       Constant *UpperBound = Context.getConstantExprAdd(NegLo, Leaf.High);
214       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
215                           "SwitchLeaf");
216     }
217   }
218
219   // Make the conditional branch...
220   BasicBlock* Succ = Leaf.BB;
221   BranchInst::Create(Succ, Default, Comp, NewLeaf);
222
223   // If there were any PHI nodes in this successor, rewrite one entry
224   // from OrigBlock to come from NewLeaf.
225   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
226     PHINode* PN = cast<PHINode>(I);
227     // Remove all but one incoming entries from the cluster
228     uint64_t Range = cast<ConstantInt>(Leaf.High)->getSExtValue() -
229                      cast<ConstantInt>(Leaf.Low)->getSExtValue();    
230     for (uint64_t j = 0; j < Range; ++j) {
231       PN->removeIncomingValue(OrigBlock);
232     }
233     
234     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
235     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
236     PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
237   }
238
239   return NewLeaf;
240 }
241
242 // Clusterify - Transform simple list of Cases into list of CaseRange's
243 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
244   unsigned numCmps = 0;
245
246   // Start with "simple" cases
247   for (unsigned i = 1; i < SI->getNumSuccessors(); ++i)
248     Cases.push_back(CaseRange(SI->getSuccessorValue(i),
249                               SI->getSuccessorValue(i),
250                               SI->getSuccessor(i)));
251   std::sort(Cases.begin(), Cases.end(), CaseCmp());
252
253   // Merge case into clusters
254   if (Cases.size()>=2)
255     for (CaseItr I=Cases.begin(), J=next(Cases.begin()); J!=Cases.end(); ) {
256       int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
257       int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
258       BasicBlock* nextBB = J->BB;
259       BasicBlock* currentBB = I->BB;
260
261       // If the two neighboring cases go to the same destination, merge them
262       // into a single case.
263       if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
264         I->High = J->High;
265         J = Cases.erase(J);
266       } else {
267         I = J++;
268       }
269     }
270
271   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
272     if (I->Low != I->High)
273       // A range counts double, since it requires two compares.
274       ++numCmps;
275   }
276
277   return numCmps;
278 }
279
280 // processSwitchInst - Replace the specified switch instruction with a sequence
281 // of chained if-then insts in a balanced binary search.
282 //
283 void LowerSwitch::processSwitchInst(SwitchInst *SI) {
284   BasicBlock *CurBlock = SI->getParent();
285   BasicBlock *OrigBlock = CurBlock;
286   Function *F = CurBlock->getParent();
287   Value *Val = SI->getOperand(0);  // The value we are switching on...
288   BasicBlock* Default = SI->getDefaultDest();
289
290   // If there is only the default destination, don't bother with the code below.
291   if (SI->getNumOperands() == 2) {
292     BranchInst::Create(SI->getDefaultDest(), CurBlock);
293     CurBlock->getInstList().erase(SI);
294     return;
295   }
296
297   // Create a new, empty default block so that the new hierarchy of
298   // if-then statements go to this and the PHI nodes are happy.
299   BasicBlock* NewDefault = BasicBlock::Create("NewDefault");
300   F->getBasicBlockList().insert(Default, NewDefault);
301
302   BranchInst::Create(Default, NewDefault);
303
304   // If there is an entry in any PHI nodes for the default edge, make sure
305   // to update them as well.
306   for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
307     PHINode *PN = cast<PHINode>(I);
308     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
309     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
310     PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
311   }
312
313   // Prepare cases vector.
314   CaseVector Cases;
315   unsigned numCmps = Clusterify(Cases, SI);
316
317   DOUT << "Clusterify finished. Total clusters: " << Cases.size()
318        << ". Total compares: " << numCmps << "\n";
319   DOUT << "Cases: " << Cases << "\n";
320   
321   BasicBlock* SwitchBlock = switchConvert(Cases.begin(), Cases.end(), Val,
322                                           OrigBlock, NewDefault);
323
324   // Branch to our shiny new if-then stuff...
325   BranchInst::Create(SwitchBlock, OrigBlock);
326
327   // We are now done with the switch instruction, delete it.
328   CurBlock->getInstList().erase(SI);
329 }