xref: /src/contrib/llvm-project/llvm/lib/CodeGen/BasicBlockSections.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1b60736ecSDimitry Andric //===-- BasicBlockSections.cpp ---=========--------------------------------===//
2cfca06d7SDimitry Andric //
3cfca06d7SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4cfca06d7SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5cfca06d7SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6cfca06d7SDimitry Andric //
7cfca06d7SDimitry Andric //===----------------------------------------------------------------------===//
8cfca06d7SDimitry Andric //
9b60736ecSDimitry Andric // BasicBlockSections implementation.
10cfca06d7SDimitry Andric //
11cfca06d7SDimitry Andric // The purpose of this pass is to assign sections to basic blocks when
12cfca06d7SDimitry Andric // -fbasic-block-sections= option is used. Further, with profile information
13cfca06d7SDimitry Andric // only the subset of basic blocks with profiles are placed in separate sections
14cfca06d7SDimitry Andric // and the rest are grouped in a cold section. The exception handling blocks are
15cfca06d7SDimitry Andric // treated specially to ensure they are all in one seciton.
16cfca06d7SDimitry Andric //
17cfca06d7SDimitry Andric // Basic Block Sections
18cfca06d7SDimitry Andric // ====================
19cfca06d7SDimitry Andric //
20cfca06d7SDimitry Andric // With option, -fbasic-block-sections=list, every function may be split into
21cfca06d7SDimitry Andric // clusters of basic blocks. Every cluster will be emitted into a separate
22cfca06d7SDimitry Andric // section with its basic blocks sequenced in the given order. To get the
23cfca06d7SDimitry Andric // optimized performance, the clusters must form an optimal BB layout for the
24c0981da4SDimitry Andric // function. We insert a symbol at the beginning of every cluster's section to
25c0981da4SDimitry Andric // allow the linker to reorder the sections in any arbitrary sequence. A global
26c0981da4SDimitry Andric // order of these sections would encapsulate the function layout.
27c0981da4SDimitry Andric // For example, consider the following clusters for a function foo (consisting
28c0981da4SDimitry Andric // of 6 basic blocks 0, 1, ..., 5).
29c0981da4SDimitry Andric //
30c0981da4SDimitry Andric // 0 2
31c0981da4SDimitry Andric // 1 3 5
32c0981da4SDimitry Andric //
33c0981da4SDimitry Andric // * Basic blocks 0 and 2 are placed in one section with symbol `foo`
34c0981da4SDimitry Andric //   referencing the beginning of this section.
35c0981da4SDimitry Andric // * Basic blocks 1, 3, 5 are placed in a separate section. A new symbol
36c0981da4SDimitry Andric //   `foo.__part.1` will reference the beginning of this section.
37c0981da4SDimitry Andric // * Basic block 4 (note that it is not referenced in the list) is placed in
38c0981da4SDimitry Andric //   one section, and a new symbol `foo.cold` will point to it.
39cfca06d7SDimitry Andric //
40cfca06d7SDimitry Andric // There are a couple of challenges to be addressed:
41cfca06d7SDimitry Andric //
42cfca06d7SDimitry Andric // 1. The last basic block of every cluster should not have any implicit
43cfca06d7SDimitry Andric //    fallthrough to its next basic block, as it can be reordered by the linker.
44cfca06d7SDimitry Andric //    The compiler should make these fallthroughs explicit by adding
45cfca06d7SDimitry Andric //    unconditional jumps..
46cfca06d7SDimitry Andric //
47cfca06d7SDimitry Andric // 2. All inter-cluster branch targets would now need to be resolved by the
48cfca06d7SDimitry Andric //    linker as they cannot be calculated during compile time. This is done
49cfca06d7SDimitry Andric //    using static relocations. Further, the compiler tries to use short branch
50cfca06d7SDimitry Andric //    instructions on some ISAs for small branch offsets. This is not possible
51cfca06d7SDimitry Andric //    for inter-cluster branches as the offset is not determined at compile
52cfca06d7SDimitry Andric //    time, and therefore, long branch instructions have to be used for those.
53cfca06d7SDimitry Andric //
54cfca06d7SDimitry Andric // 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission
55cfca06d7SDimitry Andric //    needs special handling with basic block sections. DebugInfo needs to be
56cfca06d7SDimitry Andric //    emitted with more relocations as basic block sections can break a
57cfca06d7SDimitry Andric //    function into potentially several disjoint pieces, and CFI needs to be
58cfca06d7SDimitry Andric //    emitted per cluster. This also bloats the object file and binary sizes.
59cfca06d7SDimitry Andric //
60ac9a064cSDimitry Andric // Basic Block Address Map
61cfca06d7SDimitry Andric // ==================
62cfca06d7SDimitry Andric //
63ac9a064cSDimitry Andric // With -fbasic-block-address-map, we emit the offsets of BB addresses of
64b60736ecSDimitry Andric // every function into the .llvm_bb_addr_map section. Along with the function
65b60736ecSDimitry Andric // symbols, this allows for mapping of virtual addresses in PMU profiles back to
66b60736ecSDimitry Andric // the corresponding basic blocks. This logic is implemented in AsmPrinter. This
67b60736ecSDimitry Andric // pass only assigns the BBSectionType of every function to ``labels``.
68cfca06d7SDimitry Andric //
69cfca06d7SDimitry Andric //===----------------------------------------------------------------------===//
70cfca06d7SDimitry Andric 
71cfca06d7SDimitry Andric #include "llvm/ADT/SmallVector.h"
72cfca06d7SDimitry Andric #include "llvm/ADT/StringRef.h"
73b60736ecSDimitry Andric #include "llvm/CodeGen/BasicBlockSectionUtils.h"
74e3b55780SDimitry Andric #include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
75cfca06d7SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
76cfca06d7SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
77cfca06d7SDimitry Andric #include "llvm/CodeGen/Passes.h"
78cfca06d7SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
79cfca06d7SDimitry Andric #include "llvm/InitializePasses.h"
80cfca06d7SDimitry Andric #include "llvm/Target/TargetMachine.h"
81e3b55780SDimitry Andric #include <optional>
82cfca06d7SDimitry Andric 
83cfca06d7SDimitry Andric using namespace llvm;
84cfca06d7SDimitry Andric 
85b60736ecSDimitry Andric // Placing the cold clusters in a separate section mitigates against poor
86b60736ecSDimitry Andric // profiles and allows optimizations such as hugepage mapping to be applied at a
87b60736ecSDimitry Andric // section granularity. Defaults to ".text.split." which is recognized by lld
88b60736ecSDimitry Andric // via the `-z keep-text-section-prefix` flag.
89b60736ecSDimitry Andric cl::opt<std::string> llvm::BBSectionsColdTextPrefix(
90b60736ecSDimitry Andric     "bbsections-cold-text-prefix",
91b60736ecSDimitry Andric     cl::desc("The text prefix to use for cold basic block clusters"),
92b60736ecSDimitry Andric     cl::init(".text.split."), cl::Hidden);
93b60736ecSDimitry Andric 
947fa27ce4SDimitry Andric static cl::opt<bool> BBSectionsDetectSourceDrift(
95344a3780SDimitry Andric     "bbsections-detect-source-drift",
96344a3780SDimitry Andric     cl::desc("This checks if there is a fdo instr. profile hash "
97344a3780SDimitry Andric              "mismatch for this function"),
98344a3780SDimitry Andric     cl::init(true), cl::Hidden);
99344a3780SDimitry Andric 
100cfca06d7SDimitry Andric namespace {
101cfca06d7SDimitry Andric 
102b60736ecSDimitry Andric class BasicBlockSections : public MachineFunctionPass {
103cfca06d7SDimitry Andric public:
104cfca06d7SDimitry Andric   static char ID;
105cfca06d7SDimitry Andric 
106aca2e42cSDimitry Andric   BasicBlockSectionsProfileReaderWrapperPass *BBSectionsProfileReader = nullptr;
107cfca06d7SDimitry Andric 
BasicBlockSections()108b60736ecSDimitry Andric   BasicBlockSections() : MachineFunctionPass(ID) {
109b60736ecSDimitry Andric     initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
110cfca06d7SDimitry Andric   }
111cfca06d7SDimitry Andric 
getPassName() const112cfca06d7SDimitry Andric   StringRef getPassName() const override {
113cfca06d7SDimitry Andric     return "Basic Block Sections Analysis";
114cfca06d7SDimitry Andric   }
115cfca06d7SDimitry Andric 
116cfca06d7SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override;
117cfca06d7SDimitry Andric 
118cfca06d7SDimitry Andric   /// Identify basic blocks that need separate sections and prepare to emit them
119cfca06d7SDimitry Andric   /// accordingly.
120cfca06d7SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
121ac9a064cSDimitry Andric 
122ac9a064cSDimitry Andric private:
123ac9a064cSDimitry Andric   bool handleBBSections(MachineFunction &MF);
124ac9a064cSDimitry Andric   bool handleBBAddrMap(MachineFunction &MF);
125cfca06d7SDimitry Andric };
126cfca06d7SDimitry Andric 
127cfca06d7SDimitry Andric } // end anonymous namespace
128cfca06d7SDimitry Andric 
129b60736ecSDimitry Andric char BasicBlockSections::ID = 0;
1307fa27ce4SDimitry Andric INITIALIZE_PASS_BEGIN(
1317fa27ce4SDimitry Andric     BasicBlockSections, "bbsections-prepare",
1327fa27ce4SDimitry Andric     "Prepares for basic block sections, by splitting functions "
1337fa27ce4SDimitry Andric     "into clusters of basic blocks.",
1347fa27ce4SDimitry Andric     false, false)
INITIALIZE_PASS_DEPENDENCY(BasicBlockSectionsProfileReaderWrapperPass)135aca2e42cSDimitry Andric INITIALIZE_PASS_DEPENDENCY(BasicBlockSectionsProfileReaderWrapperPass)
1367fa27ce4SDimitry Andric INITIALIZE_PASS_END(BasicBlockSections, "bbsections-prepare",
137cfca06d7SDimitry Andric                     "Prepares for basic block sections, by splitting functions "
138cfca06d7SDimitry Andric                     "into clusters of basic blocks.",
139cfca06d7SDimitry Andric                     false, false)
140cfca06d7SDimitry Andric 
141cfca06d7SDimitry Andric // This function updates and optimizes the branching instructions of every basic
142cfca06d7SDimitry Andric // block in a given function to account for changes in the layout.
143e3b55780SDimitry Andric static void
144e3b55780SDimitry Andric updateBranches(MachineFunction &MF,
145e3b55780SDimitry Andric                const SmallVector<MachineBasicBlock *> &PreLayoutFallThroughs) {
146cfca06d7SDimitry Andric   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
147cfca06d7SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
148cfca06d7SDimitry Andric   for (auto &MBB : MF) {
149cfca06d7SDimitry Andric     auto NextMBBI = std::next(MBB.getIterator());
150cfca06d7SDimitry Andric     auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];
151cfca06d7SDimitry Andric     // If this block had a fallthrough before we need an explicit unconditional
152cfca06d7SDimitry Andric     // branch to that block if either
153cfca06d7SDimitry Andric     //     1- the block ends a section, which means its next block may be
154cfca06d7SDimitry Andric     //        reorderd by the linker, or
155cfca06d7SDimitry Andric     //     2- the fallthrough block is not adjacent to the block in the new
156cfca06d7SDimitry Andric     //        order.
157cfca06d7SDimitry Andric     if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))
158cfca06d7SDimitry Andric       TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
159cfca06d7SDimitry Andric 
160cfca06d7SDimitry Andric     // We do not optimize branches for machine basic blocks ending sections, as
161cfca06d7SDimitry Andric     // their adjacent block might be reordered by the linker.
162cfca06d7SDimitry Andric     if (MBB.isEndSection())
163cfca06d7SDimitry Andric       continue;
164cfca06d7SDimitry Andric 
165cfca06d7SDimitry Andric     // It might be possible to optimize branches by flipping the branch
166cfca06d7SDimitry Andric     // condition.
167cfca06d7SDimitry Andric     Cond.clear();
168cfca06d7SDimitry Andric     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
169cfca06d7SDimitry Andric     if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
170cfca06d7SDimitry Andric       continue;
171cfca06d7SDimitry Andric     MBB.updateTerminator(FTMBB);
172cfca06d7SDimitry Andric   }
173cfca06d7SDimitry Andric }
174cfca06d7SDimitry Andric 
175cfca06d7SDimitry Andric // This function sorts basic blocks according to the cluster's information.
176cfca06d7SDimitry Andric // All explicitly specified clusters of basic blocks will be ordered
177cfca06d7SDimitry Andric // accordingly. All non-specified BBs go into a separate "Cold" section.
178cfca06d7SDimitry Andric // Additionally, if exception handling landing pads end up in more than one
179cfca06d7SDimitry Andric // clusters, they are moved into a single "Exception" section. Eventually,
180cfca06d7SDimitry Andric // clusters are ordered in increasing order of their IDs, with the "Exception"
181cfca06d7SDimitry Andric // and "Cold" succeeding all other clusters.
182b1c73532SDimitry Andric // FuncClusterInfo represents the cluster information for basic blocks. It
183e3b55780SDimitry Andric // maps from BBID of basic blocks to their cluster information. If this is
184e3b55780SDimitry Andric // empty, it means unique sections for all basic blocks in the function.
185b60736ecSDimitry Andric static void
assignSections(MachineFunction & MF,const DenseMap<UniqueBBID,BBClusterInfo> & FuncClusterInfo)186b60736ecSDimitry Andric assignSections(MachineFunction &MF,
187b1c73532SDimitry Andric                const DenseMap<UniqueBBID, BBClusterInfo> &FuncClusterInfo) {
188cfca06d7SDimitry Andric   assert(MF.hasBBSections() && "BB Sections is not set for function.");
189cfca06d7SDimitry Andric   // This variable stores the section ID of the cluster containing eh_pads (if
190cfca06d7SDimitry Andric   // all eh_pads are one cluster). If more than one cluster contain eh_pads, we
191cfca06d7SDimitry Andric   // set it equal to ExceptionSectionID.
192e3b55780SDimitry Andric   std::optional<MBBSectionID> EHPadsSectionID;
193cfca06d7SDimitry Andric 
194cfca06d7SDimitry Andric   for (auto &MBB : MF) {
195cfca06d7SDimitry Andric     // With the 'all' option, every basic block is placed in a unique section.
196cfca06d7SDimitry Andric     // With the 'list' option, every basic block is placed in a section
197cfca06d7SDimitry Andric     // associated with its cluster, unless we want individual unique sections
198b1c73532SDimitry Andric     // for every basic block in this function (if FuncClusterInfo is empty).
199cfca06d7SDimitry Andric     if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All ||
200b1c73532SDimitry Andric         FuncClusterInfo.empty()) {
201cfca06d7SDimitry Andric       // If unique sections are desired for all basic blocks of the function, we
202e3b55780SDimitry Andric       // set every basic block's section ID equal to its original position in
203e3b55780SDimitry Andric       // the layout (which is equal to its number). This ensures that basic
204e3b55780SDimitry Andric       // blocks are ordered canonically.
205e3b55780SDimitry Andric       MBB.setSectionID(MBB.getNumber());
206e3b55780SDimitry Andric     } else {
207b1c73532SDimitry Andric       auto I = FuncClusterInfo.find(*MBB.getBBID());
208b1c73532SDimitry Andric       if (I != FuncClusterInfo.end()) {
209e3b55780SDimitry Andric         MBB.setSectionID(I->second.ClusterID);
210e3b55780SDimitry Andric       } else {
211ac9a064cSDimitry Andric         const TargetInstrInfo &TII =
212ac9a064cSDimitry Andric             *MBB.getParent()->getSubtarget().getInstrInfo();
213ac9a064cSDimitry Andric 
214ac9a064cSDimitry Andric         if (TII.isMBBSafeToSplitToCold(MBB)) {
215cfca06d7SDimitry Andric           // BB goes into the special cold section if it is not specified in the
216cfca06d7SDimitry Andric           // cluster info map.
217cfca06d7SDimitry Andric           MBB.setSectionID(MBBSectionID::ColdSectionID);
218cfca06d7SDimitry Andric         }
219e3b55780SDimitry Andric       }
220ac9a064cSDimitry Andric     }
221cfca06d7SDimitry Andric 
222cfca06d7SDimitry Andric     if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&
223cfca06d7SDimitry Andric         EHPadsSectionID != MBBSectionID::ExceptionSectionID) {
224cfca06d7SDimitry Andric       // If we already have one cluster containing eh_pads, this must be updated
225cfca06d7SDimitry Andric       // to ExceptionSectionID. Otherwise, we set it equal to the current
226cfca06d7SDimitry Andric       // section ID.
227145449b1SDimitry Andric       EHPadsSectionID = EHPadsSectionID ? MBBSectionID::ExceptionSectionID
228cfca06d7SDimitry Andric                                         : MBB.getSectionID();
229cfca06d7SDimitry Andric     }
230cfca06d7SDimitry Andric   }
231cfca06d7SDimitry Andric 
232cfca06d7SDimitry Andric   // If EHPads are in more than one section, this places all of them in the
233cfca06d7SDimitry Andric   // special exception section.
234cfca06d7SDimitry Andric   if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)
235cfca06d7SDimitry Andric     for (auto &MBB : MF)
236cfca06d7SDimitry Andric       if (MBB.isEHPad())
237145449b1SDimitry Andric         MBB.setSectionID(*EHPadsSectionID);
238b60736ecSDimitry Andric }
239cfca06d7SDimitry Andric 
sortBasicBlocksAndUpdateBranches(MachineFunction & MF,MachineBasicBlockComparator MBBCmp)240b60736ecSDimitry Andric void llvm::sortBasicBlocksAndUpdateBranches(
241b60736ecSDimitry Andric     MachineFunction &MF, MachineBasicBlockComparator MBBCmp) {
242e3b55780SDimitry Andric   [[maybe_unused]] const MachineBasicBlock *EntryBlock = &MF.front();
243e3b55780SDimitry Andric   SmallVector<MachineBasicBlock *> PreLayoutFallThroughs(MF.getNumBlockIDs());
244cfca06d7SDimitry Andric   for (auto &MBB : MF)
245b1c73532SDimitry Andric     PreLayoutFallThroughs[MBB.getNumber()] =
246b1c73532SDimitry Andric         MBB.getFallThrough(/*JumpToFallThrough=*/false);
247cfca06d7SDimitry Andric 
248b60736ecSDimitry Andric   MF.sort(MBBCmp);
249e3b55780SDimitry Andric   assert(&MF.front() == EntryBlock &&
250e3b55780SDimitry Andric          "Entry block should not be displaced by basic block sections");
251b60736ecSDimitry Andric 
252b60736ecSDimitry Andric   // Set IsBeginSection and IsEndSection according to the assigned section IDs.
253b60736ecSDimitry Andric   MF.assignBeginEndSections();
254b60736ecSDimitry Andric 
255b60736ecSDimitry Andric   // After reordering basic blocks, we must update basic block branches to
256b60736ecSDimitry Andric   // insert explicit fallthrough branches when required and optimize branches
257b60736ecSDimitry Andric   // when possible.
258b60736ecSDimitry Andric   updateBranches(MF, PreLayoutFallThroughs);
259b60736ecSDimitry Andric }
260b60736ecSDimitry Andric 
261b60736ecSDimitry Andric // If the exception section begins with a landing pad, that landing pad will
262b60736ecSDimitry Andric // assume a zero offset (relative to @LPStart) in the LSDA. However, a value of
263b60736ecSDimitry Andric // zero implies "no landing pad." This function inserts a NOP just before the EH
2644b4fe385SDimitry Andric // pad label to ensure a nonzero offset.
avoidZeroOffsetLandingPad(MachineFunction & MF)2654b4fe385SDimitry Andric void llvm::avoidZeroOffsetLandingPad(MachineFunction &MF) {
266b60736ecSDimitry Andric   for (auto &MBB : MF) {
267b60736ecSDimitry Andric     if (MBB.isBeginSection() && MBB.isEHPad()) {
268b60736ecSDimitry Andric       MachineBasicBlock::iterator MI = MBB.begin();
269b60736ecSDimitry Andric       while (!MI->isEHLabel())
270b60736ecSDimitry Andric         ++MI;
271b1c73532SDimitry Andric       MF.getSubtarget().getInstrInfo()->insertNoop(MBB, MI);
272b60736ecSDimitry Andric     }
273b60736ecSDimitry Andric   }
274b60736ecSDimitry Andric }
275b60736ecSDimitry Andric 
hasInstrProfHashMismatch(MachineFunction & MF)276b1c73532SDimitry Andric bool llvm::hasInstrProfHashMismatch(MachineFunction &MF) {
277344a3780SDimitry Andric   if (!BBSectionsDetectSourceDrift)
278344a3780SDimitry Andric     return false;
279344a3780SDimitry Andric 
280344a3780SDimitry Andric   const char MetadataName[] = "instr_prof_hash_mismatch";
281344a3780SDimitry Andric   auto *Existing = MF.getFunction().getMetadata(LLVMContext::MD_annotation);
282344a3780SDimitry Andric   if (Existing) {
283344a3780SDimitry Andric     MDTuple *Tuple = cast<MDTuple>(Existing);
2844b4fe385SDimitry Andric     for (const auto &N : Tuple->operands())
2857fa27ce4SDimitry Andric       if (N.equalsStr(MetadataName))
286344a3780SDimitry Andric         return true;
287344a3780SDimitry Andric   }
288344a3780SDimitry Andric 
289344a3780SDimitry Andric   return false;
290344a3780SDimitry Andric }
291344a3780SDimitry Andric 
292ac9a064cSDimitry Andric // Identify, arrange, and modify basic blocks which need separate sections
293ac9a064cSDimitry Andric // according to the specification provided by the -fbasic-block-sections flag.
handleBBSections(MachineFunction & MF)294ac9a064cSDimitry Andric bool BasicBlockSections::handleBBSections(MachineFunction &MF) {
295b60736ecSDimitry Andric   auto BBSectionsType = MF.getTarget().getBBSectionsType();
296ac9a064cSDimitry Andric   if (BBSectionsType == BasicBlockSection::None)
297ac9a064cSDimitry Andric     return false;
298344a3780SDimitry Andric 
299344a3780SDimitry Andric   // Check for source drift. If the source has changed since the profiles
300344a3780SDimitry Andric   // were obtained, optimizing basic blocks might be sub-optimal.
301344a3780SDimitry Andric   // This only applies to BasicBlockSection::List as it creates
302344a3780SDimitry Andric   // clusters of basic blocks using basic block ids. Source drift can
303344a3780SDimitry Andric   // invalidate these groupings leading to sub-optimal code generation with
304344a3780SDimitry Andric   // regards to performance.
305344a3780SDimitry Andric   if (BBSectionsType == BasicBlockSection::List &&
306344a3780SDimitry Andric       hasInstrProfHashMismatch(MF))
307b1c73532SDimitry Andric     return false;
308b1c73532SDimitry Andric   // Renumber blocks before sorting them. This is useful for accessing the
309b1c73532SDimitry Andric   // original layout positions and finding the original fallthroughs.
310b60736ecSDimitry Andric   MF.RenumberBlocks();
311b60736ecSDimitry Andric 
312b60736ecSDimitry Andric   if (BBSectionsType == BasicBlockSection::Labels) {
313b60736ecSDimitry Andric     MF.setBBSectionsType(BBSectionsType);
314ac9a064cSDimitry Andric     return true;
315b60736ecSDimitry Andric   }
316b60736ecSDimitry Andric 
317b1c73532SDimitry Andric   DenseMap<UniqueBBID, BBClusterInfo> FuncClusterInfo;
318b1c73532SDimitry Andric   if (BBSectionsType == BasicBlockSection::List) {
319b1c73532SDimitry Andric     auto [HasProfile, ClusterInfo] =
320aca2e42cSDimitry Andric         getAnalysis<BasicBlockSectionsProfileReaderWrapperPass>()
321b1c73532SDimitry Andric             .getClusterInfoForFunction(MF.getName());
322b1c73532SDimitry Andric     if (!HasProfile)
323b1c73532SDimitry Andric       return false;
324b1c73532SDimitry Andric     for (auto &BBClusterInfo : ClusterInfo) {
325b1c73532SDimitry Andric       FuncClusterInfo.try_emplace(BBClusterInfo.BBID, BBClusterInfo);
326b1c73532SDimitry Andric     }
327b1c73532SDimitry Andric   }
328145449b1SDimitry Andric 
329b60736ecSDimitry Andric   MF.setBBSectionsType(BBSectionsType);
330b1c73532SDimitry Andric   assignSections(MF, FuncClusterInfo);
331b60736ecSDimitry Andric 
3324df029ccSDimitry Andric   const MachineBasicBlock &EntryBB = MF.front();
3334df029ccSDimitry Andric   auto EntryBBSectionID = EntryBB.getSectionID();
334cfca06d7SDimitry Andric 
335cfca06d7SDimitry Andric   // Helper function for ordering BB sections as follows:
336cfca06d7SDimitry Andric   //   * Entry section (section including the entry block).
337cfca06d7SDimitry Andric   //   * Regular sections (in increasing order of their Number).
338cfca06d7SDimitry Andric   //     ...
339cfca06d7SDimitry Andric   //   * Exception section
340cfca06d7SDimitry Andric   //   * Cold section
341cfca06d7SDimitry Andric   auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,
342cfca06d7SDimitry Andric                                             const MBBSectionID &RHS) {
343cfca06d7SDimitry Andric     // We make sure that the section containing the entry block precedes all the
344cfca06d7SDimitry Andric     // other sections.
345cfca06d7SDimitry Andric     if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)
346cfca06d7SDimitry Andric       return LHS == EntryBBSectionID;
347cfca06d7SDimitry Andric     return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;
348cfca06d7SDimitry Andric   };
349cfca06d7SDimitry Andric 
350cfca06d7SDimitry Andric   // We sort all basic blocks to make sure the basic blocks of every cluster are
351cfca06d7SDimitry Andric   // contiguous and ordered accordingly. Furthermore, clusters are ordered in
352cfca06d7SDimitry Andric   // increasing order of their section IDs, with the exception and the
353cfca06d7SDimitry Andric   // cold section placed at the end of the function.
3544df029ccSDimitry Andric   // Also, we force the entry block of the function to be placed at the
3554df029ccSDimitry Andric   // beginning of the function, regardless of the requested order.
356b60736ecSDimitry Andric   auto Comparator = [&](const MachineBasicBlock &X,
357b60736ecSDimitry Andric                         const MachineBasicBlock &Y) {
358cfca06d7SDimitry Andric     auto XSectionID = X.getSectionID();
359cfca06d7SDimitry Andric     auto YSectionID = Y.getSectionID();
360cfca06d7SDimitry Andric     if (XSectionID != YSectionID)
361cfca06d7SDimitry Andric       return MBBSectionOrder(XSectionID, YSectionID);
3624df029ccSDimitry Andric     // Make sure that the entry block is placed at the beginning.
3634df029ccSDimitry Andric     if (&X == &EntryBB || &Y == &EntryBB)
3644df029ccSDimitry Andric       return &X == &EntryBB;
365cfca06d7SDimitry Andric     // If the two basic block are in the same section, the order is decided by
366cfca06d7SDimitry Andric     // their position within the section.
367cfca06d7SDimitry Andric     if (XSectionID.Type == MBBSectionID::SectionType::Default)
368b1c73532SDimitry Andric       return FuncClusterInfo.lookup(*X.getBBID()).PositionInCluster <
369b1c73532SDimitry Andric              FuncClusterInfo.lookup(*Y.getBBID()).PositionInCluster;
370cfca06d7SDimitry Andric     return X.getNumber() < Y.getNumber();
371b60736ecSDimitry Andric   };
372cfca06d7SDimitry Andric 
373b60736ecSDimitry Andric   sortBasicBlocksAndUpdateBranches(MF, Comparator);
374b60736ecSDimitry Andric   avoidZeroOffsetLandingPad(MF);
375cfca06d7SDimitry Andric   return true;
376cfca06d7SDimitry Andric }
377cfca06d7SDimitry Andric 
378ac9a064cSDimitry Andric // When the BB address map needs to be generated, this renumbers basic blocks to
379ac9a064cSDimitry Andric // make them appear in increasing order of their IDs in the function. This
380ac9a064cSDimitry Andric // avoids the need to store basic block IDs in the BB address map section, since
381ac9a064cSDimitry Andric // they can be determined implicitly.
handleBBAddrMap(MachineFunction & MF)382ac9a064cSDimitry Andric bool BasicBlockSections::handleBBAddrMap(MachineFunction &MF) {
383ac9a064cSDimitry Andric   if (MF.getTarget().getBBSectionsType() == BasicBlockSection::Labels)
384ac9a064cSDimitry Andric     return false;
385ac9a064cSDimitry Andric   if (!MF.getTarget().Options.BBAddrMap)
386ac9a064cSDimitry Andric     return false;
387ac9a064cSDimitry Andric   MF.RenumberBlocks();
388ac9a064cSDimitry Andric   return true;
389ac9a064cSDimitry Andric }
390ac9a064cSDimitry Andric 
runOnMachineFunction(MachineFunction & MF)391ac9a064cSDimitry Andric bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {
392ac9a064cSDimitry Andric   // First handle the basic block sections.
393ac9a064cSDimitry Andric   auto R1 = handleBBSections(MF);
394ac9a064cSDimitry Andric   // Handle basic block address map after basic block sections are finalized.
395ac9a064cSDimitry Andric   auto R2 = handleBBAddrMap(MF);
396ac9a064cSDimitry Andric   return R1 || R2;
397ac9a064cSDimitry Andric }
398ac9a064cSDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const399b60736ecSDimitry Andric void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {
400cfca06d7SDimitry Andric   AU.setPreservesAll();
401aca2e42cSDimitry Andric   AU.addRequired<BasicBlockSectionsProfileReaderWrapperPass>();
402cfca06d7SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
403cfca06d7SDimitry Andric }
404cfca06d7SDimitry Andric 
createBasicBlockSectionsPass()405145449b1SDimitry Andric MachineFunctionPass *llvm::createBasicBlockSectionsPass() {
406145449b1SDimitry Andric   return new BasicBlockSections();
407cfca06d7SDimitry Andric }
408