xref: /src/contrib/llvm-project/llvm/lib/CodeGen/SwitchLoweringUtils.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1e6d15924SDimitry Andric //===- SwitchLoweringUtils.cpp - Switch Lowering --------------------------===//
2e6d15924SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e6d15924SDimitry Andric //
7e6d15924SDimitry Andric //===----------------------------------------------------------------------===//
8e6d15924SDimitry Andric //
9e6d15924SDimitry Andric // This file contains switch inst lowering optimizations and utilities for
10e6d15924SDimitry Andric // codegen, so that it can be used for both SelectionDAG and GlobalISel.
11e6d15924SDimitry Andric //
12e6d15924SDimitry Andric //===----------------------------------------------------------------------===//
13e6d15924SDimitry Andric 
14e6d15924SDimitry Andric #include "llvm/CodeGen/SwitchLoweringUtils.h"
15b60736ecSDimitry Andric #include "llvm/CodeGen/FunctionLoweringInfo.h"
16b60736ecSDimitry Andric #include "llvm/CodeGen/MachineJumpTableInfo.h"
17b60736ecSDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
18cfca06d7SDimitry Andric #include "llvm/Target/TargetMachine.h"
19e6d15924SDimitry Andric 
20e6d15924SDimitry Andric using namespace llvm;
21e6d15924SDimitry Andric using namespace SwitchCG;
22e6d15924SDimitry Andric 
getJumpTableRange(const CaseClusterVector & Clusters,unsigned First,unsigned Last)23e6d15924SDimitry Andric uint64_t SwitchCG::getJumpTableRange(const CaseClusterVector &Clusters,
24e6d15924SDimitry Andric                                      unsigned First, unsigned Last) {
25e6d15924SDimitry Andric   assert(Last >= First);
26e6d15924SDimitry Andric   const APInt &LowCase = Clusters[First].Low->getValue();
27e6d15924SDimitry Andric   const APInt &HighCase = Clusters[Last].High->getValue();
28e6d15924SDimitry Andric   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
29e6d15924SDimitry Andric 
30e6d15924SDimitry Andric   // FIXME: A range of consecutive cases has 100% density, but only requires one
31e6d15924SDimitry Andric   // comparison to lower. We should discriminate against such consecutive ranges
32e6d15924SDimitry Andric   // in jump tables.
33e6d15924SDimitry Andric   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
34e6d15924SDimitry Andric }
35e6d15924SDimitry Andric 
36e6d15924SDimitry Andric uint64_t
getJumpTableNumCases(const SmallVectorImpl<unsigned> & TotalCases,unsigned First,unsigned Last)37e6d15924SDimitry Andric SwitchCG::getJumpTableNumCases(const SmallVectorImpl<unsigned> &TotalCases,
38e6d15924SDimitry Andric                                unsigned First, unsigned Last) {
39e6d15924SDimitry Andric   assert(Last >= First);
40e6d15924SDimitry Andric   assert(TotalCases[Last] >= TotalCases[First]);
41e6d15924SDimitry Andric   uint64_t NumCases =
42e6d15924SDimitry Andric       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
43e6d15924SDimitry Andric   return NumCases;
44e6d15924SDimitry Andric }
45e6d15924SDimitry Andric 
findJumpTables(CaseClusterVector & Clusters,const SwitchInst * SI,std::optional<SDLoc> SL,MachineBasicBlock * DefaultMBB,ProfileSummaryInfo * PSI,BlockFrequencyInfo * BFI)46e6d15924SDimitry Andric void SwitchCG::SwitchLowering::findJumpTables(CaseClusterVector &Clusters,
47e6d15924SDimitry Andric                                               const SwitchInst *SI,
48b1c73532SDimitry Andric                                               std::optional<SDLoc> SL,
49706b4fc4SDimitry Andric                                               MachineBasicBlock *DefaultMBB,
50706b4fc4SDimitry Andric                                               ProfileSummaryInfo *PSI,
51706b4fc4SDimitry Andric                                               BlockFrequencyInfo *BFI) {
52e6d15924SDimitry Andric #ifndef NDEBUG
53e6d15924SDimitry Andric   // Clusters must be non-empty, sorted, and only contain Range clusters.
54e6d15924SDimitry Andric   assert(!Clusters.empty());
55e6d15924SDimitry Andric   for (CaseCluster &C : Clusters)
56e6d15924SDimitry Andric     assert(C.Kind == CC_Range);
57e6d15924SDimitry Andric   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
58e6d15924SDimitry Andric     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
59e6d15924SDimitry Andric #endif
60e6d15924SDimitry Andric 
61e6d15924SDimitry Andric   assert(TLI && "TLI not set!");
62e6d15924SDimitry Andric   if (!TLI->areJTsAllowed(SI->getParent()->getParent()))
63e6d15924SDimitry Andric     return;
64e6d15924SDimitry Andric 
65e6d15924SDimitry Andric   const unsigned MinJumpTableEntries = TLI->getMinimumJumpTableEntries();
66e6d15924SDimitry Andric   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
67e6d15924SDimitry Andric 
68e6d15924SDimitry Andric   // Bail if not enough cases.
69e6d15924SDimitry Andric   const int64_t N = Clusters.size();
70e6d15924SDimitry Andric   if (N < 2 || N < MinJumpTableEntries)
71e6d15924SDimitry Andric     return;
72e6d15924SDimitry Andric 
73e6d15924SDimitry Andric   // Accumulated number of cases in each cluster and those prior to it.
74e6d15924SDimitry Andric   SmallVector<unsigned, 8> TotalCases(N);
75e6d15924SDimitry Andric   for (unsigned i = 0; i < N; ++i) {
76e6d15924SDimitry Andric     const APInt &Hi = Clusters[i].High->getValue();
77e6d15924SDimitry Andric     const APInt &Lo = Clusters[i].Low->getValue();
78e6d15924SDimitry Andric     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
79e6d15924SDimitry Andric     if (i != 0)
80e6d15924SDimitry Andric       TotalCases[i] += TotalCases[i - 1];
81e6d15924SDimitry Andric   }
82e6d15924SDimitry Andric 
83e6d15924SDimitry Andric   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
84e6d15924SDimitry Andric   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
85e6d15924SDimitry Andric   assert(NumCases < UINT64_MAX / 100);
86e6d15924SDimitry Andric   assert(Range >= NumCases);
87e6d15924SDimitry Andric 
88e6d15924SDimitry Andric   // Cheap case: the whole range may be suitable for jump table.
89706b4fc4SDimitry Andric   if (TLI->isSuitableForJumpTable(SI, NumCases, Range, PSI, BFI)) {
90e6d15924SDimitry Andric     CaseCluster JTCluster;
91b1c73532SDimitry Andric     if (buildJumpTable(Clusters, 0, N - 1, SI, SL, DefaultMBB, JTCluster)) {
92e6d15924SDimitry Andric       Clusters[0] = JTCluster;
93e6d15924SDimitry Andric       Clusters.resize(1);
94e6d15924SDimitry Andric       return;
95e6d15924SDimitry Andric     }
96e6d15924SDimitry Andric   }
97e6d15924SDimitry Andric 
98e6d15924SDimitry Andric   // The algorithm below is not suitable for -O0.
99b1c73532SDimitry Andric   if (TM->getOptLevel() == CodeGenOptLevel::None)
100e6d15924SDimitry Andric     return;
101e6d15924SDimitry Andric 
102e6d15924SDimitry Andric   // Split Clusters into minimum number of dense partitions. The algorithm uses
103e6d15924SDimitry Andric   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
104e6d15924SDimitry Andric   // for the Case Statement'" (1994), but builds the MinPartitions array in
105e6d15924SDimitry Andric   // reverse order to make it easier to reconstruct the partitions in ascending
106e6d15924SDimitry Andric   // order. In the choice between two optimal partitionings, it picks the one
107ac9a064cSDimitry Andric   // which yields more jump tables. The algorithm is described in
108ac9a064cSDimitry Andric   // https://arxiv.org/pdf/1910.02351v2
109e6d15924SDimitry Andric 
110e6d15924SDimitry Andric   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
111e6d15924SDimitry Andric   SmallVector<unsigned, 8> MinPartitions(N);
112e6d15924SDimitry Andric   // LastElement[i] is the last element of the partition starting at i.
113e6d15924SDimitry Andric   SmallVector<unsigned, 8> LastElement(N);
114e6d15924SDimitry Andric   // PartitionsScore[i] is used to break ties when choosing between two
115e6d15924SDimitry Andric   // partitionings resulting in the same number of partitions.
116e6d15924SDimitry Andric   SmallVector<unsigned, 8> PartitionsScore(N);
117e6d15924SDimitry Andric   // For PartitionsScore, a small number of comparisons is considered as good as
118e6d15924SDimitry Andric   // a jump table and a single comparison is considered better than a jump
119e6d15924SDimitry Andric   // table.
120e6d15924SDimitry Andric   enum PartitionScores : unsigned {
121e6d15924SDimitry Andric     NoTable = 0,
122e6d15924SDimitry Andric     Table = 1,
123e6d15924SDimitry Andric     FewCases = 1,
124e6d15924SDimitry Andric     SingleCase = 2
125e6d15924SDimitry Andric   };
126e6d15924SDimitry Andric 
127e6d15924SDimitry Andric   // Base case: There is only one way to partition Clusters[N-1].
128e6d15924SDimitry Andric   MinPartitions[N - 1] = 1;
129e6d15924SDimitry Andric   LastElement[N - 1] = N - 1;
130e6d15924SDimitry Andric   PartitionsScore[N - 1] = PartitionScores::SingleCase;
131e6d15924SDimitry Andric 
132e6d15924SDimitry Andric   // Note: loop indexes are signed to avoid underflow.
133e6d15924SDimitry Andric   for (int64_t i = N - 2; i >= 0; i--) {
134e6d15924SDimitry Andric     // Find optimal partitioning of Clusters[i..N-1].
135e6d15924SDimitry Andric     // Baseline: Put Clusters[i] into a partition on its own.
136e6d15924SDimitry Andric     MinPartitions[i] = MinPartitions[i + 1] + 1;
137e6d15924SDimitry Andric     LastElement[i] = i;
138e6d15924SDimitry Andric     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
139e6d15924SDimitry Andric 
140e6d15924SDimitry Andric     // Search for a solution that results in fewer partitions.
141e6d15924SDimitry Andric     for (int64_t j = N - 1; j > i; j--) {
142e6d15924SDimitry Andric       // Try building a partition from Clusters[i..j].
143e6d15924SDimitry Andric       Range = getJumpTableRange(Clusters, i, j);
144e6d15924SDimitry Andric       NumCases = getJumpTableNumCases(TotalCases, i, j);
145e6d15924SDimitry Andric       assert(NumCases < UINT64_MAX / 100);
146e6d15924SDimitry Andric       assert(Range >= NumCases);
147e6d15924SDimitry Andric 
148706b4fc4SDimitry Andric       if (TLI->isSuitableForJumpTable(SI, NumCases, Range, PSI, BFI)) {
149e6d15924SDimitry Andric         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
150e6d15924SDimitry Andric         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
151e6d15924SDimitry Andric         int64_t NumEntries = j - i + 1;
152e6d15924SDimitry Andric 
153e6d15924SDimitry Andric         if (NumEntries == 1)
154e6d15924SDimitry Andric           Score += PartitionScores::SingleCase;
155e6d15924SDimitry Andric         else if (NumEntries <= SmallNumberOfEntries)
156e6d15924SDimitry Andric           Score += PartitionScores::FewCases;
157e6d15924SDimitry Andric         else if (NumEntries >= MinJumpTableEntries)
158e6d15924SDimitry Andric           Score += PartitionScores::Table;
159e6d15924SDimitry Andric 
160e6d15924SDimitry Andric         // If this leads to fewer partitions, or to the same number of
161e6d15924SDimitry Andric         // partitions with better score, it is a better partitioning.
162e6d15924SDimitry Andric         if (NumPartitions < MinPartitions[i] ||
163e6d15924SDimitry Andric             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
164e6d15924SDimitry Andric           MinPartitions[i] = NumPartitions;
165e6d15924SDimitry Andric           LastElement[i] = j;
166e6d15924SDimitry Andric           PartitionsScore[i] = Score;
167e6d15924SDimitry Andric         }
168e6d15924SDimitry Andric       }
169e6d15924SDimitry Andric     }
170e6d15924SDimitry Andric   }
171e6d15924SDimitry Andric 
172e6d15924SDimitry Andric   // Iterate over the partitions, replacing some with jump tables in-place.
173e6d15924SDimitry Andric   unsigned DstIndex = 0;
174e6d15924SDimitry Andric   for (unsigned First = 0, Last; First < N; First = Last + 1) {
175e6d15924SDimitry Andric     Last = LastElement[First];
176e6d15924SDimitry Andric     assert(Last >= First);
177e6d15924SDimitry Andric     assert(DstIndex <= First);
178e6d15924SDimitry Andric     unsigned NumClusters = Last - First + 1;
179e6d15924SDimitry Andric 
180e6d15924SDimitry Andric     CaseCluster JTCluster;
181e6d15924SDimitry Andric     if (NumClusters >= MinJumpTableEntries &&
182b1c73532SDimitry Andric         buildJumpTable(Clusters, First, Last, SI, SL, DefaultMBB, JTCluster)) {
183e6d15924SDimitry Andric       Clusters[DstIndex++] = JTCluster;
184e6d15924SDimitry Andric     } else {
185e6d15924SDimitry Andric       for (unsigned I = First; I <= Last; ++I)
186e6d15924SDimitry Andric         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
187e6d15924SDimitry Andric     }
188e6d15924SDimitry Andric   }
189e6d15924SDimitry Andric   Clusters.resize(DstIndex);
190e6d15924SDimitry Andric }
191e6d15924SDimitry Andric 
buildJumpTable(const CaseClusterVector & Clusters,unsigned First,unsigned Last,const SwitchInst * SI,const std::optional<SDLoc> & SL,MachineBasicBlock * DefaultMBB,CaseCluster & JTCluster)192e6d15924SDimitry Andric bool SwitchCG::SwitchLowering::buildJumpTable(const CaseClusterVector &Clusters,
193e6d15924SDimitry Andric                                               unsigned First, unsigned Last,
194e6d15924SDimitry Andric                                               const SwitchInst *SI,
195b1c73532SDimitry Andric                                               const std::optional<SDLoc> &SL,
196e6d15924SDimitry Andric                                               MachineBasicBlock *DefaultMBB,
197e6d15924SDimitry Andric                                               CaseCluster &JTCluster) {
198e6d15924SDimitry Andric   assert(First <= Last);
199e6d15924SDimitry Andric 
200e6d15924SDimitry Andric   auto Prob = BranchProbability::getZero();
201e6d15924SDimitry Andric   unsigned NumCmps = 0;
202e6d15924SDimitry Andric   std::vector<MachineBasicBlock*> Table;
203e6d15924SDimitry Andric   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
204e6d15924SDimitry Andric 
205e6d15924SDimitry Andric   // Initialize probabilities in JTProbs.
206e6d15924SDimitry Andric   for (unsigned I = First; I <= Last; ++I)
207e6d15924SDimitry Andric     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
208e6d15924SDimitry Andric 
209e6d15924SDimitry Andric   for (unsigned I = First; I <= Last; ++I) {
210e6d15924SDimitry Andric     assert(Clusters[I].Kind == CC_Range);
211e6d15924SDimitry Andric     Prob += Clusters[I].Prob;
212e6d15924SDimitry Andric     const APInt &Low = Clusters[I].Low->getValue();
213e6d15924SDimitry Andric     const APInt &High = Clusters[I].High->getValue();
214e6d15924SDimitry Andric     NumCmps += (Low == High) ? 1 : 2;
215e6d15924SDimitry Andric     if (I != First) {
216e6d15924SDimitry Andric       // Fill the gap between this and the previous cluster.
217e6d15924SDimitry Andric       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
218e6d15924SDimitry Andric       assert(PreviousHigh.slt(Low));
219e6d15924SDimitry Andric       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
220e6d15924SDimitry Andric       for (uint64_t J = 0; J < Gap; J++)
221e6d15924SDimitry Andric         Table.push_back(DefaultMBB);
222e6d15924SDimitry Andric     }
223e6d15924SDimitry Andric     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
224e6d15924SDimitry Andric     for (uint64_t J = 0; J < ClusterSize; ++J)
225e6d15924SDimitry Andric       Table.push_back(Clusters[I].MBB);
226e6d15924SDimitry Andric     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
227e6d15924SDimitry Andric   }
228e6d15924SDimitry Andric 
229e6d15924SDimitry Andric   unsigned NumDests = JTProbs.size();
230e6d15924SDimitry Andric   if (TLI->isSuitableForBitTests(NumDests, NumCmps,
231e6d15924SDimitry Andric                                  Clusters[First].Low->getValue(),
232e6d15924SDimitry Andric                                  Clusters[Last].High->getValue(), *DL)) {
233e6d15924SDimitry Andric     // Clusters[First..Last] should be lowered as bit tests instead.
234e6d15924SDimitry Andric     return false;
235e6d15924SDimitry Andric   }
236e6d15924SDimitry Andric 
237e6d15924SDimitry Andric   // Create the MBB that will load from and jump through the table.
238e6d15924SDimitry Andric   // Note: We create it here, but it's not inserted into the function yet.
239e6d15924SDimitry Andric   MachineFunction *CurMF = FuncInfo.MF;
240e6d15924SDimitry Andric   MachineBasicBlock *JumpTableMBB =
241e6d15924SDimitry Andric       CurMF->CreateMachineBasicBlock(SI->getParent());
242e6d15924SDimitry Andric 
243e6d15924SDimitry Andric   // Add successors. Note: use table order for determinism.
244e6d15924SDimitry Andric   SmallPtrSet<MachineBasicBlock *, 8> Done;
245e6d15924SDimitry Andric   for (MachineBasicBlock *Succ : Table) {
246e6d15924SDimitry Andric     if (Done.count(Succ))
247e6d15924SDimitry Andric       continue;
248e6d15924SDimitry Andric     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
249e6d15924SDimitry Andric     Done.insert(Succ);
250e6d15924SDimitry Andric   }
251e6d15924SDimitry Andric   JumpTableMBB->normalizeSuccProbs();
252e6d15924SDimitry Andric 
253e6d15924SDimitry Andric   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI->getJumpTableEncoding())
254e6d15924SDimitry Andric                      ->createJumpTableIndex(Table);
255e6d15924SDimitry Andric 
256e6d15924SDimitry Andric   // Set up the jump table info.
257b1c73532SDimitry Andric   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr, SL);
258e6d15924SDimitry Andric   JumpTableHeader JTH(Clusters[First].Low->getValue(),
259e6d15924SDimitry Andric                       Clusters[Last].High->getValue(), SI->getCondition(),
260e6d15924SDimitry Andric                       nullptr, false);
261e6d15924SDimitry Andric   JTCases.emplace_back(std::move(JTH), std::move(JT));
262e6d15924SDimitry Andric 
263e6d15924SDimitry Andric   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
264e6d15924SDimitry Andric                                      JTCases.size() - 1, Prob);
265e6d15924SDimitry Andric   return true;
266e6d15924SDimitry Andric }
267e6d15924SDimitry Andric 
findBitTestClusters(CaseClusterVector & Clusters,const SwitchInst * SI)268e6d15924SDimitry Andric void SwitchCG::SwitchLowering::findBitTestClusters(CaseClusterVector &Clusters,
269e6d15924SDimitry Andric                                                    const SwitchInst *SI) {
270e6d15924SDimitry Andric   // Partition Clusters into as few subsets as possible, where each subset has a
271e6d15924SDimitry Andric   // range that fits in a machine word and has <= 3 unique destinations.
272e6d15924SDimitry Andric 
273e6d15924SDimitry Andric #ifndef NDEBUG
274e6d15924SDimitry Andric   // Clusters must be sorted and contain Range or JumpTable clusters.
275e6d15924SDimitry Andric   assert(!Clusters.empty());
276e6d15924SDimitry Andric   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
277e6d15924SDimitry Andric   for (const CaseCluster &C : Clusters)
278e6d15924SDimitry Andric     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
279e6d15924SDimitry Andric   for (unsigned i = 1; i < Clusters.size(); ++i)
280e6d15924SDimitry Andric     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
281e6d15924SDimitry Andric #endif
282e6d15924SDimitry Andric 
283e6d15924SDimitry Andric   // The algorithm below is not suitable for -O0.
284b1c73532SDimitry Andric   if (TM->getOptLevel() == CodeGenOptLevel::None)
285e6d15924SDimitry Andric     return;
286e6d15924SDimitry Andric 
287e6d15924SDimitry Andric   // If target does not have legal shift left, do not emit bit tests at all.
288e6d15924SDimitry Andric   EVT PTy = TLI->getPointerTy(*DL);
289e6d15924SDimitry Andric   if (!TLI->isOperationLegal(ISD::SHL, PTy))
290e6d15924SDimitry Andric     return;
291e6d15924SDimitry Andric 
292e6d15924SDimitry Andric   int BitWidth = PTy.getSizeInBits();
293e6d15924SDimitry Andric   const int64_t N = Clusters.size();
294e6d15924SDimitry Andric 
295e6d15924SDimitry Andric   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
296e6d15924SDimitry Andric   SmallVector<unsigned, 8> MinPartitions(N);
297e6d15924SDimitry Andric   // LastElement[i] is the last element of the partition starting at i.
298e6d15924SDimitry Andric   SmallVector<unsigned, 8> LastElement(N);
299e6d15924SDimitry Andric 
300e6d15924SDimitry Andric   // FIXME: This might not be the best algorithm for finding bit test clusters.
301e6d15924SDimitry Andric 
302e6d15924SDimitry Andric   // Base case: There is only one way to partition Clusters[N-1].
303e6d15924SDimitry Andric   MinPartitions[N - 1] = 1;
304e6d15924SDimitry Andric   LastElement[N - 1] = N - 1;
305e6d15924SDimitry Andric 
306e6d15924SDimitry Andric   // Note: loop indexes are signed to avoid underflow.
307e6d15924SDimitry Andric   for (int64_t i = N - 2; i >= 0; --i) {
308e6d15924SDimitry Andric     // Find optimal partitioning of Clusters[i..N-1].
309e6d15924SDimitry Andric     // Baseline: Put Clusters[i] into a partition on its own.
310e6d15924SDimitry Andric     MinPartitions[i] = MinPartitions[i + 1] + 1;
311e6d15924SDimitry Andric     LastElement[i] = i;
312e6d15924SDimitry Andric 
313e6d15924SDimitry Andric     // Search for a solution that results in fewer partitions.
314e6d15924SDimitry Andric     // Note: the search is limited by BitWidth, reducing time complexity.
315e6d15924SDimitry Andric     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
316e6d15924SDimitry Andric       // Try building a partition from Clusters[i..j].
317e6d15924SDimitry Andric 
318e6d15924SDimitry Andric       // Check the range.
319e6d15924SDimitry Andric       if (!TLI->rangeFitsInWord(Clusters[i].Low->getValue(),
320e6d15924SDimitry Andric                                 Clusters[j].High->getValue(), *DL))
321e6d15924SDimitry Andric         continue;
322e6d15924SDimitry Andric 
323e6d15924SDimitry Andric       // Check nbr of destinations and cluster types.
324e6d15924SDimitry Andric       // FIXME: This works, but doesn't seem very efficient.
325e6d15924SDimitry Andric       bool RangesOnly = true;
326e6d15924SDimitry Andric       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
327e6d15924SDimitry Andric       for (int64_t k = i; k <= j; k++) {
328e6d15924SDimitry Andric         if (Clusters[k].Kind != CC_Range) {
329e6d15924SDimitry Andric           RangesOnly = false;
330e6d15924SDimitry Andric           break;
331e6d15924SDimitry Andric         }
332e6d15924SDimitry Andric         Dests.set(Clusters[k].MBB->getNumber());
333e6d15924SDimitry Andric       }
334e6d15924SDimitry Andric       if (!RangesOnly || Dests.count() > 3)
335e6d15924SDimitry Andric         break;
336e6d15924SDimitry Andric 
337e6d15924SDimitry Andric       // Check if it's a better partition.
338e6d15924SDimitry Andric       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
339e6d15924SDimitry Andric       if (NumPartitions < MinPartitions[i]) {
340e6d15924SDimitry Andric         // Found a better partition.
341e6d15924SDimitry Andric         MinPartitions[i] = NumPartitions;
342e6d15924SDimitry Andric         LastElement[i] = j;
343e6d15924SDimitry Andric       }
344e6d15924SDimitry Andric     }
345e6d15924SDimitry Andric   }
346e6d15924SDimitry Andric 
347e6d15924SDimitry Andric   // Iterate over the partitions, replacing with bit-test clusters in-place.
348e6d15924SDimitry Andric   unsigned DstIndex = 0;
349e6d15924SDimitry Andric   for (unsigned First = 0, Last; First < N; First = Last + 1) {
350e6d15924SDimitry Andric     Last = LastElement[First];
351e6d15924SDimitry Andric     assert(First <= Last);
352e6d15924SDimitry Andric     assert(DstIndex <= First);
353e6d15924SDimitry Andric 
354e6d15924SDimitry Andric     CaseCluster BitTestCluster;
355e6d15924SDimitry Andric     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
356e6d15924SDimitry Andric       Clusters[DstIndex++] = BitTestCluster;
357e6d15924SDimitry Andric     } else {
358e6d15924SDimitry Andric       size_t NumClusters = Last - First + 1;
359e6d15924SDimitry Andric       std::memmove(&Clusters[DstIndex], &Clusters[First],
360e6d15924SDimitry Andric                    sizeof(Clusters[0]) * NumClusters);
361e6d15924SDimitry Andric       DstIndex += NumClusters;
362e6d15924SDimitry Andric     }
363e6d15924SDimitry Andric   }
364e6d15924SDimitry Andric   Clusters.resize(DstIndex);
365e6d15924SDimitry Andric }
366e6d15924SDimitry Andric 
buildBitTests(CaseClusterVector & Clusters,unsigned First,unsigned Last,const SwitchInst * SI,CaseCluster & BTCluster)367e6d15924SDimitry Andric bool SwitchCG::SwitchLowering::buildBitTests(CaseClusterVector &Clusters,
368e6d15924SDimitry Andric                                              unsigned First, unsigned Last,
369e6d15924SDimitry Andric                                              const SwitchInst *SI,
370e6d15924SDimitry Andric                                              CaseCluster &BTCluster) {
371e6d15924SDimitry Andric   assert(First <= Last);
372e6d15924SDimitry Andric   if (First == Last)
373e6d15924SDimitry Andric     return false;
374e6d15924SDimitry Andric 
375e6d15924SDimitry Andric   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
376e6d15924SDimitry Andric   unsigned NumCmps = 0;
377e6d15924SDimitry Andric   for (int64_t I = First; I <= Last; ++I) {
378e6d15924SDimitry Andric     assert(Clusters[I].Kind == CC_Range);
379e6d15924SDimitry Andric     Dests.set(Clusters[I].MBB->getNumber());
380e6d15924SDimitry Andric     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
381e6d15924SDimitry Andric   }
382e6d15924SDimitry Andric   unsigned NumDests = Dests.count();
383e6d15924SDimitry Andric 
384e6d15924SDimitry Andric   APInt Low = Clusters[First].Low->getValue();
385e6d15924SDimitry Andric   APInt High = Clusters[Last].High->getValue();
386e6d15924SDimitry Andric   assert(Low.slt(High));
387e6d15924SDimitry Andric 
388e6d15924SDimitry Andric   if (!TLI->isSuitableForBitTests(NumDests, NumCmps, Low, High, *DL))
389e6d15924SDimitry Andric     return false;
390e6d15924SDimitry Andric 
391e6d15924SDimitry Andric   APInt LowBound;
392e6d15924SDimitry Andric   APInt CmpRange;
393e6d15924SDimitry Andric 
394e6d15924SDimitry Andric   const int BitWidth = TLI->getPointerTy(*DL).getSizeInBits();
395e6d15924SDimitry Andric   assert(TLI->rangeFitsInWord(Low, High, *DL) &&
396e6d15924SDimitry Andric          "Case range must fit in bit mask!");
397e6d15924SDimitry Andric 
398e6d15924SDimitry Andric   // Check if the clusters cover a contiguous range such that no value in the
399e6d15924SDimitry Andric   // range will jump to the default statement.
400e6d15924SDimitry Andric   bool ContiguousRange = true;
401e6d15924SDimitry Andric   for (int64_t I = First + 1; I <= Last; ++I) {
402e6d15924SDimitry Andric     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
403e6d15924SDimitry Andric       ContiguousRange = false;
404e6d15924SDimitry Andric       break;
405e6d15924SDimitry Andric     }
406e6d15924SDimitry Andric   }
407e6d15924SDimitry Andric 
408e6d15924SDimitry Andric   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
409e6d15924SDimitry Andric     // Optimize the case where all the case values fit in a word without having
410e6d15924SDimitry Andric     // to subtract minValue. In this case, we can optimize away the subtraction.
411c0981da4SDimitry Andric     LowBound = APInt::getZero(Low.getBitWidth());
412e6d15924SDimitry Andric     CmpRange = High;
413e6d15924SDimitry Andric     ContiguousRange = false;
414e6d15924SDimitry Andric   } else {
415e6d15924SDimitry Andric     LowBound = Low;
416e6d15924SDimitry Andric     CmpRange = High - Low;
417e6d15924SDimitry Andric   }
418e6d15924SDimitry Andric 
419e6d15924SDimitry Andric   CaseBitsVector CBV;
420e6d15924SDimitry Andric   auto TotalProb = BranchProbability::getZero();
421e6d15924SDimitry Andric   for (unsigned i = First; i <= Last; ++i) {
422e6d15924SDimitry Andric     // Find the CaseBits for this destination.
423e6d15924SDimitry Andric     unsigned j;
424e6d15924SDimitry Andric     for (j = 0; j < CBV.size(); ++j)
425e6d15924SDimitry Andric       if (CBV[j].BB == Clusters[i].MBB)
426e6d15924SDimitry Andric         break;
427e6d15924SDimitry Andric     if (j == CBV.size())
428e6d15924SDimitry Andric       CBV.push_back(
429e6d15924SDimitry Andric           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
430e6d15924SDimitry Andric     CaseBits *CB = &CBV[j];
431e6d15924SDimitry Andric 
432e6d15924SDimitry Andric     // Update Mask, Bits and ExtraProb.
433e6d15924SDimitry Andric     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
434e6d15924SDimitry Andric     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
435e6d15924SDimitry Andric     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
436e6d15924SDimitry Andric     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
437e6d15924SDimitry Andric     CB->Bits += Hi - Lo + 1;
438e6d15924SDimitry Andric     CB->ExtraProb += Clusters[i].Prob;
439e6d15924SDimitry Andric     TotalProb += Clusters[i].Prob;
440e6d15924SDimitry Andric   }
441e6d15924SDimitry Andric 
442e6d15924SDimitry Andric   BitTestInfo BTI;
443e6d15924SDimitry Andric   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
444e6d15924SDimitry Andric     // Sort by probability first, number of bits second, bit mask third.
445e6d15924SDimitry Andric     if (a.ExtraProb != b.ExtraProb)
446e6d15924SDimitry Andric       return a.ExtraProb > b.ExtraProb;
447e6d15924SDimitry Andric     if (a.Bits != b.Bits)
448e6d15924SDimitry Andric       return a.Bits > b.Bits;
449e6d15924SDimitry Andric     return a.Mask < b.Mask;
450e6d15924SDimitry Andric   });
451e6d15924SDimitry Andric 
452e6d15924SDimitry Andric   for (auto &CB : CBV) {
453e6d15924SDimitry Andric     MachineBasicBlock *BitTestBB =
454e6d15924SDimitry Andric         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
455e6d15924SDimitry Andric     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
456e6d15924SDimitry Andric   }
457e6d15924SDimitry Andric   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
458e6d15924SDimitry Andric                             SI->getCondition(), -1U, MVT::Other, false,
459e6d15924SDimitry Andric                             ContiguousRange, nullptr, nullptr, std::move(BTI),
460e6d15924SDimitry Andric                             TotalProb);
461e6d15924SDimitry Andric 
462e6d15924SDimitry Andric   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
463e6d15924SDimitry Andric                                     BitTestCases.size() - 1, TotalProb);
464e6d15924SDimitry Andric   return true;
465e6d15924SDimitry Andric }
466e6d15924SDimitry Andric 
sortAndRangeify(CaseClusterVector & Clusters)467e6d15924SDimitry Andric void SwitchCG::sortAndRangeify(CaseClusterVector &Clusters) {
468e6d15924SDimitry Andric #ifndef NDEBUG
469e6d15924SDimitry Andric   for (const CaseCluster &CC : Clusters)
470e6d15924SDimitry Andric     assert(CC.Low == CC.High && "Input clusters must be single-case");
471e6d15924SDimitry Andric #endif
472e6d15924SDimitry Andric 
473e6d15924SDimitry Andric   llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
474e6d15924SDimitry Andric     return a.Low->getValue().slt(b.Low->getValue());
475e6d15924SDimitry Andric   });
476e6d15924SDimitry Andric 
477e6d15924SDimitry Andric   // Merge adjacent clusters with the same destination.
478e6d15924SDimitry Andric   const unsigned N = Clusters.size();
479e6d15924SDimitry Andric   unsigned DstIndex = 0;
480e6d15924SDimitry Andric   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
481e6d15924SDimitry Andric     CaseCluster &CC = Clusters[SrcIndex];
482e6d15924SDimitry Andric     const ConstantInt *CaseVal = CC.Low;
483e6d15924SDimitry Andric     MachineBasicBlock *Succ = CC.MBB;
484e6d15924SDimitry Andric 
485e6d15924SDimitry Andric     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
486e6d15924SDimitry Andric         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
487e6d15924SDimitry Andric       // If this case has the same successor and is a neighbour, merge it into
488e6d15924SDimitry Andric       // the previous cluster.
489e6d15924SDimitry Andric       Clusters[DstIndex - 1].High = CaseVal;
490e6d15924SDimitry Andric       Clusters[DstIndex - 1].Prob += CC.Prob;
491e6d15924SDimitry Andric     } else {
492e6d15924SDimitry Andric       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
493e6d15924SDimitry Andric                    sizeof(Clusters[SrcIndex]));
494e6d15924SDimitry Andric     }
495e6d15924SDimitry Andric   }
496e6d15924SDimitry Andric   Clusters.resize(DstIndex);
497e6d15924SDimitry Andric }
498aca2e42cSDimitry Andric 
caseClusterRank(const CaseCluster & CC,CaseClusterIt First,CaseClusterIt Last)499aca2e42cSDimitry Andric unsigned SwitchCG::SwitchLowering::caseClusterRank(const CaseCluster &CC,
500aca2e42cSDimitry Andric                                                    CaseClusterIt First,
501aca2e42cSDimitry Andric                                                    CaseClusterIt Last) {
502aca2e42cSDimitry Andric   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
503aca2e42cSDimitry Andric     if (X.Prob != CC.Prob)
504aca2e42cSDimitry Andric       return X.Prob > CC.Prob;
505aca2e42cSDimitry Andric 
506aca2e42cSDimitry Andric     // Ties are broken by comparing the case value.
507aca2e42cSDimitry Andric     return X.Low->getValue().slt(CC.Low->getValue());
508aca2e42cSDimitry Andric   });
509aca2e42cSDimitry Andric }
510aca2e42cSDimitry Andric 
511aca2e42cSDimitry Andric llvm::SwitchCG::SwitchLowering::SplitWorkItemInfo
computeSplitWorkItemInfo(const SwitchWorkListItem & W)512aca2e42cSDimitry Andric SwitchCG::SwitchLowering::computeSplitWorkItemInfo(
513aca2e42cSDimitry Andric     const SwitchWorkListItem &W) {
514aca2e42cSDimitry Andric   CaseClusterIt LastLeft = W.FirstCluster;
515aca2e42cSDimitry Andric   CaseClusterIt FirstRight = W.LastCluster;
516aca2e42cSDimitry Andric   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
517aca2e42cSDimitry Andric   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
518aca2e42cSDimitry Andric 
519aca2e42cSDimitry Andric   // Move LastLeft and FirstRight towards each other from opposite directions to
520aca2e42cSDimitry Andric   // find a partitioning of the clusters which balances the probability on both
521aca2e42cSDimitry Andric   // sides. If LeftProb and RightProb are equal, alternate which side is
522aca2e42cSDimitry Andric   // taken to ensure 0-probability nodes are distributed evenly.
523aca2e42cSDimitry Andric   unsigned I = 0;
524aca2e42cSDimitry Andric   while (LastLeft + 1 < FirstRight) {
525aca2e42cSDimitry Andric     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
526aca2e42cSDimitry Andric       LeftProb += (++LastLeft)->Prob;
527aca2e42cSDimitry Andric     else
528aca2e42cSDimitry Andric       RightProb += (--FirstRight)->Prob;
529aca2e42cSDimitry Andric     I++;
530aca2e42cSDimitry Andric   }
531aca2e42cSDimitry Andric 
532aca2e42cSDimitry Andric   while (true) {
533aca2e42cSDimitry Andric     // Our binary search tree differs from a typical BST in that ours can have
534aca2e42cSDimitry Andric     // up to three values in each leaf. The pivot selection above doesn't take
535aca2e42cSDimitry Andric     // that into account, which means the tree might require more nodes and be
536aca2e42cSDimitry Andric     // less efficient. We compensate for this here.
537aca2e42cSDimitry Andric 
538aca2e42cSDimitry Andric     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
539aca2e42cSDimitry Andric     unsigned NumRight = W.LastCluster - FirstRight + 1;
540aca2e42cSDimitry Andric 
541aca2e42cSDimitry Andric     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
542aca2e42cSDimitry Andric       // If one side has less than 3 clusters, and the other has more than 3,
543aca2e42cSDimitry Andric       // consider taking a cluster from the other side.
544aca2e42cSDimitry Andric 
545aca2e42cSDimitry Andric       if (NumLeft < NumRight) {
546aca2e42cSDimitry Andric         // Consider moving the first cluster on the right to the left side.
547aca2e42cSDimitry Andric         CaseCluster &CC = *FirstRight;
548aca2e42cSDimitry Andric         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
549aca2e42cSDimitry Andric         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
550aca2e42cSDimitry Andric         if (LeftSideRank <= RightSideRank) {
551aca2e42cSDimitry Andric           // Moving the cluster to the left does not demote it.
552aca2e42cSDimitry Andric           ++LastLeft;
553aca2e42cSDimitry Andric           ++FirstRight;
554aca2e42cSDimitry Andric           continue;
555aca2e42cSDimitry Andric         }
556aca2e42cSDimitry Andric       } else {
557aca2e42cSDimitry Andric         assert(NumRight < NumLeft);
558aca2e42cSDimitry Andric         // Consider moving the last element on the left to the right side.
559aca2e42cSDimitry Andric         CaseCluster &CC = *LastLeft;
560aca2e42cSDimitry Andric         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
561aca2e42cSDimitry Andric         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
562aca2e42cSDimitry Andric         if (RightSideRank <= LeftSideRank) {
563aca2e42cSDimitry Andric           // Moving the cluster to the right does not demot it.
564aca2e42cSDimitry Andric           --LastLeft;
565aca2e42cSDimitry Andric           --FirstRight;
566aca2e42cSDimitry Andric           continue;
567aca2e42cSDimitry Andric         }
568aca2e42cSDimitry Andric       }
569aca2e42cSDimitry Andric     }
570aca2e42cSDimitry Andric     break;
571aca2e42cSDimitry Andric   }
572aca2e42cSDimitry Andric 
573aca2e42cSDimitry Andric   assert(LastLeft + 1 == FirstRight);
574aca2e42cSDimitry Andric   assert(LastLeft >= W.FirstCluster);
575aca2e42cSDimitry Andric   assert(FirstRight <= W.LastCluster);
576aca2e42cSDimitry Andric 
577aca2e42cSDimitry Andric   return SplitWorkItemInfo{LastLeft, FirstRight, LeftProb, RightProb};
578aca2e42cSDimitry Andric }
579