1f22ef01cSRoman Divacky //===- LowerSwitch.cpp - Eliminate Switch instructions --------------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // The LowerSwitch transformation rewrites switch instructions with a sequence
11f22ef01cSRoman Divacky // of branches, which allows targets to get away with not implementing the
12f22ef01cSRoman Divacky // switch instruction until it is convenient.
13f22ef01cSRoman Divacky //
14f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
15f22ef01cSRoman Divacky 
162cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
17f22ef01cSRoman Divacky #include "llvm/ADT/STLExtras.h"
182cab237bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
192cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
202cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
21ff0cc061SDimitry Andric #include "llvm/IR/CFG.h"
22139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
23139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
242cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h"
25139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
262cab237bSDimitry Andric #include "llvm/IR/Value.h"
27139f7f9bSDimitry Andric #include "llvm/Pass.h"
282cab237bSDimitry Andric #include "llvm/Support/Casting.h"
29f22ef01cSRoman Divacky #include "llvm/Support/Compiler.h"
30f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
31f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
324ba319b5SDimitry Andric #include "llvm/Transforms/Utils.h"
33ff0cc061SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34f22ef01cSRoman Divacky #include <algorithm>
352cab237bSDimitry Andric #include <cassert>
362cab237bSDimitry Andric #include <cstdint>
372cab237bSDimitry Andric #include <iterator>
382cab237bSDimitry Andric #include <limits>
392cab237bSDimitry Andric #include <vector>
402cab237bSDimitry Andric 
41f22ef01cSRoman Divacky using namespace llvm;
42f22ef01cSRoman Divacky 
4391bc56edSDimitry Andric #define DEBUG_TYPE "lower-switch"
4491bc56edSDimitry Andric 
45f22ef01cSRoman Divacky namespace {
462cab237bSDimitry Andric 
47ff0cc061SDimitry Andric   struct IntRange {
48ff0cc061SDimitry Andric     int64_t Low, High;
49ff0cc061SDimitry Andric   };
502cab237bSDimitry Andric 
512cab237bSDimitry Andric } // end anonymous namespace
522cab237bSDimitry Andric 
53ff0cc061SDimitry Andric // Return true iff R is covered by Ranges.
IsInRanges(const IntRange & R,const std::vector<IntRange> & Ranges)54ff0cc061SDimitry Andric static bool IsInRanges(const IntRange &R,
55ff0cc061SDimitry Andric                        const std::vector<IntRange> &Ranges) {
56ff0cc061SDimitry Andric   // Note: Ranges must be sorted, non-overlapping and non-adjacent.
57ff0cc061SDimitry Andric 
58ff0cc061SDimitry Andric   // Find the first range whose High field is >= R.High,
59ff0cc061SDimitry Andric   // then check if the Low field is <= R.Low. If so, we
60ff0cc061SDimitry Andric   // have a Range that covers R.
61ff0cc061SDimitry Andric   auto I = std::lower_bound(
62ff0cc061SDimitry Andric       Ranges.begin(), Ranges.end(), R,
63ff0cc061SDimitry Andric       [](const IntRange &A, const IntRange &B) { return A.High < B.High; });
64ff0cc061SDimitry Andric   return I != Ranges.end() && I->Low <= R.Low;
65ff0cc061SDimitry Andric }
66ff0cc061SDimitry Andric 
672cab237bSDimitry Andric namespace {
682cab237bSDimitry Andric 
697d523365SDimitry Andric   /// Replace all SwitchInst instructions with chained branch instructions.
70f22ef01cSRoman Divacky   class LowerSwitch : public FunctionPass {
71f22ef01cSRoman Divacky   public:
722cab237bSDimitry Andric     // Pass identification, replacement for typeid
732cab237bSDimitry Andric     static char ID;
742cab237bSDimitry Andric 
LowerSwitch()752754fe60SDimitry Andric     LowerSwitch() : FunctionPass(ID) {
762754fe60SDimitry Andric       initializeLowerSwitchPass(*PassRegistry::getPassRegistry());
772754fe60SDimitry Andric     }
78f22ef01cSRoman Divacky 
7991bc56edSDimitry Andric     bool runOnFunction(Function &F) override;
80f22ef01cSRoman Divacky 
81f22ef01cSRoman Divacky     struct CaseRange {
82ff0cc061SDimitry Andric       ConstantInt* Low;
83ff0cc061SDimitry Andric       ConstantInt* High;
84f22ef01cSRoman Divacky       BasicBlock* BB;
85f22ef01cSRoman Divacky 
CaseRange__anon9322e28e0311::LowerSwitch::CaseRange86ff0cc061SDimitry Andric       CaseRange(ConstantInt *low, ConstantInt *high, BasicBlock *bb)
87ff0cc061SDimitry Andric           : Low(low), High(high), BB(bb) {}
88f22ef01cSRoman Divacky     };
89f22ef01cSRoman Divacky 
902cab237bSDimitry Andric     using CaseVector = std::vector<CaseRange>;
912cab237bSDimitry Andric     using CaseItr = std::vector<CaseRange>::iterator;
922cab237bSDimitry Andric 
93f22ef01cSRoman Divacky   private:
947d523365SDimitry Andric     void processSwitchInst(SwitchInst *SI, SmallPtrSetImpl<BasicBlock*> &DeleteList);
95f22ef01cSRoman Divacky 
9691bc56edSDimitry Andric     BasicBlock *switchConvert(CaseItr Begin, CaseItr End,
9791bc56edSDimitry Andric                               ConstantInt *LowerBound, ConstantInt *UpperBound,
9891bc56edSDimitry Andric                               Value *Val, BasicBlock *Predecessor,
99ff0cc061SDimitry Andric                               BasicBlock *OrigBlock, BasicBlock *Default,
100ff0cc061SDimitry Andric                               const std::vector<IntRange> &UnreachableRanges);
10191bc56edSDimitry Andric     BasicBlock *newLeafBlock(CaseRange &Leaf, Value *Val, BasicBlock *OrigBlock,
10291bc56edSDimitry Andric                              BasicBlock *Default);
103f22ef01cSRoman Divacky     unsigned Clusterify(CaseVector &Cases, SwitchInst *SI);
104f22ef01cSRoman Divacky   };
105f785676fSDimitry Andric 
106f785676fSDimitry Andric   /// The comparison function for sorting the switch case values in the vector.
107f785676fSDimitry Andric   /// WARNING: Case ranges should be disjoint!
108f785676fSDimitry Andric   struct CaseCmp {
operator ()__anon9322e28e0311::CaseCmp109f785676fSDimitry Andric     bool operator()(const LowerSwitch::CaseRange& C1,
110f785676fSDimitry Andric                     const LowerSwitch::CaseRange& C2) {
111f785676fSDimitry Andric       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
112f785676fSDimitry Andric       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
113f785676fSDimitry Andric       return CI1->getValue().slt(CI2->getValue());
114f785676fSDimitry Andric     }
115f785676fSDimitry Andric   };
1162cab237bSDimitry Andric 
1172cab237bSDimitry Andric } // end anonymous namespace
118f22ef01cSRoman Divacky 
119f22ef01cSRoman Divacky char LowerSwitch::ID = 0;
120f22ef01cSRoman Divacky 
1213b0f4066SDimitry Andric // Publicly exposed interface to pass...
122e580952dSDimitry Andric char &llvm::LowerSwitchID = LowerSwitch::ID;
1232cab237bSDimitry Andric 
1242cab237bSDimitry Andric INITIALIZE_PASS(LowerSwitch, "lowerswitch",
1252cab237bSDimitry Andric                 "Lower SwitchInst's to branches", false, false)
1262cab237bSDimitry Andric 
127f22ef01cSRoman Divacky // createLowerSwitchPass - Interface to this file...
createLowerSwitchPass()128f22ef01cSRoman Divacky FunctionPass *llvm::createLowerSwitchPass() {
129f22ef01cSRoman Divacky   return new LowerSwitch();
130f22ef01cSRoman Divacky }
131f22ef01cSRoman Divacky 
runOnFunction(Function & F)132f22ef01cSRoman Divacky bool LowerSwitch::runOnFunction(Function &F) {
133f22ef01cSRoman Divacky   bool Changed = false;
1347d523365SDimitry Andric   SmallPtrSet<BasicBlock*, 8> DeleteList;
135f22ef01cSRoman Divacky 
136f22ef01cSRoman Divacky   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
1377d523365SDimitry Andric     BasicBlock *Cur = &*I++; // Advance over block so we don't traverse new blocks
1387d523365SDimitry Andric 
1397d523365SDimitry Andric     // If the block is a dead Default block that will be deleted later, don't
1407d523365SDimitry Andric     // waste time processing it.
1417d523365SDimitry Andric     if (DeleteList.count(Cur))
1427d523365SDimitry Andric       continue;
143f22ef01cSRoman Divacky 
144f22ef01cSRoman Divacky     if (SwitchInst *SI = dyn_cast<SwitchInst>(Cur->getTerminator())) {
145f22ef01cSRoman Divacky       Changed = true;
1467d523365SDimitry Andric       processSwitchInst(SI, DeleteList);
147f22ef01cSRoman Divacky     }
148f22ef01cSRoman Divacky   }
149f22ef01cSRoman Divacky 
1507d523365SDimitry Andric   for (BasicBlock* BB: DeleteList) {
1517d523365SDimitry Andric     DeleteDeadBlock(BB);
1527d523365SDimitry Andric   }
1537d523365SDimitry Andric 
154f22ef01cSRoman Divacky   return Changed;
155f22ef01cSRoman Divacky }
156f22ef01cSRoman Divacky 
1577d523365SDimitry Andric /// Used for debugging purposes.
1584ba319b5SDimitry Andric LLVM_ATTRIBUTE_USED
operator <<(raw_ostream & O,const LowerSwitch::CaseVector & C)159f22ef01cSRoman Divacky static raw_ostream &operator<<(raw_ostream &O,
160f22ef01cSRoman Divacky                                const LowerSwitch::CaseVector &C) {
161f22ef01cSRoman Divacky   O << "[";
162f22ef01cSRoman Divacky 
163f22ef01cSRoman Divacky   for (LowerSwitch::CaseVector::const_iterator B = C.begin(),
164f22ef01cSRoman Divacky          E = C.end(); B != E; ) {
165f22ef01cSRoman Divacky     O << *B->Low << " -" << *B->High;
166f22ef01cSRoman Divacky     if (++B != E) O << ", ";
167f22ef01cSRoman Divacky   }
168f22ef01cSRoman Divacky 
169f22ef01cSRoman Divacky   return O << "]";
170f22ef01cSRoman Divacky }
171f22ef01cSRoman Divacky 
1724ba319b5SDimitry Andric /// Update the first occurrence of the "switch statement" BB in the PHI
1737d523365SDimitry Andric /// node with the "new" BB. The other occurrences will:
1747d523365SDimitry Andric ///
1757d523365SDimitry Andric /// 1) Be updated by subsequent calls to this function.  Switch statements may
1767d523365SDimitry Andric /// have more than one outcoming edge into the same BB if they all have the same
1777d523365SDimitry Andric /// value. When the switch statement is converted these incoming edges are now
1787d523365SDimitry Andric /// coming from multiple BBs.
1797d523365SDimitry Andric /// 2) Removed if subsequent incoming values now share the same case, i.e.,
1807d523365SDimitry Andric /// multiple outcome edges are condensed into one. This is necessary to keep the
1817d523365SDimitry Andric /// number of phi values equal to the number of branches to SuccBB.
fixPhis(BasicBlock * SuccBB,BasicBlock * OrigBB,BasicBlock * NewBB,unsigned NumMergedCases)18239d628a0SDimitry Andric static void fixPhis(BasicBlock *SuccBB, BasicBlock *OrigBB, BasicBlock *NewBB,
18339d628a0SDimitry Andric                     unsigned NumMergedCases) {
1847d523365SDimitry Andric   for (BasicBlock::iterator I = SuccBB->begin(),
1857d523365SDimitry Andric                             IE = SuccBB->getFirstNonPHI()->getIterator();
18639d628a0SDimitry Andric        I != IE; ++I) {
18791bc56edSDimitry Andric     PHINode *PN = cast<PHINode>(I);
18891bc56edSDimitry Andric 
1897d523365SDimitry Andric     // Only update the first occurrence.
19039d628a0SDimitry Andric     unsigned Idx = 0, E = PN->getNumIncomingValues();
19139d628a0SDimitry Andric     unsigned LocalNumMergedCases = NumMergedCases;
19239d628a0SDimitry Andric     for (; Idx != E; ++Idx) {
19339d628a0SDimitry Andric       if (PN->getIncomingBlock(Idx) == OrigBB) {
19439d628a0SDimitry Andric         PN->setIncomingBlock(Idx, NewBB);
19539d628a0SDimitry Andric         break;
19639d628a0SDimitry Andric       }
19739d628a0SDimitry Andric     }
19839d628a0SDimitry Andric 
1997d523365SDimitry Andric     // Remove additional occurrences coming from condensed cases and keep the
20039d628a0SDimitry Andric     // number of incoming values equal to the number of branches to SuccBB.
201ff0cc061SDimitry Andric     SmallVector<unsigned, 8> Indices;
20239d628a0SDimitry Andric     for (++Idx; LocalNumMergedCases > 0 && Idx < E; ++Idx)
20339d628a0SDimitry Andric       if (PN->getIncomingBlock(Idx) == OrigBB) {
204ff0cc061SDimitry Andric         Indices.push_back(Idx);
20539d628a0SDimitry Andric         LocalNumMergedCases--;
20691bc56edSDimitry Andric       }
207ff0cc061SDimitry Andric     // Remove incoming values in the reverse order to prevent invalidating
208ff0cc061SDimitry Andric     // *successive* index.
2092cab237bSDimitry Andric     for (unsigned III : llvm::reverse(Indices))
2103ca95b02SDimitry Andric       PN->removeIncomingValue(III);
21191bc56edSDimitry Andric   }
21291bc56edSDimitry Andric }
21391bc56edSDimitry Andric 
2147d523365SDimitry Andric /// Convert the switch statement into a binary lookup of the case values.
2157d523365SDimitry Andric /// The function recursively builds this tree. LowerBound and UpperBound are
2167d523365SDimitry Andric /// used to keep track of the bounds for Val that have already been checked by
2177d523365SDimitry Andric /// a block emitted by one of the previous calls to switchConvert in the call
2187d523365SDimitry Andric /// stack.
219ff0cc061SDimitry Andric BasicBlock *
switchConvert(CaseItr Begin,CaseItr End,ConstantInt * LowerBound,ConstantInt * UpperBound,Value * Val,BasicBlock * Predecessor,BasicBlock * OrigBlock,BasicBlock * Default,const std::vector<IntRange> & UnreachableRanges)220ff0cc061SDimitry Andric LowerSwitch::switchConvert(CaseItr Begin, CaseItr End, ConstantInt *LowerBound,
22191bc56edSDimitry Andric                            ConstantInt *UpperBound, Value *Val,
222ff0cc061SDimitry Andric                            BasicBlock *Predecessor, BasicBlock *OrigBlock,
223ff0cc061SDimitry Andric                            BasicBlock *Default,
224ff0cc061SDimitry Andric                            const std::vector<IntRange> &UnreachableRanges) {
225f22ef01cSRoman Divacky   unsigned Size = End - Begin;
226f22ef01cSRoman Divacky 
22791bc56edSDimitry Andric   if (Size == 1) {
22891bc56edSDimitry Andric     // Check if the Case Range is perfectly squeezed in between
22991bc56edSDimitry Andric     // already checked Upper and Lower bounds. If it is then we can avoid
23091bc56edSDimitry Andric     // emitting the code that checks if the value actually falls in the range
23191bc56edSDimitry Andric     // because the bounds already tell us so.
23291bc56edSDimitry Andric     if (Begin->Low == LowerBound && Begin->High == UpperBound) {
23339d628a0SDimitry Andric       unsigned NumMergedCases = 0;
23439d628a0SDimitry Andric       if (LowerBound && UpperBound)
23539d628a0SDimitry Andric         NumMergedCases =
23639d628a0SDimitry Andric             UpperBound->getSExtValue() - LowerBound->getSExtValue();
23739d628a0SDimitry Andric       fixPhis(Begin->BB, OrigBlock, Predecessor, NumMergedCases);
23891bc56edSDimitry Andric       return Begin->BB;
23991bc56edSDimitry Andric     }
240f22ef01cSRoman Divacky     return newLeafBlock(*Begin, Val, OrigBlock, Default);
24191bc56edSDimitry Andric   }
242f22ef01cSRoman Divacky 
243f22ef01cSRoman Divacky   unsigned Mid = Size / 2;
244f22ef01cSRoman Divacky   std::vector<CaseRange> LHS(Begin, Begin + Mid);
2454ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LHS: " << LHS << "\n");
246f22ef01cSRoman Divacky   std::vector<CaseRange> RHS(Begin + Mid, End);
2474ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "RHS: " << RHS << "\n");
248f22ef01cSRoman Divacky 
249f22ef01cSRoman Divacky   CaseRange &Pivot = *(Begin + Mid);
2504ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Pivot ==> " << Pivot.Low->getValue() << " -"
2514ba319b5SDimitry Andric                     << Pivot.High->getValue() << "\n");
252f22ef01cSRoman Divacky 
25391bc56edSDimitry Andric   // NewLowerBound here should never be the integer minimal value.
25491bc56edSDimitry Andric   // This is because it is computed from a case range that is never
25591bc56edSDimitry Andric   // the smallest, so there is always a case range that has at least
25691bc56edSDimitry Andric   // a smaller value.
257ff0cc061SDimitry Andric   ConstantInt *NewLowerBound = Pivot.Low;
25891bc56edSDimitry Andric 
25991bc56edSDimitry Andric   // Because NewLowerBound is never the smallest representable integer
26091bc56edSDimitry Andric   // it is safe here to subtract one.
261ff0cc061SDimitry Andric   ConstantInt *NewUpperBound = ConstantInt::get(NewLowerBound->getContext(),
26291bc56edSDimitry Andric                                                 NewLowerBound->getValue() - 1);
263ff0cc061SDimitry Andric 
264ff0cc061SDimitry Andric   if (!UnreachableRanges.empty()) {
265ff0cc061SDimitry Andric     // Check if the gap between LHS's highest and NewLowerBound is unreachable.
266ff0cc061SDimitry Andric     int64_t GapLow = LHS.back().High->getSExtValue() + 1;
267ff0cc061SDimitry Andric     int64_t GapHigh = NewLowerBound->getSExtValue() - 1;
268ff0cc061SDimitry Andric     IntRange Gap = { GapLow, GapHigh };
269ff0cc061SDimitry Andric     if (GapHigh >= GapLow && IsInRanges(Gap, UnreachableRanges))
270ff0cc061SDimitry Andric       NewUpperBound = LHS.back().High;
27191bc56edSDimitry Andric   }
27291bc56edSDimitry Andric 
2734ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "LHS Bounds ==> "; if (LowerBound) {
274ff0cc061SDimitry Andric     dbgs() << LowerBound->getSExtValue();
2754ba319b5SDimitry Andric   } else { dbgs() << "NONE"; } dbgs() << " - "
2764ba319b5SDimitry Andric                                       << NewUpperBound->getSExtValue() << "\n";
27791bc56edSDimitry Andric              dbgs() << "RHS Bounds ==> ";
2784ba319b5SDimitry Andric              dbgs() << NewLowerBound->getSExtValue() << " - "; if (UpperBound) {
279ff0cc061SDimitry Andric                dbgs() << UpperBound->getSExtValue() << "\n";
2804ba319b5SDimitry Andric              } else { dbgs() << "NONE\n"; });
281f22ef01cSRoman Divacky 
282f22ef01cSRoman Divacky   // Create a new node that checks if the value is < pivot. Go to the
283f22ef01cSRoman Divacky   // left branch if it is and right branch if not.
284f22ef01cSRoman Divacky   Function* F = OrigBlock->getParent();
285f22ef01cSRoman Divacky   BasicBlock* NewNode = BasicBlock::Create(Val->getContext(), "NodeBlock");
286f22ef01cSRoman Divacky 
287f785676fSDimitry Andric   ICmpInst* Comp = new ICmpInst(ICmpInst::ICMP_SLT,
288f22ef01cSRoman Divacky                                 Val, Pivot.Low, "Pivot");
28991bc56edSDimitry Andric 
29091bc56edSDimitry Andric   BasicBlock *LBranch = switchConvert(LHS.begin(), LHS.end(), LowerBound,
29191bc56edSDimitry Andric                                       NewUpperBound, Val, NewNode, OrigBlock,
292ff0cc061SDimitry Andric                                       Default, UnreachableRanges);
29391bc56edSDimitry Andric   BasicBlock *RBranch = switchConvert(RHS.begin(), RHS.end(), NewLowerBound,
29491bc56edSDimitry Andric                                       UpperBound, Val, NewNode, OrigBlock,
295ff0cc061SDimitry Andric                                       Default, UnreachableRanges);
29691bc56edSDimitry Andric 
2977d523365SDimitry Andric   F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewNode);
298f22ef01cSRoman Divacky   NewNode->getInstList().push_back(Comp);
29991bc56edSDimitry Andric 
300f22ef01cSRoman Divacky   BranchInst::Create(LBranch, RBranch, Comp, NewNode);
301f22ef01cSRoman Divacky   return NewNode;
302f22ef01cSRoman Divacky }
303f22ef01cSRoman Divacky 
3047d523365SDimitry Andric /// Create a new leaf block for the binary lookup tree. It checks if the
3057d523365SDimitry Andric /// switch's value == the case's value. If not, then it jumps to the default
3067d523365SDimitry Andric /// branch. At this point in the tree, the value can't be another valid case
3077d523365SDimitry Andric /// value, so the jump to the "default" branch is warranted.
newLeafBlock(CaseRange & Leaf,Value * Val,BasicBlock * OrigBlock,BasicBlock * Default)308f22ef01cSRoman Divacky BasicBlock* LowerSwitch::newLeafBlock(CaseRange& Leaf, Value* Val,
309f22ef01cSRoman Divacky                                       BasicBlock* OrigBlock,
3102cab237bSDimitry Andric                                       BasicBlock* Default) {
311f22ef01cSRoman Divacky   Function* F = OrigBlock->getParent();
312f22ef01cSRoman Divacky   BasicBlock* NewLeaf = BasicBlock::Create(Val->getContext(), "LeafBlock");
3137d523365SDimitry Andric   F->getBasicBlockList().insert(++OrigBlock->getIterator(), NewLeaf);
314f22ef01cSRoman Divacky 
315f22ef01cSRoman Divacky   // Emit comparison
31691bc56edSDimitry Andric   ICmpInst* Comp = nullptr;
317f22ef01cSRoman Divacky   if (Leaf.Low == Leaf.High) {
318f22ef01cSRoman Divacky     // Make the seteq instruction...
319f22ef01cSRoman Divacky     Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_EQ, Val,
320f22ef01cSRoman Divacky                         Leaf.Low, "SwitchLeaf");
321f22ef01cSRoman Divacky   } else {
322f22ef01cSRoman Divacky     // Make range comparison
323ff0cc061SDimitry Andric     if (Leaf.Low->isMinValue(true /*isSigned*/)) {
324f22ef01cSRoman Divacky       // Val >= Min && Val <= Hi --> Val <= Hi
325f22ef01cSRoman Divacky       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_SLE, Val, Leaf.High,
326f22ef01cSRoman Divacky                           "SwitchLeaf");
327ff0cc061SDimitry Andric     } else if (Leaf.Low->isZero()) {
328f22ef01cSRoman Divacky       // Val >= 0 && Val <= Hi --> Val <=u Hi
329f22ef01cSRoman Divacky       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Val, Leaf.High,
330f22ef01cSRoman Divacky                           "SwitchLeaf");
331f22ef01cSRoman Divacky     } else {
332f22ef01cSRoman Divacky       // Emit V-Lo <=u Hi-Lo
333f22ef01cSRoman Divacky       Constant* NegLo = ConstantExpr::getNeg(Leaf.Low);
334f22ef01cSRoman Divacky       Instruction* Add = BinaryOperator::CreateAdd(Val, NegLo,
335f22ef01cSRoman Divacky                                                    Val->getName()+".off",
336f22ef01cSRoman Divacky                                                    NewLeaf);
337f22ef01cSRoman Divacky       Constant *UpperBound = ConstantExpr::getAdd(NegLo, Leaf.High);
338f22ef01cSRoman Divacky       Comp = new ICmpInst(*NewLeaf, ICmpInst::ICMP_ULE, Add, UpperBound,
339f22ef01cSRoman Divacky                           "SwitchLeaf");
340f22ef01cSRoman Divacky     }
341f22ef01cSRoman Divacky   }
342f22ef01cSRoman Divacky 
343f22ef01cSRoman Divacky   // Make the conditional branch...
344f22ef01cSRoman Divacky   BasicBlock* Succ = Leaf.BB;
345f22ef01cSRoman Divacky   BranchInst::Create(Succ, Default, Comp, NewLeaf);
346f22ef01cSRoman Divacky 
347f22ef01cSRoman Divacky   // If there were any PHI nodes in this successor, rewrite one entry
348f22ef01cSRoman Divacky   // from OrigBlock to come from NewLeaf.
349f22ef01cSRoman Divacky   for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
350f22ef01cSRoman Divacky     PHINode* PN = cast<PHINode>(I);
351f22ef01cSRoman Divacky     // Remove all but one incoming entries from the cluster
352ff0cc061SDimitry Andric     uint64_t Range = Leaf.High->getSExtValue() -
353ff0cc061SDimitry Andric                      Leaf.Low->getSExtValue();
354f22ef01cSRoman Divacky     for (uint64_t j = 0; j < Range; ++j) {
355f22ef01cSRoman Divacky       PN->removeIncomingValue(OrigBlock);
356f22ef01cSRoman Divacky     }
357f22ef01cSRoman Divacky 
358f22ef01cSRoman Divacky     int BlockIdx = PN->getBasicBlockIndex(OrigBlock);
359f22ef01cSRoman Divacky     assert(BlockIdx != -1 && "Switch didn't go to this successor??");
360f22ef01cSRoman Divacky     PN->setIncomingBlock((unsigned)BlockIdx, NewLeaf);
361f22ef01cSRoman Divacky   }
362f22ef01cSRoman Divacky 
363f22ef01cSRoman Divacky   return NewLeaf;
364f22ef01cSRoman Divacky }
365f22ef01cSRoman Divacky 
3667d523365SDimitry Andric /// Transform simple list of Cases into list of CaseRange's.
Clusterify(CaseVector & Cases,SwitchInst * SI)367f22ef01cSRoman Divacky unsigned LowerSwitch::Clusterify(CaseVector& Cases, SwitchInst *SI) {
368f785676fSDimitry Andric   unsigned numCmps = 0;
369f22ef01cSRoman Divacky 
370f22ef01cSRoman Divacky   // Start with "simple" cases
3717a7e6055SDimitry Andric   for (auto Case : SI->cases())
3727a7e6055SDimitry Andric     Cases.push_back(CaseRange(Case.getCaseValue(), Case.getCaseValue(),
3737a7e6055SDimitry Andric                               Case.getCaseSuccessor()));
374f785676fSDimitry Andric 
375*b5893f02SDimitry Andric   llvm::sort(Cases, CaseCmp());
376f785676fSDimitry Andric 
377f785676fSDimitry Andric   // Merge case into clusters
3788f0fd8f6SDimitry Andric   if (Cases.size() >= 2) {
3798f0fd8f6SDimitry Andric     CaseItr I = Cases.begin();
3808f0fd8f6SDimitry Andric     for (CaseItr J = std::next(I), E = Cases.end(); J != E; ++J) {
381ff0cc061SDimitry Andric       int64_t nextValue = J->Low->getSExtValue();
382ff0cc061SDimitry Andric       int64_t currentValue = I->High->getSExtValue();
383f785676fSDimitry Andric       BasicBlock* nextBB = J->BB;
384f785676fSDimitry Andric       BasicBlock* currentBB = I->BB;
385f785676fSDimitry Andric 
386f785676fSDimitry Andric       // If the two neighboring cases go to the same destination, merge them
387f785676fSDimitry Andric       // into a single case.
3888f0fd8f6SDimitry Andric       assert(nextValue > currentValue && "Cases should be strictly ascending");
3898f0fd8f6SDimitry Andric       if ((nextValue == currentValue + 1) && (currentBB == nextBB)) {
390f785676fSDimitry Andric         I->High = J->High;
3918f0fd8f6SDimitry Andric         // FIXME: Combine branch weights.
3928f0fd8f6SDimitry Andric       } else if (++I != J) {
3938f0fd8f6SDimitry Andric         *I = *J;
394f785676fSDimitry Andric       }
395f22ef01cSRoman Divacky     }
3968f0fd8f6SDimitry Andric     Cases.erase(std::next(I), Cases.end());
3978f0fd8f6SDimitry Andric   }
398f22ef01cSRoman Divacky 
399f785676fSDimitry Andric   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
400f785676fSDimitry Andric     if (I->Low != I->High)
401f22ef01cSRoman Divacky       // A range counts double, since it requires two compares.
402f22ef01cSRoman Divacky       ++numCmps;
403f22ef01cSRoman Divacky   }
404f22ef01cSRoman Divacky 
405f22ef01cSRoman Divacky   return numCmps;
406f22ef01cSRoman Divacky }
407f22ef01cSRoman Divacky 
4087d523365SDimitry Andric /// Replace the specified switch instruction with a sequence of chained if-then
4097d523365SDimitry Andric /// insts in a balanced binary search.
processSwitchInst(SwitchInst * SI,SmallPtrSetImpl<BasicBlock * > & DeleteList)4107d523365SDimitry Andric void LowerSwitch::processSwitchInst(SwitchInst *SI,
4117d523365SDimitry Andric                                     SmallPtrSetImpl<BasicBlock*> &DeleteList) {
412f22ef01cSRoman Divacky   BasicBlock *CurBlock = SI->getParent();
413f22ef01cSRoman Divacky   BasicBlock *OrigBlock = CurBlock;
414f22ef01cSRoman Divacky   Function *F = CurBlock->getParent();
4156122f3e6SDimitry Andric   Value *Val = SI->getCondition();  // The value we are switching on...
416f22ef01cSRoman Divacky   BasicBlock* Default = SI->getDefaultDest();
417f22ef01cSRoman Divacky 
41851690af2SDimitry Andric   // Don't handle unreachable blocks. If there are successors with phis, this
41951690af2SDimitry Andric   // would leave them behind with missing predecessors.
42051690af2SDimitry Andric   if ((CurBlock != &F->getEntryBlock() && pred_empty(CurBlock)) ||
42151690af2SDimitry Andric       CurBlock->getSinglePredecessor() == CurBlock) {
42251690af2SDimitry Andric     DeleteList.insert(CurBlock);
42351690af2SDimitry Andric     return;
42451690af2SDimitry Andric   }
42551690af2SDimitry Andric 
426ff0cc061SDimitry Andric   // If there is only the default destination, just branch.
427dff0c46cSDimitry Andric   if (!SI->getNumCases()) {
428ff0cc061SDimitry Andric     BranchInst::Create(Default, CurBlock);
429ff0cc061SDimitry Andric     SI->eraseFromParent();
430f22ef01cSRoman Divacky     return;
431f22ef01cSRoman Divacky   }
432f22ef01cSRoman Divacky 
433ff0cc061SDimitry Andric   // Prepare cases vector.
434ff0cc061SDimitry Andric   CaseVector Cases;
435ff0cc061SDimitry Andric   unsigned numCmps = Clusterify(Cases, SI);
4364ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
437ff0cc061SDimitry Andric                     << ". Total compares: " << numCmps << "\n");
4384ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Cases: " << Cases << "\n");
439ff0cc061SDimitry Andric   (void)numCmps;
440ff0cc061SDimitry Andric 
441ff0cc061SDimitry Andric   ConstantInt *LowerBound = nullptr;
442ff0cc061SDimitry Andric   ConstantInt *UpperBound = nullptr;
443ff0cc061SDimitry Andric   std::vector<IntRange> UnreachableRanges;
444ff0cc061SDimitry Andric 
445ff0cc061SDimitry Andric   if (isa<UnreachableInst>(Default->getFirstNonPHIOrDbg())) {
4467d523365SDimitry Andric     // Make the bounds tightly fitted around the case value range, because we
447ff0cc061SDimitry Andric     // know that the value passed to the switch must be exactly one of the case
448ff0cc061SDimitry Andric     // values.
449ff0cc061SDimitry Andric     assert(!Cases.empty());
450ff0cc061SDimitry Andric     LowerBound = Cases.front().Low;
451ff0cc061SDimitry Andric     UpperBound = Cases.back().High;
452ff0cc061SDimitry Andric 
453ff0cc061SDimitry Andric     DenseMap<BasicBlock *, unsigned> Popularity;
454ff0cc061SDimitry Andric     unsigned MaxPop = 0;
455ff0cc061SDimitry Andric     BasicBlock *PopSucc = nullptr;
456ff0cc061SDimitry Andric 
4572cab237bSDimitry Andric     IntRange R = {std::numeric_limits<int64_t>::min(),
4582cab237bSDimitry Andric                   std::numeric_limits<int64_t>::max()};
459ff0cc061SDimitry Andric     UnreachableRanges.push_back(R);
460ff0cc061SDimitry Andric     for (const auto &I : Cases) {
461ff0cc061SDimitry Andric       int64_t Low = I.Low->getSExtValue();
462ff0cc061SDimitry Andric       int64_t High = I.High->getSExtValue();
463ff0cc061SDimitry Andric 
464ff0cc061SDimitry Andric       IntRange &LastRange = UnreachableRanges.back();
465ff0cc061SDimitry Andric       if (LastRange.Low == Low) {
466ff0cc061SDimitry Andric         // There is nothing left of the previous range.
467ff0cc061SDimitry Andric         UnreachableRanges.pop_back();
468ff0cc061SDimitry Andric       } else {
469ff0cc061SDimitry Andric         // Terminate the previous range.
470ff0cc061SDimitry Andric         assert(Low > LastRange.Low);
471ff0cc061SDimitry Andric         LastRange.High = Low - 1;
472ff0cc061SDimitry Andric       }
4732cab237bSDimitry Andric       if (High != std::numeric_limits<int64_t>::max()) {
4742cab237bSDimitry Andric         IntRange R = { High + 1, std::numeric_limits<int64_t>::max() };
475ff0cc061SDimitry Andric         UnreachableRanges.push_back(R);
476ff0cc061SDimitry Andric       }
477ff0cc061SDimitry Andric 
478ff0cc061SDimitry Andric       // Count popularity.
479ff0cc061SDimitry Andric       int64_t N = High - Low + 1;
480ff0cc061SDimitry Andric       unsigned &Pop = Popularity[I.BB];
481ff0cc061SDimitry Andric       if ((Pop += N) > MaxPop) {
482ff0cc061SDimitry Andric         MaxPop = Pop;
483ff0cc061SDimitry Andric         PopSucc = I.BB;
484ff0cc061SDimitry Andric       }
485ff0cc061SDimitry Andric     }
486ff0cc061SDimitry Andric #ifndef NDEBUG
487ff0cc061SDimitry Andric     /* UnreachableRanges should be sorted and the ranges non-adjacent. */
488ff0cc061SDimitry Andric     for (auto I = UnreachableRanges.begin(), E = UnreachableRanges.end();
489ff0cc061SDimitry Andric          I != E; ++I) {
490ff0cc061SDimitry Andric       assert(I->Low <= I->High);
491ff0cc061SDimitry Andric       auto Next = I + 1;
492ff0cc061SDimitry Andric       if (Next != E) {
493ff0cc061SDimitry Andric         assert(Next->Low > I->High);
494ff0cc061SDimitry Andric       }
495ff0cc061SDimitry Andric     }
496ff0cc061SDimitry Andric #endif
497ff0cc061SDimitry Andric 
4984ba319b5SDimitry Andric     // As the default block in the switch is unreachable, update the PHI nodes
4994ba319b5SDimitry Andric     // (remove the entry to the default block) to reflect this.
5004ba319b5SDimitry Andric     Default->removePredecessor(OrigBlock);
5014ba319b5SDimitry Andric 
502ff0cc061SDimitry Andric     // Use the most popular block as the new default, reducing the number of
503ff0cc061SDimitry Andric     // cases.
504ff0cc061SDimitry Andric     assert(MaxPop > 0 && PopSucc);
505ff0cc061SDimitry Andric     Default = PopSucc;
506d88c1a5aSDimitry Andric     Cases.erase(
5072cab237bSDimitry Andric         llvm::remove_if(
5082cab237bSDimitry Andric             Cases, [PopSucc](const CaseRange &R) { return R.BB == PopSucc; }),
5098f0fd8f6SDimitry Andric         Cases.end());
510ff0cc061SDimitry Andric 
511ff0cc061SDimitry Andric     // If there are no cases left, just branch.
512ff0cc061SDimitry Andric     if (Cases.empty()) {
513ff0cc061SDimitry Andric       BranchInst::Create(Default, CurBlock);
514ff0cc061SDimitry Andric       SI->eraseFromParent();
5154ba319b5SDimitry Andric       // As all the cases have been replaced with a single branch, only keep
5164ba319b5SDimitry Andric       // one entry in the PHI nodes.
5174ba319b5SDimitry Andric       for (unsigned I = 0 ; I < (MaxPop - 1) ; ++I)
5184ba319b5SDimitry Andric         PopSucc->removePredecessor(OrigBlock);
519ff0cc061SDimitry Andric       return;
520ff0cc061SDimitry Andric     }
521ff0cc061SDimitry Andric   }
522ff0cc061SDimitry Andric 
5234ba319b5SDimitry Andric   unsigned NrOfDefaults = (SI->getDefaultDest() == Default) ? 1 : 0;
5244ba319b5SDimitry Andric   for (const auto &Case : SI->cases())
5254ba319b5SDimitry Andric     if (Case.getCaseSuccessor() == Default)
5264ba319b5SDimitry Andric       NrOfDefaults++;
5274ba319b5SDimitry Andric 
528f22ef01cSRoman Divacky   // Create a new, empty default block so that the new hierarchy of
529f22ef01cSRoman Divacky   // if-then statements go to this and the PHI nodes are happy.
530ff0cc061SDimitry Andric   BasicBlock *NewDefault = BasicBlock::Create(SI->getContext(), "NewDefault");
5317d523365SDimitry Andric   F->getBasicBlockList().insert(Default->getIterator(), NewDefault);
532f22ef01cSRoman Divacky   BranchInst::Create(Default, NewDefault);
533ff0cc061SDimitry Andric 
53491bc56edSDimitry Andric   BasicBlock *SwitchBlock =
53591bc56edSDimitry Andric       switchConvert(Cases.begin(), Cases.end(), LowerBound, UpperBound, Val,
536ff0cc061SDimitry Andric                     OrigBlock, OrigBlock, NewDefault, UnreachableRanges);
537f22ef01cSRoman Divacky 
5384ba319b5SDimitry Andric   // If there are entries in any PHI nodes for the default edge, make sure
5394ba319b5SDimitry Andric   // to update them as well.
5404ba319b5SDimitry Andric   fixPhis(Default, OrigBlock, NewDefault, NrOfDefaults);
5414ba319b5SDimitry Andric 
542f22ef01cSRoman Divacky   // Branch to our shiny new if-then stuff...
543f22ef01cSRoman Divacky   BranchInst::Create(SwitchBlock, OrigBlock);
544f22ef01cSRoman Divacky 
545f22ef01cSRoman Divacky   // We are now done with the switch instruction, delete it.
546ff0cc061SDimitry Andric   BasicBlock *OldDefault = SI->getDefaultDest();
547f22ef01cSRoman Divacky   CurBlock->getInstList().erase(SI);
54891bc56edSDimitry Andric 
5497d523365SDimitry Andric   // If the Default block has no more predecessors just add it to DeleteList.
550ff0cc061SDimitry Andric   if (pred_begin(OldDefault) == pred_end(OldDefault))
5517d523365SDimitry Andric     DeleteList.insert(OldDefault);
552f22ef01cSRoman Divacky }
553