10b57cec5SDimitry Andric //===- SwitchLoweringUtils.cpp - Switch Lowering --------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains switch inst lowering optimizations and utilities for
100b57cec5SDimitry Andric // codegen, so that it can be used for both SelectionDAG and GlobalISel.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/CodeGen/SwitchLoweringUtils.h"
15e8d8bef9SDimitry Andric #include "llvm/CodeGen/FunctionLoweringInfo.h"
16e8d8bef9SDimitry Andric #include "llvm/CodeGen/MachineJumpTableInfo.h"
17e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
185ffd83dbSDimitry Andric #include "llvm/Target/TargetMachine.h"
190b57cec5SDimitry Andric 
200b57cec5SDimitry Andric using namespace llvm;
210b57cec5SDimitry Andric using namespace SwitchCG;
220b57cec5SDimitry Andric 
getJumpTableRange(const CaseClusterVector & Clusters,unsigned First,unsigned Last)230b57cec5SDimitry Andric uint64_t SwitchCG::getJumpTableRange(const CaseClusterVector &Clusters,
240b57cec5SDimitry Andric                                      unsigned First, unsigned Last) {
250b57cec5SDimitry Andric   assert(Last >= First);
260b57cec5SDimitry Andric   const APInt &LowCase = Clusters[First].Low->getValue();
270b57cec5SDimitry Andric   const APInt &HighCase = Clusters[Last].High->getValue();
280b57cec5SDimitry Andric   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
290b57cec5SDimitry Andric 
300b57cec5SDimitry Andric   // FIXME: A range of consecutive cases has 100% density, but only requires one
310b57cec5SDimitry Andric   // comparison to lower. We should discriminate against such consecutive ranges
320b57cec5SDimitry Andric   // in jump tables.
330b57cec5SDimitry Andric   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
340b57cec5SDimitry Andric }
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric uint64_t
getJumpTableNumCases(const SmallVectorImpl<unsigned> & TotalCases,unsigned First,unsigned Last)370b57cec5SDimitry Andric SwitchCG::getJumpTableNumCases(const SmallVectorImpl<unsigned> &TotalCases,
380b57cec5SDimitry Andric                                unsigned First, unsigned Last) {
390b57cec5SDimitry Andric   assert(Last >= First);
400b57cec5SDimitry Andric   assert(TotalCases[Last] >= TotalCases[First]);
410b57cec5SDimitry Andric   uint64_t NumCases =
420b57cec5SDimitry Andric       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
430b57cec5SDimitry Andric   return NumCases;
440b57cec5SDimitry Andric }
450b57cec5SDimitry Andric 
findJumpTables(CaseClusterVector & Clusters,const SwitchInst * SI,std::optional<SDLoc> SL,MachineBasicBlock * DefaultMBB,ProfileSummaryInfo * PSI,BlockFrequencyInfo * BFI)460b57cec5SDimitry Andric void SwitchCG::SwitchLowering::findJumpTables(CaseClusterVector &Clusters,
470b57cec5SDimitry Andric                                               const SwitchInst *SI,
48c9157d92SDimitry Andric                                               std::optional<SDLoc> SL,
49480093f4SDimitry Andric                                               MachineBasicBlock *DefaultMBB,
50480093f4SDimitry Andric                                               ProfileSummaryInfo *PSI,
51480093f4SDimitry Andric                                               BlockFrequencyInfo *BFI) {
520b57cec5SDimitry Andric #ifndef NDEBUG
530b57cec5SDimitry Andric   // Clusters must be non-empty, sorted, and only contain Range clusters.
540b57cec5SDimitry Andric   assert(!Clusters.empty());
550b57cec5SDimitry Andric   for (CaseCluster &C : Clusters)
560b57cec5SDimitry Andric     assert(C.Kind == CC_Range);
570b57cec5SDimitry Andric   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
580b57cec5SDimitry Andric     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
590b57cec5SDimitry Andric #endif
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric   assert(TLI && "TLI not set!");
620b57cec5SDimitry Andric   if (!TLI->areJTsAllowed(SI->getParent()->getParent()))
630b57cec5SDimitry Andric     return;
640b57cec5SDimitry Andric 
650b57cec5SDimitry Andric   const unsigned MinJumpTableEntries = TLI->getMinimumJumpTableEntries();
660b57cec5SDimitry Andric   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric   // Bail if not enough cases.
690b57cec5SDimitry Andric   const int64_t N = Clusters.size();
700b57cec5SDimitry Andric   if (N < 2 || N < MinJumpTableEntries)
710b57cec5SDimitry Andric     return;
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric   // Accumulated number of cases in each cluster and those prior to it.
740b57cec5SDimitry Andric   SmallVector<unsigned, 8> TotalCases(N);
750b57cec5SDimitry Andric   for (unsigned i = 0; i < N; ++i) {
760b57cec5SDimitry Andric     const APInt &Hi = Clusters[i].High->getValue();
770b57cec5SDimitry Andric     const APInt &Lo = Clusters[i].Low->getValue();
780b57cec5SDimitry Andric     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
790b57cec5SDimitry Andric     if (i != 0)
800b57cec5SDimitry Andric       TotalCases[i] += TotalCases[i - 1];
810b57cec5SDimitry Andric   }
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
840b57cec5SDimitry Andric   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
850b57cec5SDimitry Andric   assert(NumCases < UINT64_MAX / 100);
860b57cec5SDimitry Andric   assert(Range >= NumCases);
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric   // Cheap case: the whole range may be suitable for jump table.
89480093f4SDimitry Andric   if (TLI->isSuitableForJumpTable(SI, NumCases, Range, PSI, BFI)) {
900b57cec5SDimitry Andric     CaseCluster JTCluster;
91c9157d92SDimitry Andric     if (buildJumpTable(Clusters, 0, N - 1, SI, SL, DefaultMBB, JTCluster)) {
920b57cec5SDimitry Andric       Clusters[0] = JTCluster;
930b57cec5SDimitry Andric       Clusters.resize(1);
940b57cec5SDimitry Andric       return;
950b57cec5SDimitry Andric     }
960b57cec5SDimitry Andric   }
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric   // The algorithm below is not suitable for -O0.
99c9157d92SDimitry Andric   if (TM->getOptLevel() == CodeGenOptLevel::None)
1000b57cec5SDimitry Andric     return;
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric   // Split Clusters into minimum number of dense partitions. The algorithm uses
1030b57cec5SDimitry Andric   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
1040b57cec5SDimitry Andric   // for the Case Statement'" (1994), but builds the MinPartitions array in
1050b57cec5SDimitry Andric   // reverse order to make it easier to reconstruct the partitions in ascending
1060b57cec5SDimitry Andric   // order. In the choice between two optimal partitionings, it picks the one
1070b57cec5SDimitry Andric   // which yields more jump tables.
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
1100b57cec5SDimitry Andric   SmallVector<unsigned, 8> MinPartitions(N);
1110b57cec5SDimitry Andric   // LastElement[i] is the last element of the partition starting at i.
1120b57cec5SDimitry Andric   SmallVector<unsigned, 8> LastElement(N);
1130b57cec5SDimitry Andric   // PartitionsScore[i] is used to break ties when choosing between two
1140b57cec5SDimitry Andric   // partitionings resulting in the same number of partitions.
1150b57cec5SDimitry Andric   SmallVector<unsigned, 8> PartitionsScore(N);
1160b57cec5SDimitry Andric   // For PartitionsScore, a small number of comparisons is considered as good as
1170b57cec5SDimitry Andric   // a jump table and a single comparison is considered better than a jump
1180b57cec5SDimitry Andric   // table.
1190b57cec5SDimitry Andric   enum PartitionScores : unsigned {
1200b57cec5SDimitry Andric     NoTable = 0,
1210b57cec5SDimitry Andric     Table = 1,
1220b57cec5SDimitry Andric     FewCases = 1,
1230b57cec5SDimitry Andric     SingleCase = 2
1240b57cec5SDimitry Andric   };
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric   // Base case: There is only one way to partition Clusters[N-1].
1270b57cec5SDimitry Andric   MinPartitions[N - 1] = 1;
1280b57cec5SDimitry Andric   LastElement[N - 1] = N - 1;
1290b57cec5SDimitry Andric   PartitionsScore[N - 1] = PartitionScores::SingleCase;
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric   // Note: loop indexes are signed to avoid underflow.
1320b57cec5SDimitry Andric   for (int64_t i = N - 2; i >= 0; i--) {
1330b57cec5SDimitry Andric     // Find optimal partitioning of Clusters[i..N-1].
1340b57cec5SDimitry Andric     // Baseline: Put Clusters[i] into a partition on its own.
1350b57cec5SDimitry Andric     MinPartitions[i] = MinPartitions[i + 1] + 1;
1360b57cec5SDimitry Andric     LastElement[i] = i;
1370b57cec5SDimitry Andric     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric     // Search for a solution that results in fewer partitions.
1400b57cec5SDimitry Andric     for (int64_t j = N - 1; j > i; j--) {
1410b57cec5SDimitry Andric       // Try building a partition from Clusters[i..j].
1420b57cec5SDimitry Andric       Range = getJumpTableRange(Clusters, i, j);
1430b57cec5SDimitry Andric       NumCases = getJumpTableNumCases(TotalCases, i, j);
1440b57cec5SDimitry Andric       assert(NumCases < UINT64_MAX / 100);
1450b57cec5SDimitry Andric       assert(Range >= NumCases);
1460b57cec5SDimitry Andric 
147480093f4SDimitry Andric       if (TLI->isSuitableForJumpTable(SI, NumCases, Range, PSI, BFI)) {
1480b57cec5SDimitry Andric         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
1490b57cec5SDimitry Andric         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
1500b57cec5SDimitry Andric         int64_t NumEntries = j - i + 1;
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric         if (NumEntries == 1)
1530b57cec5SDimitry Andric           Score += PartitionScores::SingleCase;
1540b57cec5SDimitry Andric         else if (NumEntries <= SmallNumberOfEntries)
1550b57cec5SDimitry Andric           Score += PartitionScores::FewCases;
1560b57cec5SDimitry Andric         else if (NumEntries >= MinJumpTableEntries)
1570b57cec5SDimitry Andric           Score += PartitionScores::Table;
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric         // If this leads to fewer partitions, or to the same number of
1600b57cec5SDimitry Andric         // partitions with better score, it is a better partitioning.
1610b57cec5SDimitry Andric         if (NumPartitions < MinPartitions[i] ||
1620b57cec5SDimitry Andric             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
1630b57cec5SDimitry Andric           MinPartitions[i] = NumPartitions;
1640b57cec5SDimitry Andric           LastElement[i] = j;
1650b57cec5SDimitry Andric           PartitionsScore[i] = Score;
1660b57cec5SDimitry Andric         }
1670b57cec5SDimitry Andric       }
1680b57cec5SDimitry Andric     }
1690b57cec5SDimitry Andric   }
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric   // Iterate over the partitions, replacing some with jump tables in-place.
1720b57cec5SDimitry Andric   unsigned DstIndex = 0;
1730b57cec5SDimitry Andric   for (unsigned First = 0, Last; First < N; First = Last + 1) {
1740b57cec5SDimitry Andric     Last = LastElement[First];
1750b57cec5SDimitry Andric     assert(Last >= First);
1760b57cec5SDimitry Andric     assert(DstIndex <= First);
1770b57cec5SDimitry Andric     unsigned NumClusters = Last - First + 1;
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric     CaseCluster JTCluster;
1800b57cec5SDimitry Andric     if (NumClusters >= MinJumpTableEntries &&
181c9157d92SDimitry Andric         buildJumpTable(Clusters, First, Last, SI, SL, DefaultMBB, JTCluster)) {
1820b57cec5SDimitry Andric       Clusters[DstIndex++] = JTCluster;
1830b57cec5SDimitry Andric     } else {
1840b57cec5SDimitry Andric       for (unsigned I = First; I <= Last; ++I)
1850b57cec5SDimitry Andric         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
1860b57cec5SDimitry Andric     }
1870b57cec5SDimitry Andric   }
1880b57cec5SDimitry Andric   Clusters.resize(DstIndex);
1890b57cec5SDimitry Andric }
1900b57cec5SDimitry Andric 
buildJumpTable(const CaseClusterVector & Clusters,unsigned First,unsigned Last,const SwitchInst * SI,const std::optional<SDLoc> & SL,MachineBasicBlock * DefaultMBB,CaseCluster & JTCluster)1910b57cec5SDimitry Andric bool SwitchCG::SwitchLowering::buildJumpTable(const CaseClusterVector &Clusters,
1920b57cec5SDimitry Andric                                               unsigned First, unsigned Last,
1930b57cec5SDimitry Andric                                               const SwitchInst *SI,
194c9157d92SDimitry Andric                                               const std::optional<SDLoc> &SL,
1950b57cec5SDimitry Andric                                               MachineBasicBlock *DefaultMBB,
1960b57cec5SDimitry Andric                                               CaseCluster &JTCluster) {
1970b57cec5SDimitry Andric   assert(First <= Last);
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric   auto Prob = BranchProbability::getZero();
2000b57cec5SDimitry Andric   unsigned NumCmps = 0;
2010b57cec5SDimitry Andric   std::vector<MachineBasicBlock*> Table;
2020b57cec5SDimitry Andric   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   // Initialize probabilities in JTProbs.
2050b57cec5SDimitry Andric   for (unsigned I = First; I <= Last; ++I)
2060b57cec5SDimitry Andric     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
2070b57cec5SDimitry Andric 
2080b57cec5SDimitry Andric   for (unsigned I = First; I <= Last; ++I) {
2090b57cec5SDimitry Andric     assert(Clusters[I].Kind == CC_Range);
2100b57cec5SDimitry Andric     Prob += Clusters[I].Prob;
2110b57cec5SDimitry Andric     const APInt &Low = Clusters[I].Low->getValue();
2120b57cec5SDimitry Andric     const APInt &High = Clusters[I].High->getValue();
2130b57cec5SDimitry Andric     NumCmps += (Low == High) ? 1 : 2;
2140b57cec5SDimitry Andric     if (I != First) {
2150b57cec5SDimitry Andric       // Fill the gap between this and the previous cluster.
2160b57cec5SDimitry Andric       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
2170b57cec5SDimitry Andric       assert(PreviousHigh.slt(Low));
2180b57cec5SDimitry Andric       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
2190b57cec5SDimitry Andric       for (uint64_t J = 0; J < Gap; J++)
2200b57cec5SDimitry Andric         Table.push_back(DefaultMBB);
2210b57cec5SDimitry Andric     }
2220b57cec5SDimitry Andric     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
2230b57cec5SDimitry Andric     for (uint64_t J = 0; J < ClusterSize; ++J)
2240b57cec5SDimitry Andric       Table.push_back(Clusters[I].MBB);
2250b57cec5SDimitry Andric     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
2260b57cec5SDimitry Andric   }
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric   unsigned NumDests = JTProbs.size();
2290b57cec5SDimitry Andric   if (TLI->isSuitableForBitTests(NumDests, NumCmps,
2300b57cec5SDimitry Andric                                  Clusters[First].Low->getValue(),
2310b57cec5SDimitry Andric                                  Clusters[Last].High->getValue(), *DL)) {
2320b57cec5SDimitry Andric     // Clusters[First..Last] should be lowered as bit tests instead.
2330b57cec5SDimitry Andric     return false;
2340b57cec5SDimitry Andric   }
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric   // Create the MBB that will load from and jump through the table.
2370b57cec5SDimitry Andric   // Note: We create it here, but it's not inserted into the function yet.
2380b57cec5SDimitry Andric   MachineFunction *CurMF = FuncInfo.MF;
2390b57cec5SDimitry Andric   MachineBasicBlock *JumpTableMBB =
2400b57cec5SDimitry Andric       CurMF->CreateMachineBasicBlock(SI->getParent());
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric   // Add successors. Note: use table order for determinism.
2430b57cec5SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 8> Done;
2440b57cec5SDimitry Andric   for (MachineBasicBlock *Succ : Table) {
2450b57cec5SDimitry Andric     if (Done.count(Succ))
2460b57cec5SDimitry Andric       continue;
2470b57cec5SDimitry Andric     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
2480b57cec5SDimitry Andric     Done.insert(Succ);
2490b57cec5SDimitry Andric   }
2500b57cec5SDimitry Andric   JumpTableMBB->normalizeSuccProbs();
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI->getJumpTableEncoding())
2530b57cec5SDimitry Andric                      ->createJumpTableIndex(Table);
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   // Set up the jump table info.
256c9157d92SDimitry Andric   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr, SL);
2570b57cec5SDimitry Andric   JumpTableHeader JTH(Clusters[First].Low->getValue(),
2580b57cec5SDimitry Andric                       Clusters[Last].High->getValue(), SI->getCondition(),
2590b57cec5SDimitry Andric                       nullptr, false);
2600b57cec5SDimitry Andric   JTCases.emplace_back(std::move(JTH), std::move(JT));
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
2630b57cec5SDimitry Andric                                      JTCases.size() - 1, Prob);
2640b57cec5SDimitry Andric   return true;
2650b57cec5SDimitry Andric }
2660b57cec5SDimitry Andric 
findBitTestClusters(CaseClusterVector & Clusters,const SwitchInst * SI)2670b57cec5SDimitry Andric void SwitchCG::SwitchLowering::findBitTestClusters(CaseClusterVector &Clusters,
2680b57cec5SDimitry Andric                                                    const SwitchInst *SI) {
2690b57cec5SDimitry Andric   // Partition Clusters into as few subsets as possible, where each subset has a
2700b57cec5SDimitry Andric   // range that fits in a machine word and has <= 3 unique destinations.
2710b57cec5SDimitry Andric 
2720b57cec5SDimitry Andric #ifndef NDEBUG
2730b57cec5SDimitry Andric   // Clusters must be sorted and contain Range or JumpTable clusters.
2740b57cec5SDimitry Andric   assert(!Clusters.empty());
2750b57cec5SDimitry Andric   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
2760b57cec5SDimitry Andric   for (const CaseCluster &C : Clusters)
2770b57cec5SDimitry Andric     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
2780b57cec5SDimitry Andric   for (unsigned i = 1; i < Clusters.size(); ++i)
2790b57cec5SDimitry Andric     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
2800b57cec5SDimitry Andric #endif
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric   // The algorithm below is not suitable for -O0.
283c9157d92SDimitry Andric   if (TM->getOptLevel() == CodeGenOptLevel::None)
2840b57cec5SDimitry Andric     return;
2850b57cec5SDimitry Andric 
2860b57cec5SDimitry Andric   // If target does not have legal shift left, do not emit bit tests at all.
2870b57cec5SDimitry Andric   EVT PTy = TLI->getPointerTy(*DL);
2880b57cec5SDimitry Andric   if (!TLI->isOperationLegal(ISD::SHL, PTy))
2890b57cec5SDimitry Andric     return;
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   int BitWidth = PTy.getSizeInBits();
2920b57cec5SDimitry Andric   const int64_t N = Clusters.size();
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
2950b57cec5SDimitry Andric   SmallVector<unsigned, 8> MinPartitions(N);
2960b57cec5SDimitry Andric   // LastElement[i] is the last element of the partition starting at i.
2970b57cec5SDimitry Andric   SmallVector<unsigned, 8> LastElement(N);
2980b57cec5SDimitry Andric 
2990b57cec5SDimitry Andric   // FIXME: This might not be the best algorithm for finding bit test clusters.
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   // Base case: There is only one way to partition Clusters[N-1].
3020b57cec5SDimitry Andric   MinPartitions[N - 1] = 1;
3030b57cec5SDimitry Andric   LastElement[N - 1] = N - 1;
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric   // Note: loop indexes are signed to avoid underflow.
3060b57cec5SDimitry Andric   for (int64_t i = N - 2; i >= 0; --i) {
3070b57cec5SDimitry Andric     // Find optimal partitioning of Clusters[i..N-1].
3080b57cec5SDimitry Andric     // Baseline: Put Clusters[i] into a partition on its own.
3090b57cec5SDimitry Andric     MinPartitions[i] = MinPartitions[i + 1] + 1;
3100b57cec5SDimitry Andric     LastElement[i] = i;
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric     // Search for a solution that results in fewer partitions.
3130b57cec5SDimitry Andric     // Note: the search is limited by BitWidth, reducing time complexity.
3140b57cec5SDimitry Andric     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
3150b57cec5SDimitry Andric       // Try building a partition from Clusters[i..j].
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric       // Check the range.
3180b57cec5SDimitry Andric       if (!TLI->rangeFitsInWord(Clusters[i].Low->getValue(),
3190b57cec5SDimitry Andric                                 Clusters[j].High->getValue(), *DL))
3200b57cec5SDimitry Andric         continue;
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric       // Check nbr of destinations and cluster types.
3230b57cec5SDimitry Andric       // FIXME: This works, but doesn't seem very efficient.
3240b57cec5SDimitry Andric       bool RangesOnly = true;
3250b57cec5SDimitry Andric       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
3260b57cec5SDimitry Andric       for (int64_t k = i; k <= j; k++) {
3270b57cec5SDimitry Andric         if (Clusters[k].Kind != CC_Range) {
3280b57cec5SDimitry Andric           RangesOnly = false;
3290b57cec5SDimitry Andric           break;
3300b57cec5SDimitry Andric         }
3310b57cec5SDimitry Andric         Dests.set(Clusters[k].MBB->getNumber());
3320b57cec5SDimitry Andric       }
3330b57cec5SDimitry Andric       if (!RangesOnly || Dests.count() > 3)
3340b57cec5SDimitry Andric         break;
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric       // Check if it's a better partition.
3370b57cec5SDimitry Andric       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
3380b57cec5SDimitry Andric       if (NumPartitions < MinPartitions[i]) {
3390b57cec5SDimitry Andric         // Found a better partition.
3400b57cec5SDimitry Andric         MinPartitions[i] = NumPartitions;
3410b57cec5SDimitry Andric         LastElement[i] = j;
3420b57cec5SDimitry Andric       }
3430b57cec5SDimitry Andric     }
3440b57cec5SDimitry Andric   }
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric   // Iterate over the partitions, replacing with bit-test clusters in-place.
3470b57cec5SDimitry Andric   unsigned DstIndex = 0;
3480b57cec5SDimitry Andric   for (unsigned First = 0, Last; First < N; First = Last + 1) {
3490b57cec5SDimitry Andric     Last = LastElement[First];
3500b57cec5SDimitry Andric     assert(First <= Last);
3510b57cec5SDimitry Andric     assert(DstIndex <= First);
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric     CaseCluster BitTestCluster;
3540b57cec5SDimitry Andric     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
3550b57cec5SDimitry Andric       Clusters[DstIndex++] = BitTestCluster;
3560b57cec5SDimitry Andric     } else {
3570b57cec5SDimitry Andric       size_t NumClusters = Last - First + 1;
3580b57cec5SDimitry Andric       std::memmove(&Clusters[DstIndex], &Clusters[First],
3590b57cec5SDimitry Andric                    sizeof(Clusters[0]) * NumClusters);
3600b57cec5SDimitry Andric       DstIndex += NumClusters;
3610b57cec5SDimitry Andric     }
3620b57cec5SDimitry Andric   }
3630b57cec5SDimitry Andric   Clusters.resize(DstIndex);
3640b57cec5SDimitry Andric }
3650b57cec5SDimitry Andric 
buildBitTests(CaseClusterVector & Clusters,unsigned First,unsigned Last,const SwitchInst * SI,CaseCluster & BTCluster)3660b57cec5SDimitry Andric bool SwitchCG::SwitchLowering::buildBitTests(CaseClusterVector &Clusters,
3670b57cec5SDimitry Andric                                              unsigned First, unsigned Last,
3680b57cec5SDimitry Andric                                              const SwitchInst *SI,
3690b57cec5SDimitry Andric                                              CaseCluster &BTCluster) {
3700b57cec5SDimitry Andric   assert(First <= Last);
3710b57cec5SDimitry Andric   if (First == Last)
3720b57cec5SDimitry Andric     return false;
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
3750b57cec5SDimitry Andric   unsigned NumCmps = 0;
3760b57cec5SDimitry Andric   for (int64_t I = First; I <= Last; ++I) {
3770b57cec5SDimitry Andric     assert(Clusters[I].Kind == CC_Range);
3780b57cec5SDimitry Andric     Dests.set(Clusters[I].MBB->getNumber());
3790b57cec5SDimitry Andric     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
3800b57cec5SDimitry Andric   }
3810b57cec5SDimitry Andric   unsigned NumDests = Dests.count();
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   APInt Low = Clusters[First].Low->getValue();
3840b57cec5SDimitry Andric   APInt High = Clusters[Last].High->getValue();
3850b57cec5SDimitry Andric   assert(Low.slt(High));
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric   if (!TLI->isSuitableForBitTests(NumDests, NumCmps, Low, High, *DL))
3880b57cec5SDimitry Andric     return false;
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   APInt LowBound;
3910b57cec5SDimitry Andric   APInt CmpRange;
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   const int BitWidth = TLI->getPointerTy(*DL).getSizeInBits();
3940b57cec5SDimitry Andric   assert(TLI->rangeFitsInWord(Low, High, *DL) &&
3950b57cec5SDimitry Andric          "Case range must fit in bit mask!");
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric   // Check if the clusters cover a contiguous range such that no value in the
3980b57cec5SDimitry Andric   // range will jump to the default statement.
3990b57cec5SDimitry Andric   bool ContiguousRange = true;
4000b57cec5SDimitry Andric   for (int64_t I = First + 1; I <= Last; ++I) {
4010b57cec5SDimitry Andric     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
4020b57cec5SDimitry Andric       ContiguousRange = false;
4030b57cec5SDimitry Andric       break;
4040b57cec5SDimitry Andric     }
4050b57cec5SDimitry Andric   }
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
4080b57cec5SDimitry Andric     // Optimize the case where all the case values fit in a word without having
4090b57cec5SDimitry Andric     // to subtract minValue. In this case, we can optimize away the subtraction.
410349cc55cSDimitry Andric     LowBound = APInt::getZero(Low.getBitWidth());
4110b57cec5SDimitry Andric     CmpRange = High;
4120b57cec5SDimitry Andric     ContiguousRange = false;
4130b57cec5SDimitry Andric   } else {
4140b57cec5SDimitry Andric     LowBound = Low;
4150b57cec5SDimitry Andric     CmpRange = High - Low;
4160b57cec5SDimitry Andric   }
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric   CaseBitsVector CBV;
4190b57cec5SDimitry Andric   auto TotalProb = BranchProbability::getZero();
4200b57cec5SDimitry Andric   for (unsigned i = First; i <= Last; ++i) {
4210b57cec5SDimitry Andric     // Find the CaseBits for this destination.
4220b57cec5SDimitry Andric     unsigned j;
4230b57cec5SDimitry Andric     for (j = 0; j < CBV.size(); ++j)
4240b57cec5SDimitry Andric       if (CBV[j].BB == Clusters[i].MBB)
4250b57cec5SDimitry Andric         break;
4260b57cec5SDimitry Andric     if (j == CBV.size())
4270b57cec5SDimitry Andric       CBV.push_back(
4280b57cec5SDimitry Andric           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
4290b57cec5SDimitry Andric     CaseBits *CB = &CBV[j];
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric     // Update Mask, Bits and ExtraProb.
4320b57cec5SDimitry Andric     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
4330b57cec5SDimitry Andric     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
4340b57cec5SDimitry Andric     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
4350b57cec5SDimitry Andric     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
4360b57cec5SDimitry Andric     CB->Bits += Hi - Lo + 1;
4370b57cec5SDimitry Andric     CB->ExtraProb += Clusters[i].Prob;
4380b57cec5SDimitry Andric     TotalProb += Clusters[i].Prob;
4390b57cec5SDimitry Andric   }
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   BitTestInfo BTI;
4420b57cec5SDimitry Andric   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
4430b57cec5SDimitry Andric     // Sort by probability first, number of bits second, bit mask third.
4440b57cec5SDimitry Andric     if (a.ExtraProb != b.ExtraProb)
4450b57cec5SDimitry Andric       return a.ExtraProb > b.ExtraProb;
4460b57cec5SDimitry Andric     if (a.Bits != b.Bits)
4470b57cec5SDimitry Andric       return a.Bits > b.Bits;
4480b57cec5SDimitry Andric     return a.Mask < b.Mask;
4490b57cec5SDimitry Andric   });
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric   for (auto &CB : CBV) {
4520b57cec5SDimitry Andric     MachineBasicBlock *BitTestBB =
4530b57cec5SDimitry Andric         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
4540b57cec5SDimitry Andric     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
4550b57cec5SDimitry Andric   }
4560b57cec5SDimitry Andric   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
4570b57cec5SDimitry Andric                             SI->getCondition(), -1U, MVT::Other, false,
4580b57cec5SDimitry Andric                             ContiguousRange, nullptr, nullptr, std::move(BTI),
4590b57cec5SDimitry Andric                             TotalProb);
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
4620b57cec5SDimitry Andric                                     BitTestCases.size() - 1, TotalProb);
4630b57cec5SDimitry Andric   return true;
4640b57cec5SDimitry Andric }
4650b57cec5SDimitry Andric 
sortAndRangeify(CaseClusterVector & Clusters)4660b57cec5SDimitry Andric void SwitchCG::sortAndRangeify(CaseClusterVector &Clusters) {
4670b57cec5SDimitry Andric #ifndef NDEBUG
4680b57cec5SDimitry Andric   for (const CaseCluster &CC : Clusters)
4690b57cec5SDimitry Andric     assert(CC.Low == CC.High && "Input clusters must be single-case");
4700b57cec5SDimitry Andric #endif
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
4730b57cec5SDimitry Andric     return a.Low->getValue().slt(b.Low->getValue());
4740b57cec5SDimitry Andric   });
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric   // Merge adjacent clusters with the same destination.
4770b57cec5SDimitry Andric   const unsigned N = Clusters.size();
4780b57cec5SDimitry Andric   unsigned DstIndex = 0;
4790b57cec5SDimitry Andric   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
4800b57cec5SDimitry Andric     CaseCluster &CC = Clusters[SrcIndex];
4810b57cec5SDimitry Andric     const ConstantInt *CaseVal = CC.Low;
4820b57cec5SDimitry Andric     MachineBasicBlock *Succ = CC.MBB;
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
4850b57cec5SDimitry Andric         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
4860b57cec5SDimitry Andric       // If this case has the same successor and is a neighbour, merge it into
4870b57cec5SDimitry Andric       // the previous cluster.
4880b57cec5SDimitry Andric       Clusters[DstIndex - 1].High = CaseVal;
4890b57cec5SDimitry Andric       Clusters[DstIndex - 1].Prob += CC.Prob;
4900b57cec5SDimitry Andric     } else {
4910b57cec5SDimitry Andric       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
4920b57cec5SDimitry Andric                    sizeof(Clusters[SrcIndex]));
4930b57cec5SDimitry Andric     }
4940b57cec5SDimitry Andric   }
4950b57cec5SDimitry Andric   Clusters.resize(DstIndex);
4960b57cec5SDimitry Andric }
497*cdc20ff6SDimitry Andric 
caseClusterRank(const CaseCluster & CC,CaseClusterIt First,CaseClusterIt Last)498*cdc20ff6SDimitry Andric unsigned SwitchCG::SwitchLowering::caseClusterRank(const CaseCluster &CC,
499*cdc20ff6SDimitry Andric                                                    CaseClusterIt First,
500*cdc20ff6SDimitry Andric                                                    CaseClusterIt Last) {
501*cdc20ff6SDimitry Andric   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
502*cdc20ff6SDimitry Andric     if (X.Prob != CC.Prob)
503*cdc20ff6SDimitry Andric       return X.Prob > CC.Prob;
504*cdc20ff6SDimitry Andric 
505*cdc20ff6SDimitry Andric     // Ties are broken by comparing the case value.
506*cdc20ff6SDimitry Andric     return X.Low->getValue().slt(CC.Low->getValue());
507*cdc20ff6SDimitry Andric   });
508*cdc20ff6SDimitry Andric }
509*cdc20ff6SDimitry Andric 
510*cdc20ff6SDimitry Andric llvm::SwitchCG::SwitchLowering::SplitWorkItemInfo
computeSplitWorkItemInfo(const SwitchWorkListItem & W)511*cdc20ff6SDimitry Andric SwitchCG::SwitchLowering::computeSplitWorkItemInfo(
512*cdc20ff6SDimitry Andric     const SwitchWorkListItem &W) {
513*cdc20ff6SDimitry Andric   CaseClusterIt LastLeft = W.FirstCluster;
514*cdc20ff6SDimitry Andric   CaseClusterIt FirstRight = W.LastCluster;
515*cdc20ff6SDimitry Andric   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
516*cdc20ff6SDimitry Andric   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
517*cdc20ff6SDimitry Andric 
518*cdc20ff6SDimitry Andric   // Move LastLeft and FirstRight towards each other from opposite directions to
519*cdc20ff6SDimitry Andric   // find a partitioning of the clusters which balances the probability on both
520*cdc20ff6SDimitry Andric   // sides. If LeftProb and RightProb are equal, alternate which side is
521*cdc20ff6SDimitry Andric   // taken to ensure 0-probability nodes are distributed evenly.
522*cdc20ff6SDimitry Andric   unsigned I = 0;
523*cdc20ff6SDimitry Andric   while (LastLeft + 1 < FirstRight) {
524*cdc20ff6SDimitry Andric     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
525*cdc20ff6SDimitry Andric       LeftProb += (++LastLeft)->Prob;
526*cdc20ff6SDimitry Andric     else
527*cdc20ff6SDimitry Andric       RightProb += (--FirstRight)->Prob;
528*cdc20ff6SDimitry Andric     I++;
529*cdc20ff6SDimitry Andric   }
530*cdc20ff6SDimitry Andric 
531*cdc20ff6SDimitry Andric   while (true) {
532*cdc20ff6SDimitry Andric     // Our binary search tree differs from a typical BST in that ours can have
533*cdc20ff6SDimitry Andric     // up to three values in each leaf. The pivot selection above doesn't take
534*cdc20ff6SDimitry Andric     // that into account, which means the tree might require more nodes and be
535*cdc20ff6SDimitry Andric     // less efficient. We compensate for this here.
536*cdc20ff6SDimitry Andric 
537*cdc20ff6SDimitry Andric     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
538*cdc20ff6SDimitry Andric     unsigned NumRight = W.LastCluster - FirstRight + 1;
539*cdc20ff6SDimitry Andric 
540*cdc20ff6SDimitry Andric     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
541*cdc20ff6SDimitry Andric       // If one side has less than 3 clusters, and the other has more than 3,
542*cdc20ff6SDimitry Andric       // consider taking a cluster from the other side.
543*cdc20ff6SDimitry Andric 
544*cdc20ff6SDimitry Andric       if (NumLeft < NumRight) {
545*cdc20ff6SDimitry Andric         // Consider moving the first cluster on the right to the left side.
546*cdc20ff6SDimitry Andric         CaseCluster &CC = *FirstRight;
547*cdc20ff6SDimitry Andric         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
548*cdc20ff6SDimitry Andric         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
549*cdc20ff6SDimitry Andric         if (LeftSideRank <= RightSideRank) {
550*cdc20ff6SDimitry Andric           // Moving the cluster to the left does not demote it.
551*cdc20ff6SDimitry Andric           ++LastLeft;
552*cdc20ff6SDimitry Andric           ++FirstRight;
553*cdc20ff6SDimitry Andric           continue;
554*cdc20ff6SDimitry Andric         }
555*cdc20ff6SDimitry Andric       } else {
556*cdc20ff6SDimitry Andric         assert(NumRight < NumLeft);
557*cdc20ff6SDimitry Andric         // Consider moving the last element on the left to the right side.
558*cdc20ff6SDimitry Andric         CaseCluster &CC = *LastLeft;
559*cdc20ff6SDimitry Andric         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
560*cdc20ff6SDimitry Andric         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
561*cdc20ff6SDimitry Andric         if (RightSideRank <= LeftSideRank) {
562*cdc20ff6SDimitry Andric           // Moving the cluster to the right does not demot it.
563*cdc20ff6SDimitry Andric           --LastLeft;
564*cdc20ff6SDimitry Andric           --FirstRight;
565*cdc20ff6SDimitry Andric           continue;
566*cdc20ff6SDimitry Andric         }
567*cdc20ff6SDimitry Andric       }
568*cdc20ff6SDimitry Andric     }
569*cdc20ff6SDimitry Andric     break;
570*cdc20ff6SDimitry Andric   }
571*cdc20ff6SDimitry Andric 
572*cdc20ff6SDimitry Andric   assert(LastLeft + 1 == FirstRight);
573*cdc20ff6SDimitry Andric   assert(LastLeft >= W.FirstCluster);
574*cdc20ff6SDimitry Andric   assert(FirstRight <= W.LastCluster);
575*cdc20ff6SDimitry Andric 
576*cdc20ff6SDimitry Andric   return SplitWorkItemInfo{LastLeft, FirstRight, LeftProb, RightProb};
577*cdc20ff6SDimitry Andric }