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 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 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 460b57cec5SDimitry Andric void SwitchCG::SwitchLowering::findJumpTables(CaseClusterVector &Clusters, 470b57cec5SDimitry Andric const SwitchInst *SI, 485f757f3fSDimitry 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; 915f757f3fSDimitry 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. 995f757f3fSDimitry 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 107*0fca6ea1SDimitry Andric // which yields more jump tables. The algorithm is described in 108*0fca6ea1SDimitry Andric // https://arxiv.org/pdf/1910.02351v2 1090b57cec5SDimitry Andric 1100b57cec5SDimitry Andric // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 1110b57cec5SDimitry Andric SmallVector<unsigned, 8> MinPartitions(N); 1120b57cec5SDimitry Andric // LastElement[i] is the last element of the partition starting at i. 1130b57cec5SDimitry Andric SmallVector<unsigned, 8> LastElement(N); 1140b57cec5SDimitry Andric // PartitionsScore[i] is used to break ties when choosing between two 1150b57cec5SDimitry Andric // partitionings resulting in the same number of partitions. 1160b57cec5SDimitry Andric SmallVector<unsigned, 8> PartitionsScore(N); 1170b57cec5SDimitry Andric // For PartitionsScore, a small number of comparisons is considered as good as 1180b57cec5SDimitry Andric // a jump table and a single comparison is considered better than a jump 1190b57cec5SDimitry Andric // table. 1200b57cec5SDimitry Andric enum PartitionScores : unsigned { 1210b57cec5SDimitry Andric NoTable = 0, 1220b57cec5SDimitry Andric Table = 1, 1230b57cec5SDimitry Andric FewCases = 1, 1240b57cec5SDimitry Andric SingleCase = 2 1250b57cec5SDimitry Andric }; 1260b57cec5SDimitry Andric 1270b57cec5SDimitry Andric // Base case: There is only one way to partition Clusters[N-1]. 1280b57cec5SDimitry Andric MinPartitions[N - 1] = 1; 1290b57cec5SDimitry Andric LastElement[N - 1] = N - 1; 1300b57cec5SDimitry Andric PartitionsScore[N - 1] = PartitionScores::SingleCase; 1310b57cec5SDimitry Andric 1320b57cec5SDimitry Andric // Note: loop indexes are signed to avoid underflow. 1330b57cec5SDimitry Andric for (int64_t i = N - 2; i >= 0; i--) { 1340b57cec5SDimitry Andric // Find optimal partitioning of Clusters[i..N-1]. 1350b57cec5SDimitry Andric // Baseline: Put Clusters[i] into a partition on its own. 1360b57cec5SDimitry Andric MinPartitions[i] = MinPartitions[i + 1] + 1; 1370b57cec5SDimitry Andric LastElement[i] = i; 1380b57cec5SDimitry Andric PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase; 1390b57cec5SDimitry Andric 1400b57cec5SDimitry Andric // Search for a solution that results in fewer partitions. 1410b57cec5SDimitry Andric for (int64_t j = N - 1; j > i; j--) { 1420b57cec5SDimitry Andric // Try building a partition from Clusters[i..j]. 1430b57cec5SDimitry Andric Range = getJumpTableRange(Clusters, i, j); 1440b57cec5SDimitry Andric NumCases = getJumpTableNumCases(TotalCases, i, j); 1450b57cec5SDimitry Andric assert(NumCases < UINT64_MAX / 100); 1460b57cec5SDimitry Andric assert(Range >= NumCases); 1470b57cec5SDimitry Andric 148480093f4SDimitry Andric if (TLI->isSuitableForJumpTable(SI, NumCases, Range, PSI, BFI)) { 1490b57cec5SDimitry Andric unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 1500b57cec5SDimitry Andric unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1]; 1510b57cec5SDimitry Andric int64_t NumEntries = j - i + 1; 1520b57cec5SDimitry Andric 1530b57cec5SDimitry Andric if (NumEntries == 1) 1540b57cec5SDimitry Andric Score += PartitionScores::SingleCase; 1550b57cec5SDimitry Andric else if (NumEntries <= SmallNumberOfEntries) 1560b57cec5SDimitry Andric Score += PartitionScores::FewCases; 1570b57cec5SDimitry Andric else if (NumEntries >= MinJumpTableEntries) 1580b57cec5SDimitry Andric Score += PartitionScores::Table; 1590b57cec5SDimitry Andric 1600b57cec5SDimitry Andric // If this leads to fewer partitions, or to the same number of 1610b57cec5SDimitry Andric // partitions with better score, it is a better partitioning. 1620b57cec5SDimitry Andric if (NumPartitions < MinPartitions[i] || 1630b57cec5SDimitry Andric (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) { 1640b57cec5SDimitry Andric MinPartitions[i] = NumPartitions; 1650b57cec5SDimitry Andric LastElement[i] = j; 1660b57cec5SDimitry Andric PartitionsScore[i] = Score; 1670b57cec5SDimitry Andric } 1680b57cec5SDimitry Andric } 1690b57cec5SDimitry Andric } 1700b57cec5SDimitry Andric } 1710b57cec5SDimitry Andric 1720b57cec5SDimitry Andric // Iterate over the partitions, replacing some with jump tables in-place. 1730b57cec5SDimitry Andric unsigned DstIndex = 0; 1740b57cec5SDimitry Andric for (unsigned First = 0, Last; First < N; First = Last + 1) { 1750b57cec5SDimitry Andric Last = LastElement[First]; 1760b57cec5SDimitry Andric assert(Last >= First); 1770b57cec5SDimitry Andric assert(DstIndex <= First); 1780b57cec5SDimitry Andric unsigned NumClusters = Last - First + 1; 1790b57cec5SDimitry Andric 1800b57cec5SDimitry Andric CaseCluster JTCluster; 1810b57cec5SDimitry Andric if (NumClusters >= MinJumpTableEntries && 1825f757f3fSDimitry Andric buildJumpTable(Clusters, First, Last, SI, SL, DefaultMBB, JTCluster)) { 1830b57cec5SDimitry Andric Clusters[DstIndex++] = JTCluster; 1840b57cec5SDimitry Andric } else { 1850b57cec5SDimitry Andric for (unsigned I = First; I <= Last; ++I) 1860b57cec5SDimitry Andric std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I])); 1870b57cec5SDimitry Andric } 1880b57cec5SDimitry Andric } 1890b57cec5SDimitry Andric Clusters.resize(DstIndex); 1900b57cec5SDimitry Andric } 1910b57cec5SDimitry Andric 1920b57cec5SDimitry Andric bool SwitchCG::SwitchLowering::buildJumpTable(const CaseClusterVector &Clusters, 1930b57cec5SDimitry Andric unsigned First, unsigned Last, 1940b57cec5SDimitry Andric const SwitchInst *SI, 1955f757f3fSDimitry Andric const std::optional<SDLoc> &SL, 1960b57cec5SDimitry Andric MachineBasicBlock *DefaultMBB, 1970b57cec5SDimitry Andric CaseCluster &JTCluster) { 1980b57cec5SDimitry Andric assert(First <= Last); 1990b57cec5SDimitry Andric 2000b57cec5SDimitry Andric auto Prob = BranchProbability::getZero(); 2010b57cec5SDimitry Andric unsigned NumCmps = 0; 2020b57cec5SDimitry Andric std::vector<MachineBasicBlock*> Table; 2030b57cec5SDimitry Andric DenseMap<MachineBasicBlock*, BranchProbability> JTProbs; 2040b57cec5SDimitry Andric 2050b57cec5SDimitry Andric // Initialize probabilities in JTProbs. 2060b57cec5SDimitry Andric for (unsigned I = First; I <= Last; ++I) 2070b57cec5SDimitry Andric JTProbs[Clusters[I].MBB] = BranchProbability::getZero(); 2080b57cec5SDimitry Andric 2090b57cec5SDimitry Andric for (unsigned I = First; I <= Last; ++I) { 2100b57cec5SDimitry Andric assert(Clusters[I].Kind == CC_Range); 2110b57cec5SDimitry Andric Prob += Clusters[I].Prob; 2120b57cec5SDimitry Andric const APInt &Low = Clusters[I].Low->getValue(); 2130b57cec5SDimitry Andric const APInt &High = Clusters[I].High->getValue(); 2140b57cec5SDimitry Andric NumCmps += (Low == High) ? 1 : 2; 2150b57cec5SDimitry Andric if (I != First) { 2160b57cec5SDimitry Andric // Fill the gap between this and the previous cluster. 2170b57cec5SDimitry Andric const APInt &PreviousHigh = Clusters[I - 1].High->getValue(); 2180b57cec5SDimitry Andric assert(PreviousHigh.slt(Low)); 2190b57cec5SDimitry Andric uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1; 2200b57cec5SDimitry Andric for (uint64_t J = 0; J < Gap; J++) 2210b57cec5SDimitry Andric Table.push_back(DefaultMBB); 2220b57cec5SDimitry Andric } 2230b57cec5SDimitry Andric uint64_t ClusterSize = (High - Low).getLimitedValue() + 1; 2240b57cec5SDimitry Andric for (uint64_t J = 0; J < ClusterSize; ++J) 2250b57cec5SDimitry Andric Table.push_back(Clusters[I].MBB); 2260b57cec5SDimitry Andric JTProbs[Clusters[I].MBB] += Clusters[I].Prob; 2270b57cec5SDimitry Andric } 2280b57cec5SDimitry Andric 2290b57cec5SDimitry Andric unsigned NumDests = JTProbs.size(); 2300b57cec5SDimitry Andric if (TLI->isSuitableForBitTests(NumDests, NumCmps, 2310b57cec5SDimitry Andric Clusters[First].Low->getValue(), 2320b57cec5SDimitry Andric Clusters[Last].High->getValue(), *DL)) { 2330b57cec5SDimitry Andric // Clusters[First..Last] should be lowered as bit tests instead. 2340b57cec5SDimitry Andric return false; 2350b57cec5SDimitry Andric } 2360b57cec5SDimitry Andric 2370b57cec5SDimitry Andric // Create the MBB that will load from and jump through the table. 2380b57cec5SDimitry Andric // Note: We create it here, but it's not inserted into the function yet. 2390b57cec5SDimitry Andric MachineFunction *CurMF = FuncInfo.MF; 2400b57cec5SDimitry Andric MachineBasicBlock *JumpTableMBB = 2410b57cec5SDimitry Andric CurMF->CreateMachineBasicBlock(SI->getParent()); 2420b57cec5SDimitry Andric 2430b57cec5SDimitry Andric // Add successors. Note: use table order for determinism. 2440b57cec5SDimitry Andric SmallPtrSet<MachineBasicBlock *, 8> Done; 2450b57cec5SDimitry Andric for (MachineBasicBlock *Succ : Table) { 2460b57cec5SDimitry Andric if (Done.count(Succ)) 2470b57cec5SDimitry Andric continue; 2480b57cec5SDimitry Andric addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]); 2490b57cec5SDimitry Andric Done.insert(Succ); 2500b57cec5SDimitry Andric } 2510b57cec5SDimitry Andric JumpTableMBB->normalizeSuccProbs(); 2520b57cec5SDimitry Andric 2530b57cec5SDimitry Andric unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI->getJumpTableEncoding()) 2540b57cec5SDimitry Andric ->createJumpTableIndex(Table); 2550b57cec5SDimitry Andric 2560b57cec5SDimitry Andric // Set up the jump table info. 2575f757f3fSDimitry Andric JumpTable JT(-1U, JTI, JumpTableMBB, nullptr, SL); 2580b57cec5SDimitry Andric JumpTableHeader JTH(Clusters[First].Low->getValue(), 2590b57cec5SDimitry Andric Clusters[Last].High->getValue(), SI->getCondition(), 2600b57cec5SDimitry Andric nullptr, false); 2610b57cec5SDimitry Andric JTCases.emplace_back(std::move(JTH), std::move(JT)); 2620b57cec5SDimitry Andric 2630b57cec5SDimitry Andric JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High, 2640b57cec5SDimitry Andric JTCases.size() - 1, Prob); 2650b57cec5SDimitry Andric return true; 2660b57cec5SDimitry Andric } 2670b57cec5SDimitry Andric 2680b57cec5SDimitry Andric void SwitchCG::SwitchLowering::findBitTestClusters(CaseClusterVector &Clusters, 2690b57cec5SDimitry Andric const SwitchInst *SI) { 2700b57cec5SDimitry Andric // Partition Clusters into as few subsets as possible, where each subset has a 2710b57cec5SDimitry Andric // range that fits in a machine word and has <= 3 unique destinations. 2720b57cec5SDimitry Andric 2730b57cec5SDimitry Andric #ifndef NDEBUG 2740b57cec5SDimitry Andric // Clusters must be sorted and contain Range or JumpTable clusters. 2750b57cec5SDimitry Andric assert(!Clusters.empty()); 2760b57cec5SDimitry Andric assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable); 2770b57cec5SDimitry Andric for (const CaseCluster &C : Clusters) 2780b57cec5SDimitry Andric assert(C.Kind == CC_Range || C.Kind == CC_JumpTable); 2790b57cec5SDimitry Andric for (unsigned i = 1; i < Clusters.size(); ++i) 2800b57cec5SDimitry Andric assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue())); 2810b57cec5SDimitry Andric #endif 2820b57cec5SDimitry Andric 2830b57cec5SDimitry Andric // The algorithm below is not suitable for -O0. 2845f757f3fSDimitry Andric if (TM->getOptLevel() == CodeGenOptLevel::None) 2850b57cec5SDimitry Andric return; 2860b57cec5SDimitry Andric 2870b57cec5SDimitry Andric // If target does not have legal shift left, do not emit bit tests at all. 2880b57cec5SDimitry Andric EVT PTy = TLI->getPointerTy(*DL); 2890b57cec5SDimitry Andric if (!TLI->isOperationLegal(ISD::SHL, PTy)) 2900b57cec5SDimitry Andric return; 2910b57cec5SDimitry Andric 2920b57cec5SDimitry Andric int BitWidth = PTy.getSizeInBits(); 2930b57cec5SDimitry Andric const int64_t N = Clusters.size(); 2940b57cec5SDimitry Andric 2950b57cec5SDimitry Andric // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1]. 2960b57cec5SDimitry Andric SmallVector<unsigned, 8> MinPartitions(N); 2970b57cec5SDimitry Andric // LastElement[i] is the last element of the partition starting at i. 2980b57cec5SDimitry Andric SmallVector<unsigned, 8> LastElement(N); 2990b57cec5SDimitry Andric 3000b57cec5SDimitry Andric // FIXME: This might not be the best algorithm for finding bit test clusters. 3010b57cec5SDimitry Andric 3020b57cec5SDimitry Andric // Base case: There is only one way to partition Clusters[N-1]. 3030b57cec5SDimitry Andric MinPartitions[N - 1] = 1; 3040b57cec5SDimitry Andric LastElement[N - 1] = N - 1; 3050b57cec5SDimitry Andric 3060b57cec5SDimitry Andric // Note: loop indexes are signed to avoid underflow. 3070b57cec5SDimitry Andric for (int64_t i = N - 2; i >= 0; --i) { 3080b57cec5SDimitry Andric // Find optimal partitioning of Clusters[i..N-1]. 3090b57cec5SDimitry Andric // Baseline: Put Clusters[i] into a partition on its own. 3100b57cec5SDimitry Andric MinPartitions[i] = MinPartitions[i + 1] + 1; 3110b57cec5SDimitry Andric LastElement[i] = i; 3120b57cec5SDimitry Andric 3130b57cec5SDimitry Andric // Search for a solution that results in fewer partitions. 3140b57cec5SDimitry Andric // Note: the search is limited by BitWidth, reducing time complexity. 3150b57cec5SDimitry Andric for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) { 3160b57cec5SDimitry Andric // Try building a partition from Clusters[i..j]. 3170b57cec5SDimitry Andric 3180b57cec5SDimitry Andric // Check the range. 3190b57cec5SDimitry Andric if (!TLI->rangeFitsInWord(Clusters[i].Low->getValue(), 3200b57cec5SDimitry Andric Clusters[j].High->getValue(), *DL)) 3210b57cec5SDimitry Andric continue; 3220b57cec5SDimitry Andric 3230b57cec5SDimitry Andric // Check nbr of destinations and cluster types. 3240b57cec5SDimitry Andric // FIXME: This works, but doesn't seem very efficient. 3250b57cec5SDimitry Andric bool RangesOnly = true; 3260b57cec5SDimitry Andric BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 3270b57cec5SDimitry Andric for (int64_t k = i; k <= j; k++) { 3280b57cec5SDimitry Andric if (Clusters[k].Kind != CC_Range) { 3290b57cec5SDimitry Andric RangesOnly = false; 3300b57cec5SDimitry Andric break; 3310b57cec5SDimitry Andric } 3320b57cec5SDimitry Andric Dests.set(Clusters[k].MBB->getNumber()); 3330b57cec5SDimitry Andric } 3340b57cec5SDimitry Andric if (!RangesOnly || Dests.count() > 3) 3350b57cec5SDimitry Andric break; 3360b57cec5SDimitry Andric 3370b57cec5SDimitry Andric // Check if it's a better partition. 3380b57cec5SDimitry Andric unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]); 3390b57cec5SDimitry Andric if (NumPartitions < MinPartitions[i]) { 3400b57cec5SDimitry Andric // Found a better partition. 3410b57cec5SDimitry Andric MinPartitions[i] = NumPartitions; 3420b57cec5SDimitry Andric LastElement[i] = j; 3430b57cec5SDimitry Andric } 3440b57cec5SDimitry Andric } 3450b57cec5SDimitry Andric } 3460b57cec5SDimitry Andric 3470b57cec5SDimitry Andric // Iterate over the partitions, replacing with bit-test clusters in-place. 3480b57cec5SDimitry Andric unsigned DstIndex = 0; 3490b57cec5SDimitry Andric for (unsigned First = 0, Last; First < N; First = Last + 1) { 3500b57cec5SDimitry Andric Last = LastElement[First]; 3510b57cec5SDimitry Andric assert(First <= Last); 3520b57cec5SDimitry Andric assert(DstIndex <= First); 3530b57cec5SDimitry Andric 3540b57cec5SDimitry Andric CaseCluster BitTestCluster; 3550b57cec5SDimitry Andric if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) { 3560b57cec5SDimitry Andric Clusters[DstIndex++] = BitTestCluster; 3570b57cec5SDimitry Andric } else { 3580b57cec5SDimitry Andric size_t NumClusters = Last - First + 1; 3590b57cec5SDimitry Andric std::memmove(&Clusters[DstIndex], &Clusters[First], 3600b57cec5SDimitry Andric sizeof(Clusters[0]) * NumClusters); 3610b57cec5SDimitry Andric DstIndex += NumClusters; 3620b57cec5SDimitry Andric } 3630b57cec5SDimitry Andric } 3640b57cec5SDimitry Andric Clusters.resize(DstIndex); 3650b57cec5SDimitry Andric } 3660b57cec5SDimitry Andric 3670b57cec5SDimitry Andric bool SwitchCG::SwitchLowering::buildBitTests(CaseClusterVector &Clusters, 3680b57cec5SDimitry Andric unsigned First, unsigned Last, 3690b57cec5SDimitry Andric const SwitchInst *SI, 3700b57cec5SDimitry Andric CaseCluster &BTCluster) { 3710b57cec5SDimitry Andric assert(First <= Last); 3720b57cec5SDimitry Andric if (First == Last) 3730b57cec5SDimitry Andric return false; 3740b57cec5SDimitry Andric 3750b57cec5SDimitry Andric BitVector Dests(FuncInfo.MF->getNumBlockIDs()); 3760b57cec5SDimitry Andric unsigned NumCmps = 0; 3770b57cec5SDimitry Andric for (int64_t I = First; I <= Last; ++I) { 3780b57cec5SDimitry Andric assert(Clusters[I].Kind == CC_Range); 3790b57cec5SDimitry Andric Dests.set(Clusters[I].MBB->getNumber()); 3800b57cec5SDimitry Andric NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2; 3810b57cec5SDimitry Andric } 3820b57cec5SDimitry Andric unsigned NumDests = Dests.count(); 3830b57cec5SDimitry Andric 3840b57cec5SDimitry Andric APInt Low = Clusters[First].Low->getValue(); 3850b57cec5SDimitry Andric APInt High = Clusters[Last].High->getValue(); 3860b57cec5SDimitry Andric assert(Low.slt(High)); 3870b57cec5SDimitry Andric 3880b57cec5SDimitry Andric if (!TLI->isSuitableForBitTests(NumDests, NumCmps, Low, High, *DL)) 3890b57cec5SDimitry Andric return false; 3900b57cec5SDimitry Andric 3910b57cec5SDimitry Andric APInt LowBound; 3920b57cec5SDimitry Andric APInt CmpRange; 3930b57cec5SDimitry Andric 3940b57cec5SDimitry Andric const int BitWidth = TLI->getPointerTy(*DL).getSizeInBits(); 3950b57cec5SDimitry Andric assert(TLI->rangeFitsInWord(Low, High, *DL) && 3960b57cec5SDimitry Andric "Case range must fit in bit mask!"); 3970b57cec5SDimitry Andric 3980b57cec5SDimitry Andric // Check if the clusters cover a contiguous range such that no value in the 3990b57cec5SDimitry Andric // range will jump to the default statement. 4000b57cec5SDimitry Andric bool ContiguousRange = true; 4010b57cec5SDimitry Andric for (int64_t I = First + 1; I <= Last; ++I) { 4020b57cec5SDimitry Andric if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) { 4030b57cec5SDimitry Andric ContiguousRange = false; 4040b57cec5SDimitry Andric break; 4050b57cec5SDimitry Andric } 4060b57cec5SDimitry Andric } 4070b57cec5SDimitry Andric 4080b57cec5SDimitry Andric if (Low.isStrictlyPositive() && High.slt(BitWidth)) { 4090b57cec5SDimitry Andric // Optimize the case where all the case values fit in a word without having 4100b57cec5SDimitry Andric // to subtract minValue. In this case, we can optimize away the subtraction. 411349cc55cSDimitry Andric LowBound = APInt::getZero(Low.getBitWidth()); 4120b57cec5SDimitry Andric CmpRange = High; 4130b57cec5SDimitry Andric ContiguousRange = false; 4140b57cec5SDimitry Andric } else { 4150b57cec5SDimitry Andric LowBound = Low; 4160b57cec5SDimitry Andric CmpRange = High - Low; 4170b57cec5SDimitry Andric } 4180b57cec5SDimitry Andric 4190b57cec5SDimitry Andric CaseBitsVector CBV; 4200b57cec5SDimitry Andric auto TotalProb = BranchProbability::getZero(); 4210b57cec5SDimitry Andric for (unsigned i = First; i <= Last; ++i) { 4220b57cec5SDimitry Andric // Find the CaseBits for this destination. 4230b57cec5SDimitry Andric unsigned j; 4240b57cec5SDimitry Andric for (j = 0; j < CBV.size(); ++j) 4250b57cec5SDimitry Andric if (CBV[j].BB == Clusters[i].MBB) 4260b57cec5SDimitry Andric break; 4270b57cec5SDimitry Andric if (j == CBV.size()) 4280b57cec5SDimitry Andric CBV.push_back( 4290b57cec5SDimitry Andric CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero())); 4300b57cec5SDimitry Andric CaseBits *CB = &CBV[j]; 4310b57cec5SDimitry Andric 4320b57cec5SDimitry Andric // Update Mask, Bits and ExtraProb. 4330b57cec5SDimitry Andric uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue(); 4340b57cec5SDimitry Andric uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue(); 4350b57cec5SDimitry Andric assert(Hi >= Lo && Hi < 64 && "Invalid bit case!"); 4360b57cec5SDimitry Andric CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo; 4370b57cec5SDimitry Andric CB->Bits += Hi - Lo + 1; 4380b57cec5SDimitry Andric CB->ExtraProb += Clusters[i].Prob; 4390b57cec5SDimitry Andric TotalProb += Clusters[i].Prob; 4400b57cec5SDimitry Andric } 4410b57cec5SDimitry Andric 4420b57cec5SDimitry Andric BitTestInfo BTI; 4430b57cec5SDimitry Andric llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) { 4440b57cec5SDimitry Andric // Sort by probability first, number of bits second, bit mask third. 4450b57cec5SDimitry Andric if (a.ExtraProb != b.ExtraProb) 4460b57cec5SDimitry Andric return a.ExtraProb > b.ExtraProb; 4470b57cec5SDimitry Andric if (a.Bits != b.Bits) 4480b57cec5SDimitry Andric return a.Bits > b.Bits; 4490b57cec5SDimitry Andric return a.Mask < b.Mask; 4500b57cec5SDimitry Andric }); 4510b57cec5SDimitry Andric 4520b57cec5SDimitry Andric for (auto &CB : CBV) { 4530b57cec5SDimitry Andric MachineBasicBlock *BitTestBB = 4540b57cec5SDimitry Andric FuncInfo.MF->CreateMachineBasicBlock(SI->getParent()); 4550b57cec5SDimitry Andric BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb)); 4560b57cec5SDimitry Andric } 4570b57cec5SDimitry Andric BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange), 4580b57cec5SDimitry Andric SI->getCondition(), -1U, MVT::Other, false, 4590b57cec5SDimitry Andric ContiguousRange, nullptr, nullptr, std::move(BTI), 4600b57cec5SDimitry Andric TotalProb); 4610b57cec5SDimitry Andric 4620b57cec5SDimitry Andric BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High, 4630b57cec5SDimitry Andric BitTestCases.size() - 1, TotalProb); 4640b57cec5SDimitry Andric return true; 4650b57cec5SDimitry Andric } 4660b57cec5SDimitry Andric 4670b57cec5SDimitry Andric void SwitchCG::sortAndRangeify(CaseClusterVector &Clusters) { 4680b57cec5SDimitry Andric #ifndef NDEBUG 4690b57cec5SDimitry Andric for (const CaseCluster &CC : Clusters) 4700b57cec5SDimitry Andric assert(CC.Low == CC.High && "Input clusters must be single-case"); 4710b57cec5SDimitry Andric #endif 4720b57cec5SDimitry Andric 4730b57cec5SDimitry Andric llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) { 4740b57cec5SDimitry Andric return a.Low->getValue().slt(b.Low->getValue()); 4750b57cec5SDimitry Andric }); 4760b57cec5SDimitry Andric 4770b57cec5SDimitry Andric // Merge adjacent clusters with the same destination. 4780b57cec5SDimitry Andric const unsigned N = Clusters.size(); 4790b57cec5SDimitry Andric unsigned DstIndex = 0; 4800b57cec5SDimitry Andric for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) { 4810b57cec5SDimitry Andric CaseCluster &CC = Clusters[SrcIndex]; 4820b57cec5SDimitry Andric const ConstantInt *CaseVal = CC.Low; 4830b57cec5SDimitry Andric MachineBasicBlock *Succ = CC.MBB; 4840b57cec5SDimitry Andric 4850b57cec5SDimitry Andric if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ && 4860b57cec5SDimitry Andric (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) { 4870b57cec5SDimitry Andric // If this case has the same successor and is a neighbour, merge it into 4880b57cec5SDimitry Andric // the previous cluster. 4890b57cec5SDimitry Andric Clusters[DstIndex - 1].High = CaseVal; 4900b57cec5SDimitry Andric Clusters[DstIndex - 1].Prob += CC.Prob; 4910b57cec5SDimitry Andric } else { 4920b57cec5SDimitry Andric std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex], 4930b57cec5SDimitry Andric sizeof(Clusters[SrcIndex])); 4940b57cec5SDimitry Andric } 4950b57cec5SDimitry Andric } 4960b57cec5SDimitry Andric Clusters.resize(DstIndex); 4970b57cec5SDimitry Andric } 4981db9f3b2SDimitry Andric 4991db9f3b2SDimitry Andric unsigned SwitchCG::SwitchLowering::caseClusterRank(const CaseCluster &CC, 5001db9f3b2SDimitry Andric CaseClusterIt First, 5011db9f3b2SDimitry Andric CaseClusterIt Last) { 5021db9f3b2SDimitry Andric return std::count_if(First, Last + 1, [&](const CaseCluster &X) { 5031db9f3b2SDimitry Andric if (X.Prob != CC.Prob) 5041db9f3b2SDimitry Andric return X.Prob > CC.Prob; 5051db9f3b2SDimitry Andric 5061db9f3b2SDimitry Andric // Ties are broken by comparing the case value. 5071db9f3b2SDimitry Andric return X.Low->getValue().slt(CC.Low->getValue()); 5081db9f3b2SDimitry Andric }); 5091db9f3b2SDimitry Andric } 5101db9f3b2SDimitry Andric 5111db9f3b2SDimitry Andric llvm::SwitchCG::SwitchLowering::SplitWorkItemInfo 5121db9f3b2SDimitry Andric SwitchCG::SwitchLowering::computeSplitWorkItemInfo( 5131db9f3b2SDimitry Andric const SwitchWorkListItem &W) { 5141db9f3b2SDimitry Andric CaseClusterIt LastLeft = W.FirstCluster; 5151db9f3b2SDimitry Andric CaseClusterIt FirstRight = W.LastCluster; 5161db9f3b2SDimitry Andric auto LeftProb = LastLeft->Prob + W.DefaultProb / 2; 5171db9f3b2SDimitry Andric auto RightProb = FirstRight->Prob + W.DefaultProb / 2; 5181db9f3b2SDimitry Andric 5191db9f3b2SDimitry Andric // Move LastLeft and FirstRight towards each other from opposite directions to 5201db9f3b2SDimitry Andric // find a partitioning of the clusters which balances the probability on both 5211db9f3b2SDimitry Andric // sides. If LeftProb and RightProb are equal, alternate which side is 5221db9f3b2SDimitry Andric // taken to ensure 0-probability nodes are distributed evenly. 5231db9f3b2SDimitry Andric unsigned I = 0; 5241db9f3b2SDimitry Andric while (LastLeft + 1 < FirstRight) { 5251db9f3b2SDimitry Andric if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1))) 5261db9f3b2SDimitry Andric LeftProb += (++LastLeft)->Prob; 5271db9f3b2SDimitry Andric else 5281db9f3b2SDimitry Andric RightProb += (--FirstRight)->Prob; 5291db9f3b2SDimitry Andric I++; 5301db9f3b2SDimitry Andric } 5311db9f3b2SDimitry Andric 5321db9f3b2SDimitry Andric while (true) { 5331db9f3b2SDimitry Andric // Our binary search tree differs from a typical BST in that ours can have 5341db9f3b2SDimitry Andric // up to three values in each leaf. The pivot selection above doesn't take 5351db9f3b2SDimitry Andric // that into account, which means the tree might require more nodes and be 5361db9f3b2SDimitry Andric // less efficient. We compensate for this here. 5371db9f3b2SDimitry Andric 5381db9f3b2SDimitry Andric unsigned NumLeft = LastLeft - W.FirstCluster + 1; 5391db9f3b2SDimitry Andric unsigned NumRight = W.LastCluster - FirstRight + 1; 5401db9f3b2SDimitry Andric 5411db9f3b2SDimitry Andric if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) { 5421db9f3b2SDimitry Andric // If one side has less than 3 clusters, and the other has more than 3, 5431db9f3b2SDimitry Andric // consider taking a cluster from the other side. 5441db9f3b2SDimitry Andric 5451db9f3b2SDimitry Andric if (NumLeft < NumRight) { 5461db9f3b2SDimitry Andric // Consider moving the first cluster on the right to the left side. 5471db9f3b2SDimitry Andric CaseCluster &CC = *FirstRight; 5481db9f3b2SDimitry Andric unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 5491db9f3b2SDimitry Andric unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 5501db9f3b2SDimitry Andric if (LeftSideRank <= RightSideRank) { 5511db9f3b2SDimitry Andric // Moving the cluster to the left does not demote it. 5521db9f3b2SDimitry Andric ++LastLeft; 5531db9f3b2SDimitry Andric ++FirstRight; 5541db9f3b2SDimitry Andric continue; 5551db9f3b2SDimitry Andric } 5561db9f3b2SDimitry Andric } else { 5571db9f3b2SDimitry Andric assert(NumRight < NumLeft); 5581db9f3b2SDimitry Andric // Consider moving the last element on the left to the right side. 5591db9f3b2SDimitry Andric CaseCluster &CC = *LastLeft; 5601db9f3b2SDimitry Andric unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft); 5611db9f3b2SDimitry Andric unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster); 5621db9f3b2SDimitry Andric if (RightSideRank <= LeftSideRank) { 5631db9f3b2SDimitry Andric // Moving the cluster to the right does not demot it. 5641db9f3b2SDimitry Andric --LastLeft; 5651db9f3b2SDimitry Andric --FirstRight; 5661db9f3b2SDimitry Andric continue; 5671db9f3b2SDimitry Andric } 5681db9f3b2SDimitry Andric } 5691db9f3b2SDimitry Andric } 5701db9f3b2SDimitry Andric break; 5711db9f3b2SDimitry Andric } 5721db9f3b2SDimitry Andric 5731db9f3b2SDimitry Andric assert(LastLeft + 1 == FirstRight); 5741db9f3b2SDimitry Andric assert(LastLeft >= W.FirstCluster); 5751db9f3b2SDimitry Andric assert(FirstRight <= W.LastCluster); 5761db9f3b2SDimitry Andric 5771db9f3b2SDimitry Andric return SplitWorkItemInfo{LastLeft, FirstRight, LeftProb, RightProb}; 5781db9f3b2SDimitry Andric } 579