0e47626ce5313496805ad35c198a05ad724fb8dd
[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/ADT/STLExtras.h"
18 #include "llvm/IR/CFG.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
29 #include <algorithm>
30 using namespace llvm;
31
32 #define DEBUG_TYPE "lower-switch"
33
34 namespace {
35   struct IntRange {
36     int64_t Low, High;
37   };
38   // Return true iff R is covered by Ranges.
39   static bool IsInRanges(const IntRange &R,
40                          const std::vector<IntRange> &Ranges) {
41     // Note: Ranges must be sorted, non-overlapping and non-adjacent.
42
43     // Find the first range whose High field is >= R.High,
44     // then check if the Low field is <= R.Low. If so, we
45     // have a Range that covers R.
46     auto I = std::lower_bound(
47         Ranges.begin(), Ranges.end(), R,
48         [](const IntRange &A, const IntRange &B) { return A.High < B.High; });
49     return I != Ranges.end() && I->Low <= R.Low;
50   }
51
52   /// LowerSwitch Pass - Replace all SwitchInst instructions with chained branch
53   /// instructions.
54   class LowerSwitch : public FunctionPass {
55   public:
56     static char ID; // Pass identification, replacement for typeid
57     LowerSwitch() : FunctionPass(ID) {
58       initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
59     } 
60
61     bool runOnFunction(Function &F) override;
62
63     void getAnalysisUsage(AnalysisUsage &AU) const override {
64       // This is a cluster of orthogonal Transforms
65       AU.addPreserved<UnifyFunctionExitNodes>();
66       AU.addPreservedID(LowerInvokePassID);
67     }
68
69     struct CaseRange {
70       ConstantInt* Low;
71       ConstantInt* High;
72       BasicBlock* BB;
73
74       CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
75           : Low(low), High(high), BB(bb) {}
76     };
77
78     typedef std::vector<CaseRange> CaseVector;
79     typedef std::vector<CaseRange>::iterator CaseItr;
80   private:
81     void processSwitchInst(SwitchInst *SI, SmallVectorImpl<BasicBlock*> &DeleteList);
82
83     BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
84                               ConstantInt *LowerBound, ConstantInt *UpperBound,
85                               Value *Val, BasicBlock *Predecessor,
86                               BasicBlock *OrigBlock, BasicBlock *Default,
87                               const std::vector<IntRange> &UnreachableRanges);
88     BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
89                              BasicBlock *Default);
90     unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
91   };
92
93   /// The comparison function for sorting the switch case values in the vector.
94   /// WARNING: Case ranges should be disjoint!
95   struct CaseCmp {
96     bool operator () (const LowerSwitch::CaseRange& C1,
97                       const LowerSwitch::CaseRange& C2) {
98
99       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
100       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
101       return CI1->getValue().slt(CI2->getValue());
102     }
103   };
104 }
105
106 char LowerSwitch::ID = 0;
107 INITIALIZE_PASS(LowerSwitch, "lowerswitch",
108                 "Lower SwitchInst's to branches", false, false)
109
110 // Publicly exposed interface to pass...
111 char &llvm::LowerSwitchID = LowerSwitch::ID;
112 // createLowerSwitchPass - Interface to this file...
113 FunctionPass *llvm::createLowerSwitchPass() {
114   return new LowerSwitch();
115 }
116
117 bool LowerSwitch::runOnFunction(Function &F) {
118   bool Changed = false;
119   SmallVector<BasicBlock*, 8> DeleteList;
120
121   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
122     BasicBlock *Cur = I++; // Advance over block so we don't traverse new blocks
123
124     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
125       Changed = true;
126       processSwitchInst(SI, DeleteList);
127     }
128   }
129
130   for (BasicBlock* BB: DeleteList) {
131     DeleteDeadBlock(BB);
132   }
133
134   return Changed;
135 }
136
137 // operator<< - Used for debugging purposes.
138 //
139 static raw_ostream& operator<<(raw_ostream &O,
140                                const LowerSwitch::CaseVector &C)
141     LLVM_ATTRIBUTE_USED;
142 static raw_ostream& operator<<(raw_ostream &O,
143                                const LowerSwitch::CaseVector &C) {
144   O << "[";
145
146   for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
147          E = C.end(); B != E; ) {
148     O << *B->Low << " -" << *B->High;
149     if (++B != E) O << ", ";
150   }
151
152   return O << "]";
153 }
154
155 // \brief Update the first occurrence of the "switch statement" BB in the PHI
156 // node with the "new" BB. The other occurrences will:
157 //
158 // 1) Be updated by subsequent calls to this function.  Switch statements may
159 // have more than one outcoming edge into the same BB if they all have the same
160 // value. When the switch statement is converted these incoming edges are now
161 // coming from multiple BBs.
162 // 2) Removed if subsequent incoming values now share the same case, i.e.,
163 // multiple outcome edges are condensed into one. This is necessary to keep the
164 // number of phi values equal to the number of branches to SuccBB.
165 static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
166                     unsigned NumMergedCases) {
167   for (BasicBlock::iterator I = SuccBB->begin(), IE = SuccBB->getFirstNonPHI();
168        I != IE; ++I) {
169     PHINode *PN = cast<PHINode>(I);
170
171     // Only update the first occurrence.
172     unsigned Idx = 0, E = PN->getNumIncomingValues();
173     unsigned LocalNumMergedCases = NumMergedCases;
174     for (; Idx != E; ++Idx) {
175       if (PN->getIncomingBlock(Idx) == OrigBB) {
176         PN->setIncomingBlock(Idx, NewBB);
177         break;
178       }
179     }
180
181     // Remove additional occurrences coming from condensed cases and keep the
182     // number of incoming values equal to the number of branches to SuccBB.
183     SmallVector<unsigned, 8> Indices;
184     for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
185       if (PN->getIncomingBlock(Idx) == OrigBB) {
186         Indices.push_back(Idx);
187         LocalNumMergedCases--;
188       }
189     // Remove incoming values in the reverse order to prevent invalidating
190     // *successive* index.
191     for (auto III = Indices.rbegin(), IIE = Indices.rend(); III != IIE; ++III)
192       PN->removeIncomingValue(*III);
193   }
194 }
195
196 // switchConvert - Convert the switch statement into a binary lookup of
197 // the case values. The function recursively builds this tree.
198 // LowerBound and UpperBound are used to keep track of the bounds for Val
199 // that have already been checked by a block emitted by one of the previous
200 // calls to switchConvert in the call stack.
201 BasicBlock *
202 LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
203                            ConstantInt *UpperBound, Value *Val,
204                            BasicBlock *Predecessor, BasicBlock *OrigBlock,
205                            BasicBlock *Default,
206                            const std::vector<IntRange> &UnreachableRanges) {
207   unsigned Size = End - Begin;
208
209   if (Size == 1) {
210     // Check if the Case Range is perfectly squeezed in between
211     // already checked Upper and Lower bounds. If it is then we can avoid
212     // emitting the code that checks if the value actually falls in the range
213     // because the bounds already tell us so.
214     if (Begin->Low == LowerBound && Begin->High == UpperBound) {
215       unsigned NumMergedCases = 0;
216       if (LowerBound && UpperBound)
217         NumMergedCases =
218             UpperBound->getSExtValue() - LowerBound->getSExtValue();
219       fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
220       return Begin->BB;
221     }
222     return newLeafBlock(*Begin, Val, OrigBlock, Default);
223   }
224
225   unsigned Mid = Size / 2;
226   std::vector<CaseRange> LHS(Begin, Begin + Mid);
227   DEBUG(dbgs() << "LHS: " << LHS << "\n");
228   std::vector<CaseRange> RHS(Begin + Mid, End);
229   DEBUG(dbgs() << "RHS: " << RHS << "\n");
230
231   CaseRange &Pivot = *(Begin + Mid);
232   DEBUG(dbgs() << "Pivot ==> "
233                << Pivot.Low->getValue()
234                << " -" << Pivot.High->getValue() << "\n");
235
236   // NewLowerBound here should never be the integer minimal value.
237   // This is because it is computed from a case range that is never
238   // the smallest, so there is always a case range that has at least
239   // a smaller value.
240   ConstantInt *NewLowerBound = Pivot.Low;
241
242   // Because NewLowerBound is never the smallest representable integer
243   // it is safe here to subtract one.
244   ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
245                                                 NewLowerBound->getValue() - 1);
246
247   if (!UnreachableRanges.empty()) {
248     // Check if the gap between LHS's highest and NewLowerBound is unreachable.
249     int64_t GapLow = LHS.back().High->getSExtValue() + 1;
250     int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
251     IntRange Gap = { GapLow, GapHigh };
252     if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
253       NewUpperBound = LHS.back().High;
254   }
255
256   DEBUG(dbgs() << "LHS Bounds ==> ";
257         if (LowerBound) {
258           dbgs() << LowerBound->getSExtValue();
259         } else {
260           dbgs() << "NONE";
261         }
262         dbgs() << " - " << NewUpperBound->getSExtValue() << "\n";
263         dbgs() << "RHS Bounds ==> ";
264         dbgs() << NewLowerBound->getSExtValue() << " - ";
265         if (UpperBound) {
266           dbgs() << UpperBound->getSExtValue() << "\n";
267         } else {
268           dbgs() << "NONE\n";
269         });
270
271   // Create a new node that checks if the value is < pivot. Go to the
272   // left branch if it is and right branch if not.
273   Function* F = OrigBlock->getParent();
274   BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
275
276   ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
277                                 Val, Pivot.Low, "Pivot");
278
279   BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
280                                       NewUpperBound, Val, NewNode, OrigBlock,
281                                       Default, UnreachableRanges);
282   BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
283                                       UpperBound, Val, NewNode, OrigBlock,
284                                       Default, UnreachableRanges);
285
286   Function::iterator FI = OrigBlock;
287   F->getBasicBlockList().insert(++FI, NewNode);
288   NewNode->getInstList().push_back(Comp);
289
290   BranchInst::Create(LBranch, RBranch, Comp, NewNode);
291   return NewNode;
292 }
293
294 // newLeafBlock - Create a new leaf block for the binary lookup tree. It
295 // checks if the switch's value == the case's value. If not, then it
296 // jumps to the default branch. At this point in the tree, the value
297 // can't be another valid case value, so the jump to the "default" branch
298 // is warranted.
299 //
300 BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
301                                       BasicBlock* OrigBlock,
302                                       BasicBlock* Default)
303 {
304   Function* F = OrigBlock->getParent();
305   BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
306   Function::iterator FI = OrigBlock;
307   F->getBasicBlockList().insert(++FI, NewLeaf);
308
309   // Emit comparison
310   ICmpInst* Comp = nullptr;
311   if (Leaf.Low == Leaf.High) {
312     // Make the seteq instruction...
313     Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
314                         Leaf.Low, "SwitchLeaf");
315   } else {
316     // Make range comparison
317     if (Leaf.Low->isMinValue(true /*isSigned*/)) {
318       // Val >= Min && Val <= Hi --> Val <= Hi
319       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
320                           "SwitchLeaf");
321     } else if (Leaf.Low->isZero()) {
322       // Val >= 0 && Val <= Hi --> Val <=u Hi
323       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
324                           "SwitchLeaf");      
325     } else {
326       // Emit V-Lo <=u Hi-Lo
327       Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
328       Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
329                                                    Val->getName()+".off",
330                                                    NewLeaf);
331       Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
332       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
333                           "SwitchLeaf");
334     }
335   }
336
337   // Make the conditional branch...
338   BasicBlock* Succ = Leaf.BB;
339   BranchInst::Create(Succ, Default, Comp, NewLeaf);
340
341   // If there were any PHI nodes in this successor, rewrite one entry
342   // from OrigBlock to come from NewLeaf.
343   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
344     PHINode* PN = cast<PHINode>(I);
345     // Remove all but one incoming entries from the cluster
346     uint64_t Range = Leaf.High->getSExtValue() -
347                      Leaf.Low->getSExtValue();
348     for (uint64_t j = 0; j < Range; ++j) {
349       PN->removeIncomingValue(OrigBlock);
350     }
351     
352     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
353     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
354     PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
355   }
356
357   return NewLeaf;
358 }
359
360 // Clusterify - Transform simple list of Cases into list of CaseRange's
361 unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
362   unsigned numCmps = 0;
363
364   // Start with "simple" cases
365   for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
366     Cases.push_back(CaseRange(i.getCaseValue(), i.getCaseValue(),
367                               i.getCaseSuccessor()));
368   
369   std::sort(Cases.begin(), Cases.end(), CaseCmp());
370
371   // Merge case into clusters
372   if (Cases.size() >= 2) {
373     CaseItr I = Cases.begin();
374     for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
375       int64_t nextValue = J->Low->getSExtValue();
376       int64_t currentValue = I->High->getSExtValue();
377       BasicBlock* nextBB = J->BB;
378       BasicBlock* currentBB = I->BB;
379
380       // If the two neighboring cases go to the same destination, merge them
381       // into a single case.
382       assert(nextValue > currentValue && "Cases should be strictly ascending");
383       if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
384         I->High = J->High;
385         // FIXME: Combine branch weights.
386       } else if (++I != J) {
387         *I = *J;
388       }
389     }
390     Cases.erase(std::next(I), Cases.end());
391   }
392
393   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
394     if (I->Low != I->High)
395       // A range counts double, since it requires two compares.
396       ++numCmps;
397   }
398
399   return numCmps;
400 }
401
402 // processSwitchInst - Replace the specified switch instruction with a sequence
403 // of chained if-then insts in a balanced binary search.
404 //
405 void LowerSwitch::processSwitchInst(SwitchInst *SI, SmallVectorImpl<BasicBlock*> &DeleteList) {
406   BasicBlock *CurBlock = SI->getParent();
407   BasicBlock *OrigBlock = CurBlock;
408   Function *F = CurBlock->getParent();
409   Value *Val = SI->getCondition();  // The value we are switching on...
410   BasicBlock* Default = SI->getDefaultDest();
411
412   // If there is only the default destination, just branch.
413   if (!SI->getNumCases()) {
414     BranchInst::Create(Default, CurBlock);
415     SI->eraseFromParent();
416     return;
417   }
418
419   // Prepare cases vector.
420   CaseVector Cases;
421   unsigned numCmps = Clusterify(Cases, SI);
422   DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
423                << ". Total compares: " << numCmps << "\n");
424   DEBUG(dbgs() << "Cases: " << Cases << "\n");
425   (void)numCmps;
426
427   ConstantInt *LowerBound = nullptr;
428   ConstantInt *UpperBound = nullptr;
429   std::vector<IntRange> UnreachableRanges;
430
431   if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
432     // Make the bounds tightly fitted around the case value range, because we
433     // know that the value passed to the switch must be exactly one of the case
434     // values.
435     assert(!Cases.empty());
436     LowerBound = Cases.front().Low;
437     UpperBound = Cases.back().High;
438
439     DenseMap<BasicBlock *, unsigned> Popularity;
440     unsigned MaxPop = 0;
441     BasicBlock *PopSucc = nullptr;
442
443     IntRange R = { INT64_MIN, INT64_MAX };
444     UnreachableRanges.push_back(R);
445     for (const auto &I : Cases) {
446       int64_t Low = I.Low->getSExtValue();
447       int64_t High = I.High->getSExtValue();
448
449       IntRange &LastRange = UnreachableRanges.back();
450       if (LastRange.Low == Low) {
451         // There is nothing left of the previous range.
452         UnreachableRanges.pop_back();
453       } else {
454         // Terminate the previous range.
455         assert(Low > LastRange.Low);
456         LastRange.High = Low - 1;
457       }
458       if (High != INT64_MAX) {
459         IntRange R = { High + 1, INT64_MAX };
460         UnreachableRanges.push_back(R);
461       }
462
463       // Count popularity.
464       int64_t N = High - Low + 1;
465       unsigned &Pop = Popularity[I.BB];
466       if ((Pop += N) > MaxPop) {
467         MaxPop = Pop;
468         PopSucc = I.BB;
469       }
470     }
471 #ifndef NDEBUG
472     /* UnreachableRanges should be sorted and the ranges non-adjacent. */
473     for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
474          I != E; ++I) {
475       assert(I->Low <= I->High);
476       auto Next = I + 1;
477       if (Next != E) {
478         assert(Next->Low > I->High);
479       }
480     }
481 #endif
482
483     // Use the most popular block as the new default, reducing the number of
484     // cases.
485     assert(MaxPop > 0 && PopSucc);
486     Default = PopSucc;
487     Cases.erase(std::remove_if(
488                     Cases.begin(), Cases.end(),
489                     [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }),
490                 Cases.end());
491
492     // If there are no cases left, just branch.
493     if (Cases.empty()) {
494       BranchInst::Create(Default, CurBlock);
495       SI->eraseFromParent();
496       return;
497     }
498   }
499
500   // Create a new, empty default block so that the new hierarchy of
501   // if-then statements go to this and the PHI nodes are happy.
502   BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
503   F->getBasicBlockList().insert(Default, NewDefault);
504   BranchInst::Create(Default, NewDefault);
505
506   // If there is an entry in any PHI nodes for the default edge, make sure
507   // to update them as well.
508   for (BasicBlock::iterator I = Default->begin(); isa<PHINode>(I); ++I) {
509     PHINode *PN = cast<PHINode>(I);
510     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
511     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
512     PN->setIncomingBlock((unsigned)BlockIdx, NewDefault);
513   }
514
515   BasicBlock *SwitchBlock =
516       switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
517                     OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
518
519   // Branch to our shiny new if-then stuff...
520   BranchInst::Create(SwitchBlock, OrigBlock);
521
522   // We are now done with the switch instruction, delete it.
523   BasicBlock *OldDefault = SI->getDefaultDest();
524   CurBlock->getInstList().erase(SI);
525
526   // If the Default block has no more predecessors just add it to DeleteList.
527   if (pred_begin(OldDefault) == pred_end(OldDefault))
528     DeleteList.push_back(OldDefault);
529 }