18d943a92SSnehasish Kumar //===-- BasicBlockSections.cpp ---=========--------------------------------===//
28d943a92SSnehasish Kumar //
38d943a92SSnehasish Kumar // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
48d943a92SSnehasish Kumar // See https://llvm.org/LICENSE.txt for license information.
58d943a92SSnehasish Kumar // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
68d943a92SSnehasish Kumar //
78d943a92SSnehasish Kumar //===----------------------------------------------------------------------===//
88d943a92SSnehasish Kumar //
98d943a92SSnehasish Kumar // BasicBlockSections implementation.
108d943a92SSnehasish Kumar //
118d943a92SSnehasish Kumar // The purpose of this pass is to assign sections to basic blocks when
128d943a92SSnehasish Kumar // -fbasic-block-sections= option is used. Further, with profile information
138d943a92SSnehasish Kumar // only the subset of basic blocks with profiles are placed in separate sections
148d943a92SSnehasish Kumar // and the rest are grouped in a cold section. The exception handling blocks are
158d943a92SSnehasish Kumar // treated specially to ensure they are all in one seciton.
168d943a92SSnehasish Kumar //
178d943a92SSnehasish Kumar // Basic Block Sections
188d943a92SSnehasish Kumar // ====================
198d943a92SSnehasish Kumar //
208d943a92SSnehasish Kumar // With option, -fbasic-block-sections=list, every function may be split into
218d943a92SSnehasish Kumar // clusters of basic blocks. Every cluster will be emitted into a separate
228d943a92SSnehasish Kumar // section with its basic blocks sequenced in the given order. To get the
238d943a92SSnehasish Kumar // optimized performance, the clusters must form an optimal BB layout for the
248d943a92SSnehasish Kumar // function. Every cluster's section is labeled with a symbol to allow the
258d943a92SSnehasish Kumar // linker to reorder the sections in any arbitrary sequence. A global order of
268d943a92SSnehasish Kumar // these sections would encapsulate the function layout.
278d943a92SSnehasish Kumar //
288d943a92SSnehasish Kumar // There are a couple of challenges to be addressed:
298d943a92SSnehasish Kumar //
308d943a92SSnehasish Kumar // 1. The last basic block of every cluster should not have any implicit
318d943a92SSnehasish Kumar //    fallthrough to its next basic block, as it can be reordered by the linker.
328d943a92SSnehasish Kumar //    The compiler should make these fallthroughs explicit by adding
338d943a92SSnehasish Kumar //    unconditional jumps..
348d943a92SSnehasish Kumar //
358d943a92SSnehasish Kumar // 2. All inter-cluster branch targets would now need to be resolved by the
368d943a92SSnehasish Kumar //    linker as they cannot be calculated during compile time. This is done
378d943a92SSnehasish Kumar //    using static relocations. Further, the compiler tries to use short branch
388d943a92SSnehasish Kumar //    instructions on some ISAs for small branch offsets. This is not possible
398d943a92SSnehasish Kumar //    for inter-cluster branches as the offset is not determined at compile
408d943a92SSnehasish Kumar //    time, and therefore, long branch instructions have to be used for those.
418d943a92SSnehasish Kumar //
428d943a92SSnehasish Kumar // 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission
438d943a92SSnehasish Kumar //    needs special handling with basic block sections. DebugInfo needs to be
448d943a92SSnehasish Kumar //    emitted with more relocations as basic block sections can break a
458d943a92SSnehasish Kumar //    function into potentially several disjoint pieces, and CFI needs to be
468d943a92SSnehasish Kumar //    emitted per cluster. This also bloats the object file and binary sizes.
478d943a92SSnehasish Kumar //
488d943a92SSnehasish Kumar // Basic Block Labels
498d943a92SSnehasish Kumar // ==================
508d943a92SSnehasish Kumar //
517841e21cSRahman Lavaee // With -fbasic-block-sections=labels, we emit the offsets of BB addresses of
527841e21cSRahman Lavaee // every function into a .bb_addr_map section. Along with the function symbols,
537841e21cSRahman Lavaee // this allows for mapping of virtual addresses in PMU profiles back to the
547841e21cSRahman Lavaee // corresponding basic blocks. This logic is implemented in AsmPrinter. This
557841e21cSRahman Lavaee // pass only assigns the BBSectionType of every function to ``labels``.
568d943a92SSnehasish Kumar //
578d943a92SSnehasish Kumar //===----------------------------------------------------------------------===//
588d943a92SSnehasish Kumar 
598d943a92SSnehasish Kumar #include "llvm/ADT/Optional.h"
608d943a92SSnehasish Kumar #include "llvm/ADT/SmallSet.h"
618d943a92SSnehasish Kumar #include "llvm/ADT/SmallVector.h"
628d943a92SSnehasish Kumar #include "llvm/ADT/StringMap.h"
638d943a92SSnehasish Kumar #include "llvm/ADT/StringRef.h"
6494faadacSSnehasish Kumar #include "llvm/CodeGen/BasicBlockSectionUtils.h"
658d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineFunction.h"
668d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineFunctionPass.h"
678d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineModuleInfo.h"
688d943a92SSnehasish Kumar #include "llvm/CodeGen/Passes.h"
698d943a92SSnehasish Kumar #include "llvm/CodeGen/TargetInstrInfo.h"
708d943a92SSnehasish Kumar #include "llvm/InitializePasses.h"
718d943a92SSnehasish Kumar #include "llvm/Support/Error.h"
728d943a92SSnehasish Kumar #include "llvm/Support/LineIterator.h"
738d943a92SSnehasish Kumar #include "llvm/Support/MemoryBuffer.h"
748d943a92SSnehasish Kumar #include "llvm/Target/TargetMachine.h"
758d943a92SSnehasish Kumar 
768d943a92SSnehasish Kumar using llvm::SmallSet;
778d943a92SSnehasish Kumar using llvm::SmallVector;
788d943a92SSnehasish Kumar using llvm::StringMap;
798d943a92SSnehasish Kumar using llvm::StringRef;
808d943a92SSnehasish Kumar using namespace llvm;
818d943a92SSnehasish Kumar 
82*d2696decSSnehasish Kumar // Placing the cold clusters in a separate section mitigates against poor
83*d2696decSSnehasish Kumar // profiles and allows optimizations such as hugepage mapping to be applied at a
84*d2696decSSnehasish Kumar // section granularity. Where necessary, users should set this to ".text.split."
85*d2696decSSnehasish Kumar // which is recognized by lld via the `-z keep-text-section-prefix` flag.
86*d2696decSSnehasish Kumar cl::opt<std::string> llvm::BBSectionsColdTextPrefix(
87*d2696decSSnehasish Kumar     "bbsections-cold-text-prefix",
88*d2696decSSnehasish Kumar     cl::desc("The text prefix to use for cold basic block clusters"),
89*d2696decSSnehasish Kumar     cl::init(".text.unlikely."), cl::Hidden);
90*d2696decSSnehasish Kumar 
918d943a92SSnehasish Kumar namespace {
928d943a92SSnehasish Kumar 
938d943a92SSnehasish Kumar // This struct represents the cluster information for a machine basic block.
948d943a92SSnehasish Kumar struct BBClusterInfo {
958d943a92SSnehasish Kumar   // MachineBasicBlock ID.
968d943a92SSnehasish Kumar   unsigned MBBNumber;
978d943a92SSnehasish Kumar   // Cluster ID this basic block belongs to.
988d943a92SSnehasish Kumar   unsigned ClusterID;
998d943a92SSnehasish Kumar   // Position of basic block within the cluster.
1008d943a92SSnehasish Kumar   unsigned PositionInCluster;
1018d943a92SSnehasish Kumar };
1028d943a92SSnehasish Kumar 
1038d943a92SSnehasish Kumar using ProgramBBClusterInfoMapTy = StringMap<SmallVector<BBClusterInfo, 4>>;
1048d943a92SSnehasish Kumar 
1058d943a92SSnehasish Kumar class BasicBlockSections : public MachineFunctionPass {
1068d943a92SSnehasish Kumar public:
1078d943a92SSnehasish Kumar   static char ID;
1088d943a92SSnehasish Kumar 
1098d943a92SSnehasish Kumar   // This contains the basic-block-sections profile.
1108d943a92SSnehasish Kumar   const MemoryBuffer *MBuf = nullptr;
1118d943a92SSnehasish Kumar 
1128d943a92SSnehasish Kumar   // This encapsulates the BB cluster information for the whole program.
1138d943a92SSnehasish Kumar   //
1148d943a92SSnehasish Kumar   // For every function name, it contains the cluster information for (all or
1158d943a92SSnehasish Kumar   // some of) its basic blocks. The cluster information for every basic block
1168d943a92SSnehasish Kumar   // includes its cluster ID along with the position of the basic block in that
1178d943a92SSnehasish Kumar   // cluster.
1188d943a92SSnehasish Kumar   ProgramBBClusterInfoMapTy ProgramBBClusterInfo;
1198d943a92SSnehasish Kumar 
1208d943a92SSnehasish Kumar   // Some functions have alias names. We use this map to find the main alias
1218d943a92SSnehasish Kumar   // name for which we have mapping in ProgramBBClusterInfo.
1228d943a92SSnehasish Kumar   StringMap<StringRef> FuncAliasMap;
1238d943a92SSnehasish Kumar 
1248d943a92SSnehasish Kumar   BasicBlockSections(const MemoryBuffer *Buf)
1258d943a92SSnehasish Kumar       : MachineFunctionPass(ID), MBuf(Buf) {
1268d943a92SSnehasish Kumar     initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
1278d943a92SSnehasish Kumar   };
1288d943a92SSnehasish Kumar 
1298d943a92SSnehasish Kumar   BasicBlockSections() : MachineFunctionPass(ID) {
1308d943a92SSnehasish Kumar     initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
1318d943a92SSnehasish Kumar   }
1328d943a92SSnehasish Kumar 
1338d943a92SSnehasish Kumar   StringRef getPassName() const override {
1348d943a92SSnehasish Kumar     return "Basic Block Sections Analysis";
1358d943a92SSnehasish Kumar   }
1368d943a92SSnehasish Kumar 
1378d943a92SSnehasish Kumar   void getAnalysisUsage(AnalysisUsage &AU) const override;
1388d943a92SSnehasish Kumar 
1398d943a92SSnehasish Kumar   /// Read profiles of basic blocks if available here.
1408d943a92SSnehasish Kumar   bool doInitialization(Module &M) override;
1418d943a92SSnehasish Kumar 
1428d943a92SSnehasish Kumar   /// Identify basic blocks that need separate sections and prepare to emit them
1438d943a92SSnehasish Kumar   /// accordingly.
1448d943a92SSnehasish Kumar   bool runOnMachineFunction(MachineFunction &MF) override;
1458d943a92SSnehasish Kumar };
1468d943a92SSnehasish Kumar 
1478d943a92SSnehasish Kumar } // end anonymous namespace
1488d943a92SSnehasish Kumar 
1498d943a92SSnehasish Kumar char BasicBlockSections::ID = 0;
1508d943a92SSnehasish Kumar INITIALIZE_PASS(BasicBlockSections, "bbsections-prepare",
1518d943a92SSnehasish Kumar                 "Prepares for basic block sections, by splitting functions "
1528d943a92SSnehasish Kumar                 "into clusters of basic blocks.",
1538d943a92SSnehasish Kumar                 false, false)
1548d943a92SSnehasish Kumar 
1558d943a92SSnehasish Kumar // This function updates and optimizes the branching instructions of every basic
1568d943a92SSnehasish Kumar // block in a given function to account for changes in the layout.
1578d943a92SSnehasish Kumar static void updateBranches(
1588d943a92SSnehasish Kumar     MachineFunction &MF,
1598d943a92SSnehasish Kumar     const SmallVector<MachineBasicBlock *, 4> &PreLayoutFallThroughs) {
1608d943a92SSnehasish Kumar   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1618d943a92SSnehasish Kumar   SmallVector<MachineOperand, 4> Cond;
1628d943a92SSnehasish Kumar   for (auto &MBB : MF) {
1638d943a92SSnehasish Kumar     auto NextMBBI = std::next(MBB.getIterator());
1648d943a92SSnehasish Kumar     auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];
1658d943a92SSnehasish Kumar     // If this block had a fallthrough before we need an explicit unconditional
1668d943a92SSnehasish Kumar     // branch to that block if either
1678d943a92SSnehasish Kumar     //     1- the block ends a section, which means its next block may be
1688d943a92SSnehasish Kumar     //        reorderd by the linker, or
1698d943a92SSnehasish Kumar     //     2- the fallthrough block is not adjacent to the block in the new
1708d943a92SSnehasish Kumar     //        order.
1718d943a92SSnehasish Kumar     if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))
1728d943a92SSnehasish Kumar       TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
1738d943a92SSnehasish Kumar 
1748d943a92SSnehasish Kumar     // We do not optimize branches for machine basic blocks ending sections, as
1758d943a92SSnehasish Kumar     // their adjacent block might be reordered by the linker.
1768d943a92SSnehasish Kumar     if (MBB.isEndSection())
1778d943a92SSnehasish Kumar       continue;
1788d943a92SSnehasish Kumar 
1798d943a92SSnehasish Kumar     // It might be possible to optimize branches by flipping the branch
1808d943a92SSnehasish Kumar     // condition.
1818d943a92SSnehasish Kumar     Cond.clear();
1828d943a92SSnehasish Kumar     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
1838d943a92SSnehasish Kumar     if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
1848d943a92SSnehasish Kumar       continue;
1858d943a92SSnehasish Kumar     MBB.updateTerminator(FTMBB);
1868d943a92SSnehasish Kumar   }
1878d943a92SSnehasish Kumar }
1888d943a92SSnehasish Kumar 
1898d943a92SSnehasish Kumar // This function provides the BBCluster information associated with a function.
1908d943a92SSnehasish Kumar // Returns true if a valid association exists and false otherwise.
1918d943a92SSnehasish Kumar static bool getBBClusterInfoForFunction(
1928d943a92SSnehasish Kumar     const MachineFunction &MF, const StringMap<StringRef> FuncAliasMap,
1938d943a92SSnehasish Kumar     const ProgramBBClusterInfoMapTy &ProgramBBClusterInfo,
1948d943a92SSnehasish Kumar     std::vector<Optional<BBClusterInfo>> &V) {
1958d943a92SSnehasish Kumar   // Get the main alias name for the function.
1968d943a92SSnehasish Kumar   auto FuncName = MF.getName();
1978d943a92SSnehasish Kumar   auto R = FuncAliasMap.find(FuncName);
1988d943a92SSnehasish Kumar   StringRef AliasName = R == FuncAliasMap.end() ? FuncName : R->second;
1998d943a92SSnehasish Kumar 
2008d943a92SSnehasish Kumar   // Find the assoicated cluster information.
2018d943a92SSnehasish Kumar   auto P = ProgramBBClusterInfo.find(AliasName);
2028d943a92SSnehasish Kumar   if (P == ProgramBBClusterInfo.end())
2038d943a92SSnehasish Kumar     return false;
2048d943a92SSnehasish Kumar 
2058d943a92SSnehasish Kumar   if (P->second.empty()) {
2068d943a92SSnehasish Kumar     // This indicates that sections are desired for all basic blocks of this
2078d943a92SSnehasish Kumar     // function. We clear the BBClusterInfo vector to denote this.
2088d943a92SSnehasish Kumar     V.clear();
2098d943a92SSnehasish Kumar     return true;
2108d943a92SSnehasish Kumar   }
2118d943a92SSnehasish Kumar 
2128d943a92SSnehasish Kumar   V.resize(MF.getNumBlockIDs());
2138d943a92SSnehasish Kumar   for (auto bbClusterInfo : P->second) {
2148d943a92SSnehasish Kumar     // Bail out if the cluster information contains invalid MBB numbers.
2158d943a92SSnehasish Kumar     if (bbClusterInfo.MBBNumber >= MF.getNumBlockIDs())
2168d943a92SSnehasish Kumar       return false;
2178d943a92SSnehasish Kumar     V[bbClusterInfo.MBBNumber] = bbClusterInfo;
2188d943a92SSnehasish Kumar   }
2198d943a92SSnehasish Kumar   return true;
2208d943a92SSnehasish Kumar }
2218d943a92SSnehasish Kumar 
2228d943a92SSnehasish Kumar // This function sorts basic blocks according to the cluster's information.
2238d943a92SSnehasish Kumar // All explicitly specified clusters of basic blocks will be ordered
2248d943a92SSnehasish Kumar // accordingly. All non-specified BBs go into a separate "Cold" section.
2258d943a92SSnehasish Kumar // Additionally, if exception handling landing pads end up in more than one
2268d943a92SSnehasish Kumar // clusters, they are moved into a single "Exception" section. Eventually,
2278d943a92SSnehasish Kumar // clusters are ordered in increasing order of their IDs, with the "Exception"
2288d943a92SSnehasish Kumar // and "Cold" succeeding all other clusters.
2298d943a92SSnehasish Kumar // FuncBBClusterInfo represent the cluster information for basic blocks. If this
2308d943a92SSnehasish Kumar // is empty, it means unique sections for all basic blocks in the function.
23194faadacSSnehasish Kumar static void
23294faadacSSnehasish Kumar assignSections(MachineFunction &MF,
2338d943a92SSnehasish Kumar                const std::vector<Optional<BBClusterInfo>> &FuncBBClusterInfo) {
2348d943a92SSnehasish Kumar   assert(MF.hasBBSections() && "BB Sections is not set for function.");
2358d943a92SSnehasish Kumar   // This variable stores the section ID of the cluster containing eh_pads (if
2368d943a92SSnehasish Kumar   // all eh_pads are one cluster). If more than one cluster contain eh_pads, we
2378d943a92SSnehasish Kumar   // set it equal to ExceptionSectionID.
2388d943a92SSnehasish Kumar   Optional<MBBSectionID> EHPadsSectionID;
2398d943a92SSnehasish Kumar 
2408d943a92SSnehasish Kumar   for (auto &MBB : MF) {
2418d943a92SSnehasish Kumar     // With the 'all' option, every basic block is placed in a unique section.
2428d943a92SSnehasish Kumar     // With the 'list' option, every basic block is placed in a section
2438d943a92SSnehasish Kumar     // associated with its cluster, unless we want individual unique sections
2448d943a92SSnehasish Kumar     // for every basic block in this function (if FuncBBClusterInfo is empty).
2458d943a92SSnehasish Kumar     if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All ||
2468d943a92SSnehasish Kumar         FuncBBClusterInfo.empty()) {
2478d943a92SSnehasish Kumar       // If unique sections are desired for all basic blocks of the function, we
2488d943a92SSnehasish Kumar       // set every basic block's section ID equal to its number (basic block
2498d943a92SSnehasish Kumar       // id). This further ensures that basic blocks are ordered canonically.
2508d943a92SSnehasish Kumar       MBB.setSectionID({static_cast<unsigned int>(MBB.getNumber())});
2518d943a92SSnehasish Kumar     } else if (FuncBBClusterInfo[MBB.getNumber()].hasValue())
2528d943a92SSnehasish Kumar       MBB.setSectionID(FuncBBClusterInfo[MBB.getNumber()]->ClusterID);
2538d943a92SSnehasish Kumar     else {
2548d943a92SSnehasish Kumar       // BB goes into the special cold section if it is not specified in the
2558d943a92SSnehasish Kumar       // cluster info map.
2568d943a92SSnehasish Kumar       MBB.setSectionID(MBBSectionID::ColdSectionID);
2578d943a92SSnehasish Kumar     }
2588d943a92SSnehasish Kumar 
2598d943a92SSnehasish Kumar     if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&
2608d943a92SSnehasish Kumar         EHPadsSectionID != MBBSectionID::ExceptionSectionID) {
2618d943a92SSnehasish Kumar       // If we already have one cluster containing eh_pads, this must be updated
2628d943a92SSnehasish Kumar       // to ExceptionSectionID. Otherwise, we set it equal to the current
2638d943a92SSnehasish Kumar       // section ID.
2648d943a92SSnehasish Kumar       EHPadsSectionID = EHPadsSectionID.hasValue()
2658d943a92SSnehasish Kumar                             ? MBBSectionID::ExceptionSectionID
2668d943a92SSnehasish Kumar                             : MBB.getSectionID();
2678d943a92SSnehasish Kumar     }
2688d943a92SSnehasish Kumar   }
2698d943a92SSnehasish Kumar 
2708d943a92SSnehasish Kumar   // If EHPads are in more than one section, this places all of them in the
2718d943a92SSnehasish Kumar   // special exception section.
2728d943a92SSnehasish Kumar   if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)
2738d943a92SSnehasish Kumar     for (auto &MBB : MF)
2748d943a92SSnehasish Kumar       if (MBB.isEHPad())
2758d943a92SSnehasish Kumar         MBB.setSectionID(EHPadsSectionID.getValue());
27694faadacSSnehasish Kumar }
2778d943a92SSnehasish Kumar 
27894faadacSSnehasish Kumar void llvm::sortBasicBlocksAndUpdateBranches(
27994faadacSSnehasish Kumar     MachineFunction &MF, MachineBasicBlockComparator MBBCmp) {
2808d943a92SSnehasish Kumar   SmallVector<MachineBasicBlock *, 4> PreLayoutFallThroughs(
2818d943a92SSnehasish Kumar       MF.getNumBlockIDs());
2828d943a92SSnehasish Kumar   for (auto &MBB : MF)
2838d943a92SSnehasish Kumar     PreLayoutFallThroughs[MBB.getNumber()] = MBB.getFallThrough();
2848d943a92SSnehasish Kumar 
28594faadacSSnehasish Kumar   MF.sort(MBBCmp);
2868d943a92SSnehasish Kumar 
2878d943a92SSnehasish Kumar   // Set IsBeginSection and IsEndSection according to the assigned section IDs.
2888d943a92SSnehasish Kumar   MF.assignBeginEndSections();
2898d943a92SSnehasish Kumar 
2908d943a92SSnehasish Kumar   // After reordering basic blocks, we must update basic block branches to
2918d943a92SSnehasish Kumar   // insert explicit fallthrough branches when required and optimize branches
2928d943a92SSnehasish Kumar   // when possible.
2938d943a92SSnehasish Kumar   updateBranches(MF, PreLayoutFallThroughs);
2948d943a92SSnehasish Kumar }
2958d943a92SSnehasish Kumar 
2968d943a92SSnehasish Kumar bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {
2978d943a92SSnehasish Kumar   auto BBSectionsType = MF.getTarget().getBBSectionsType();
2988d943a92SSnehasish Kumar   assert(BBSectionsType != BasicBlockSection::None &&
2998d943a92SSnehasish Kumar          "BB Sections not enabled!");
3008d943a92SSnehasish Kumar   // Renumber blocks before sorting them for basic block sections.  This is
3018d943a92SSnehasish Kumar   // useful during sorting, basic blocks in the same section will retain the
3028d943a92SSnehasish Kumar   // default order.  This renumbering should also be done for basic block
3038d943a92SSnehasish Kumar   // labels to match the profiles with the correct blocks.
3048d943a92SSnehasish Kumar   MF.RenumberBlocks();
3058d943a92SSnehasish Kumar 
3068d943a92SSnehasish Kumar   if (BBSectionsType == BasicBlockSection::Labels) {
3078d943a92SSnehasish Kumar     MF.setBBSectionsType(BBSectionsType);
3088d943a92SSnehasish Kumar     return true;
3098d943a92SSnehasish Kumar   }
3108d943a92SSnehasish Kumar 
3118d943a92SSnehasish Kumar   std::vector<Optional<BBClusterInfo>> FuncBBClusterInfo;
3128d943a92SSnehasish Kumar   if (BBSectionsType == BasicBlockSection::List &&
3138d943a92SSnehasish Kumar       !getBBClusterInfoForFunction(MF, FuncAliasMap, ProgramBBClusterInfo,
3148d943a92SSnehasish Kumar                                    FuncBBClusterInfo))
3158d943a92SSnehasish Kumar     return true;
3168d943a92SSnehasish Kumar   MF.setBBSectionsType(BBSectionsType);
31794faadacSSnehasish Kumar   assignSections(MF, FuncBBClusterInfo);
31894faadacSSnehasish Kumar 
31994faadacSSnehasish Kumar   // We make sure that the cluster including the entry basic block precedes all
32094faadacSSnehasish Kumar   // other clusters.
32194faadacSSnehasish Kumar   auto EntryBBSectionID = MF.front().getSectionID();
32294faadacSSnehasish Kumar 
32394faadacSSnehasish Kumar   // Helper function for ordering BB sections as follows:
32494faadacSSnehasish Kumar   //   * Entry section (section including the entry block).
32594faadacSSnehasish Kumar   //   * Regular sections (in increasing order of their Number).
32694faadacSSnehasish Kumar   //     ...
32794faadacSSnehasish Kumar   //   * Exception section
32894faadacSSnehasish Kumar   //   * Cold section
32994faadacSSnehasish Kumar   auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,
33094faadacSSnehasish Kumar                                             const MBBSectionID &RHS) {
33194faadacSSnehasish Kumar     // We make sure that the section containing the entry block precedes all the
33294faadacSSnehasish Kumar     // other sections.
33394faadacSSnehasish Kumar     if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)
33494faadacSSnehasish Kumar       return LHS == EntryBBSectionID;
33594faadacSSnehasish Kumar     return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;
33694faadacSSnehasish Kumar   };
33794faadacSSnehasish Kumar 
33894faadacSSnehasish Kumar   // We sort all basic blocks to make sure the basic blocks of every cluster are
33994faadacSSnehasish Kumar   // contiguous and ordered accordingly. Furthermore, clusters are ordered in
34094faadacSSnehasish Kumar   // increasing order of their section IDs, with the exception and the
34194faadacSSnehasish Kumar   // cold section placed at the end of the function.
34294faadacSSnehasish Kumar   auto Comparator = [&](const MachineBasicBlock &X,
34394faadacSSnehasish Kumar                         const MachineBasicBlock &Y) {
34494faadacSSnehasish Kumar     auto XSectionID = X.getSectionID();
34594faadacSSnehasish Kumar     auto YSectionID = Y.getSectionID();
34694faadacSSnehasish Kumar     if (XSectionID != YSectionID)
34794faadacSSnehasish Kumar       return MBBSectionOrder(XSectionID, YSectionID);
34894faadacSSnehasish Kumar     // If the two basic block are in the same section, the order is decided by
34994faadacSSnehasish Kumar     // their position within the section.
35094faadacSSnehasish Kumar     if (XSectionID.Type == MBBSectionID::SectionType::Default)
35194faadacSSnehasish Kumar       return FuncBBClusterInfo[X.getNumber()]->PositionInCluster <
35294faadacSSnehasish Kumar              FuncBBClusterInfo[Y.getNumber()]->PositionInCluster;
35394faadacSSnehasish Kumar     return X.getNumber() < Y.getNumber();
35494faadacSSnehasish Kumar   };
35594faadacSSnehasish Kumar 
35694faadacSSnehasish Kumar   sortBasicBlocksAndUpdateBranches(MF, Comparator);
3578d943a92SSnehasish Kumar   return true;
3588d943a92SSnehasish Kumar }
3598d943a92SSnehasish Kumar 
3608d943a92SSnehasish Kumar // Basic Block Sections can be enabled for a subset of machine basic blocks.
3618d943a92SSnehasish Kumar // This is done by passing a file containing names of functions for which basic
3628d943a92SSnehasish Kumar // block sections are desired.  Additionally, machine basic block ids of the
3638d943a92SSnehasish Kumar // functions can also be specified for a finer granularity. Moreover, a cluster
3648d943a92SSnehasish Kumar // of basic blocks could be assigned to the same section.
3658d943a92SSnehasish Kumar // A file with basic block sections for all of function main and three blocks
3668d943a92SSnehasish Kumar // for function foo (of which 1 and 2 are placed in a cluster) looks like this:
3678d943a92SSnehasish Kumar // ----------------------------
3688d943a92SSnehasish Kumar // list.txt:
3698d943a92SSnehasish Kumar // !main
3708d943a92SSnehasish Kumar // !foo
3718d943a92SSnehasish Kumar // !!1 2
3728d943a92SSnehasish Kumar // !!4
3738d943a92SSnehasish Kumar static Error getBBClusterInfo(const MemoryBuffer *MBuf,
3748d943a92SSnehasish Kumar                               ProgramBBClusterInfoMapTy &ProgramBBClusterInfo,
3758d943a92SSnehasish Kumar                               StringMap<StringRef> &FuncAliasMap) {
3768d943a92SSnehasish Kumar   assert(MBuf);
3778d943a92SSnehasish Kumar   line_iterator LineIt(*MBuf, /*SkipBlanks=*/true, /*CommentMarker=*/'#');
3788d943a92SSnehasish Kumar 
3798d943a92SSnehasish Kumar   auto invalidProfileError = [&](auto Message) {
3808d943a92SSnehasish Kumar     return make_error<StringError>(
3818d943a92SSnehasish Kumar         Twine("Invalid profile " + MBuf->getBufferIdentifier() + " at line " +
3828d943a92SSnehasish Kumar               Twine(LineIt.line_number()) + ": " + Message),
3838d943a92SSnehasish Kumar         inconvertibleErrorCode());
3848d943a92SSnehasish Kumar   };
3858d943a92SSnehasish Kumar 
3868d943a92SSnehasish Kumar   auto FI = ProgramBBClusterInfo.end();
3878d943a92SSnehasish Kumar 
3888d943a92SSnehasish Kumar   // Current cluster ID corresponding to this function.
3898d943a92SSnehasish Kumar   unsigned CurrentCluster = 0;
3908d943a92SSnehasish Kumar   // Current position in the current cluster.
3918d943a92SSnehasish Kumar   unsigned CurrentPosition = 0;
3928d943a92SSnehasish Kumar 
3938d943a92SSnehasish Kumar   // Temporary set to ensure every basic block ID appears once in the clusters
3948d943a92SSnehasish Kumar   // of a function.
3958d943a92SSnehasish Kumar   SmallSet<unsigned, 4> FuncBBIDs;
3968d943a92SSnehasish Kumar 
3978d943a92SSnehasish Kumar   for (; !LineIt.is_at_eof(); ++LineIt) {
3988d943a92SSnehasish Kumar     StringRef S(*LineIt);
3998d943a92SSnehasish Kumar     if (S[0] == '@')
4008d943a92SSnehasish Kumar       continue;
4018d943a92SSnehasish Kumar     // Check for the leading "!"
4028d943a92SSnehasish Kumar     if (!S.consume_front("!") || S.empty())
4038d943a92SSnehasish Kumar       break;
4048d943a92SSnehasish Kumar     // Check for second "!" which indicates a cluster of basic blocks.
4058d943a92SSnehasish Kumar     if (S.consume_front("!")) {
4068d943a92SSnehasish Kumar       if (FI == ProgramBBClusterInfo.end())
4078d943a92SSnehasish Kumar         return invalidProfileError(
4088d943a92SSnehasish Kumar             "Cluster list does not follow a function name specifier.");
4098d943a92SSnehasish Kumar       SmallVector<StringRef, 4> BBIndexes;
4108d943a92SSnehasish Kumar       S.split(BBIndexes, ' ');
4118d943a92SSnehasish Kumar       // Reset current cluster position.
4128d943a92SSnehasish Kumar       CurrentPosition = 0;
4138d943a92SSnehasish Kumar       for (auto BBIndexStr : BBIndexes) {
4148d943a92SSnehasish Kumar         unsigned long long BBIndex;
4158d943a92SSnehasish Kumar         if (getAsUnsignedInteger(BBIndexStr, 10, BBIndex))
4168d943a92SSnehasish Kumar           return invalidProfileError(Twine("Unsigned integer expected: '") +
4178d943a92SSnehasish Kumar                                      BBIndexStr + "'.");
4188d943a92SSnehasish Kumar         if (!FuncBBIDs.insert(BBIndex).second)
4198d943a92SSnehasish Kumar           return invalidProfileError(Twine("Duplicate basic block id found '") +
4208d943a92SSnehasish Kumar                                      BBIndexStr + "'.");
4218d943a92SSnehasish Kumar         if (!BBIndex && CurrentPosition)
4228d943a92SSnehasish Kumar           return invalidProfileError("Entry BB (0) does not begin a cluster.");
4238d943a92SSnehasish Kumar 
4248d943a92SSnehasish Kumar         FI->second.emplace_back(BBClusterInfo{
4258d943a92SSnehasish Kumar             ((unsigned)BBIndex), CurrentCluster, CurrentPosition++});
4268d943a92SSnehasish Kumar       }
4278d943a92SSnehasish Kumar       CurrentCluster++;
4288d943a92SSnehasish Kumar     } else { // This is a function name specifier.
4298d943a92SSnehasish Kumar       // Function aliases are separated using '/'. We use the first function
4308d943a92SSnehasish Kumar       // name for the cluster info mapping and delegate all other aliases to
4318d943a92SSnehasish Kumar       // this one.
4328d943a92SSnehasish Kumar       SmallVector<StringRef, 4> Aliases;
4338d943a92SSnehasish Kumar       S.split(Aliases, '/');
4348d943a92SSnehasish Kumar       for (size_t i = 1; i < Aliases.size(); ++i)
4358d943a92SSnehasish Kumar         FuncAliasMap.try_emplace(Aliases[i], Aliases.front());
4368d943a92SSnehasish Kumar 
4378d943a92SSnehasish Kumar       // Prepare for parsing clusters of this function name.
4388d943a92SSnehasish Kumar       // Start a new cluster map for this function name.
4398d943a92SSnehasish Kumar       FI = ProgramBBClusterInfo.try_emplace(Aliases.front()).first;
4408d943a92SSnehasish Kumar       CurrentCluster = 0;
4418d943a92SSnehasish Kumar       FuncBBIDs.clear();
4428d943a92SSnehasish Kumar     }
4438d943a92SSnehasish Kumar   }
4448d943a92SSnehasish Kumar   return Error::success();
4458d943a92SSnehasish Kumar }
4468d943a92SSnehasish Kumar 
4478d943a92SSnehasish Kumar bool BasicBlockSections::doInitialization(Module &M) {
4488d943a92SSnehasish Kumar   if (!MBuf)
4498d943a92SSnehasish Kumar     return false;
4508d943a92SSnehasish Kumar   if (auto Err = getBBClusterInfo(MBuf, ProgramBBClusterInfo, FuncAliasMap))
4518d943a92SSnehasish Kumar     report_fatal_error(std::move(Err));
4528d943a92SSnehasish Kumar   return false;
4538d943a92SSnehasish Kumar }
4548d943a92SSnehasish Kumar 
4558d943a92SSnehasish Kumar void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {
4568d943a92SSnehasish Kumar   AU.setPreservesAll();
4578d943a92SSnehasish Kumar   MachineFunctionPass::getAnalysisUsage(AU);
4588d943a92SSnehasish Kumar }
4598d943a92SSnehasish Kumar 
4608d943a92SSnehasish Kumar MachineFunctionPass *
4618d943a92SSnehasish Kumar llvm::createBasicBlockSectionsPass(const MemoryBuffer *Buf) {
4628d943a92SSnehasish Kumar   return new BasicBlockSections(Buf);
4638d943a92SSnehasish Kumar }
464