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
24*2256b359SRahman Lavaee // function. We insert a symbol at the beginning of every cluster's section to
25*2256b359SRahman Lavaee // allow the linker to reorder the sections in any arbitrary sequence. A global
26*2256b359SRahman Lavaee // order of these sections would encapsulate the function layout.
27*2256b359SRahman Lavaee // For example, consider the following clusters for a function foo (consisting
28*2256b359SRahman Lavaee // of 6 basic blocks 0, 1, ..., 5).
29*2256b359SRahman Lavaee //
30*2256b359SRahman Lavaee // 0 2
31*2256b359SRahman Lavaee // 1 3 5
32*2256b359SRahman Lavaee //
33*2256b359SRahman Lavaee // * Basic blocks 0 and 2 are placed in one section with symbol `foo`
34*2256b359SRahman Lavaee //   referencing the beginning of this section.
35*2256b359SRahman Lavaee // * Basic blocks 1, 3, 5 are placed in a separate section. A new symbol
36*2256b359SRahman Lavaee //   `foo.__part.1` will reference the beginning of this section.
37*2256b359SRahman Lavaee // * Basic block 4 (note that it is not referenced in the list) is placed in
38*2256b359SRahman Lavaee //   one section, and a new symbol `foo.cold` will point to it.
398d943a92SSnehasish Kumar //
408d943a92SSnehasish Kumar // There are a couple of challenges to be addressed:
418d943a92SSnehasish Kumar //
428d943a92SSnehasish Kumar // 1. The last basic block of every cluster should not have any implicit
438d943a92SSnehasish Kumar //    fallthrough to its next basic block, as it can be reordered by the linker.
448d943a92SSnehasish Kumar //    The compiler should make these fallthroughs explicit by adding
458d943a92SSnehasish Kumar //    unconditional jumps..
468d943a92SSnehasish Kumar //
478d943a92SSnehasish Kumar // 2. All inter-cluster branch targets would now need to be resolved by the
488d943a92SSnehasish Kumar //    linker as they cannot be calculated during compile time. This is done
498d943a92SSnehasish Kumar //    using static relocations. Further, the compiler tries to use short branch
508d943a92SSnehasish Kumar //    instructions on some ISAs for small branch offsets. This is not possible
518d943a92SSnehasish Kumar //    for inter-cluster branches as the offset is not determined at compile
528d943a92SSnehasish Kumar //    time, and therefore, long branch instructions have to be used for those.
538d943a92SSnehasish Kumar //
548d943a92SSnehasish Kumar // 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission
558d943a92SSnehasish Kumar //    needs special handling with basic block sections. DebugInfo needs to be
568d943a92SSnehasish Kumar //    emitted with more relocations as basic block sections can break a
578d943a92SSnehasish Kumar //    function into potentially several disjoint pieces, and CFI needs to be
588d943a92SSnehasish Kumar //    emitted per cluster. This also bloats the object file and binary sizes.
598d943a92SSnehasish Kumar //
608d943a92SSnehasish Kumar // Basic Block Labels
618d943a92SSnehasish Kumar // ==================
628d943a92SSnehasish Kumar //
637841e21cSRahman Lavaee // With -fbasic-block-sections=labels, we emit the offsets of BB addresses of
642b0c5d76SRahman Lavaee // every function into the .llvm_bb_addr_map section. Along with the function
652b0c5d76SRahman Lavaee // symbols, this allows for mapping of virtual addresses in PMU profiles back to
662b0c5d76SRahman Lavaee // the corresponding basic blocks. This logic is implemented in AsmPrinter. This
677841e21cSRahman Lavaee // pass only assigns the BBSectionType of every function to ``labels``.
688d943a92SSnehasish Kumar //
698d943a92SSnehasish Kumar //===----------------------------------------------------------------------===//
708d943a92SSnehasish Kumar 
718d943a92SSnehasish Kumar #include "llvm/ADT/Optional.h"
728d943a92SSnehasish Kumar #include "llvm/ADT/SmallSet.h"
738d943a92SSnehasish Kumar #include "llvm/ADT/SmallVector.h"
748d943a92SSnehasish Kumar #include "llvm/ADT/StringMap.h"
758d943a92SSnehasish Kumar #include "llvm/ADT/StringRef.h"
7694faadacSSnehasish Kumar #include "llvm/CodeGen/BasicBlockSectionUtils.h"
778d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineFunction.h"
788d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineFunctionPass.h"
798d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineModuleInfo.h"
808d943a92SSnehasish Kumar #include "llvm/CodeGen/Passes.h"
818d943a92SSnehasish Kumar #include "llvm/CodeGen/TargetInstrInfo.h"
828d943a92SSnehasish Kumar #include "llvm/InitializePasses.h"
838d943a92SSnehasish Kumar #include "llvm/Support/Error.h"
848d943a92SSnehasish Kumar #include "llvm/Support/LineIterator.h"
858d943a92SSnehasish Kumar #include "llvm/Support/MemoryBuffer.h"
868d943a92SSnehasish Kumar #include "llvm/Target/TargetMachine.h"
878d943a92SSnehasish Kumar 
888d943a92SSnehasish Kumar using llvm::SmallSet;
898d943a92SSnehasish Kumar using llvm::SmallVector;
908d943a92SSnehasish Kumar using llvm::StringMap;
918d943a92SSnehasish Kumar using llvm::StringRef;
928d943a92SSnehasish Kumar using namespace llvm;
938d943a92SSnehasish Kumar 
94d2696decSSnehasish Kumar // Placing the cold clusters in a separate section mitigates against poor
95d2696decSSnehasish Kumar // profiles and allows optimizations such as hugepage mapping to be applied at a
9677638a53SSnehasish Kumar // section granularity. Defaults to ".text.split." which is recognized by lld
9777638a53SSnehasish Kumar // via the `-z keep-text-section-prefix` flag.
98d2696decSSnehasish Kumar cl::opt<std::string> llvm::BBSectionsColdTextPrefix(
99d2696decSSnehasish Kumar     "bbsections-cold-text-prefix",
100d2696decSSnehasish Kumar     cl::desc("The text prefix to use for cold basic block clusters"),
10177638a53SSnehasish Kumar     cl::init(".text.split."), cl::Hidden);
102d2696decSSnehasish Kumar 
103c32f3998SSriraman Tallam cl::opt<bool> BBSectionsDetectSourceDrift(
104c32f3998SSriraman Tallam     "bbsections-detect-source-drift",
105c32f3998SSriraman Tallam     cl::desc("This checks if there is a fdo instr. profile hash "
106c32f3998SSriraman Tallam              "mismatch for this function"),
107c32f3998SSriraman Tallam     cl::init(true), cl::Hidden);
108c32f3998SSriraman Tallam 
1098d943a92SSnehasish Kumar namespace {
1108d943a92SSnehasish Kumar 
1118d943a92SSnehasish Kumar // This struct represents the cluster information for a machine basic block.
1128d943a92SSnehasish Kumar struct BBClusterInfo {
1138d943a92SSnehasish Kumar   // MachineBasicBlock ID.
1148d943a92SSnehasish Kumar   unsigned MBBNumber;
1158d943a92SSnehasish Kumar   // Cluster ID this basic block belongs to.
1168d943a92SSnehasish Kumar   unsigned ClusterID;
1178d943a92SSnehasish Kumar   // Position of basic block within the cluster.
1188d943a92SSnehasish Kumar   unsigned PositionInCluster;
1198d943a92SSnehasish Kumar };
1208d943a92SSnehasish Kumar 
1218d943a92SSnehasish Kumar using ProgramBBClusterInfoMapTy = StringMap<SmallVector<BBClusterInfo, 4>>;
1228d943a92SSnehasish Kumar 
1238d943a92SSnehasish Kumar class BasicBlockSections : public MachineFunctionPass {
1248d943a92SSnehasish Kumar public:
1258d943a92SSnehasish Kumar   static char ID;
1268d943a92SSnehasish Kumar 
1278d943a92SSnehasish Kumar   // This contains the basic-block-sections profile.
1288d943a92SSnehasish Kumar   const MemoryBuffer *MBuf = nullptr;
1298d943a92SSnehasish Kumar 
1308d943a92SSnehasish Kumar   // This encapsulates the BB cluster information for the whole program.
1318d943a92SSnehasish Kumar   //
1328d943a92SSnehasish Kumar   // For every function name, it contains the cluster information for (all or
1338d943a92SSnehasish Kumar   // some of) its basic blocks. The cluster information for every basic block
1348d943a92SSnehasish Kumar   // includes its cluster ID along with the position of the basic block in that
1358d943a92SSnehasish Kumar   // cluster.
1368d943a92SSnehasish Kumar   ProgramBBClusterInfoMapTy ProgramBBClusterInfo;
1378d943a92SSnehasish Kumar 
1388d943a92SSnehasish Kumar   // Some functions have alias names. We use this map to find the main alias
1398d943a92SSnehasish Kumar   // name for which we have mapping in ProgramBBClusterInfo.
1408d943a92SSnehasish Kumar   StringMap<StringRef> FuncAliasMap;
1418d943a92SSnehasish Kumar 
1428d943a92SSnehasish Kumar   BasicBlockSections(const MemoryBuffer *Buf)
1438d943a92SSnehasish Kumar       : MachineFunctionPass(ID), MBuf(Buf) {
1448d943a92SSnehasish Kumar     initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
1458d943a92SSnehasish Kumar   };
1468d943a92SSnehasish Kumar 
1478d943a92SSnehasish Kumar   BasicBlockSections() : MachineFunctionPass(ID) {
1488d943a92SSnehasish Kumar     initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
1498d943a92SSnehasish Kumar   }
1508d943a92SSnehasish Kumar 
1518d943a92SSnehasish Kumar   StringRef getPassName() const override {
1528d943a92SSnehasish Kumar     return "Basic Block Sections Analysis";
1538d943a92SSnehasish Kumar   }
1548d943a92SSnehasish Kumar 
1558d943a92SSnehasish Kumar   void getAnalysisUsage(AnalysisUsage &AU) const override;
1568d943a92SSnehasish Kumar 
1578d943a92SSnehasish Kumar   /// Read profiles of basic blocks if available here.
1588d943a92SSnehasish Kumar   bool doInitialization(Module &M) override;
1598d943a92SSnehasish Kumar 
1608d943a92SSnehasish Kumar   /// Identify basic blocks that need separate sections and prepare to emit them
1618d943a92SSnehasish Kumar   /// accordingly.
1628d943a92SSnehasish Kumar   bool runOnMachineFunction(MachineFunction &MF) override;
1638d943a92SSnehasish Kumar };
1648d943a92SSnehasish Kumar 
1658d943a92SSnehasish Kumar } // end anonymous namespace
1668d943a92SSnehasish Kumar 
1678d943a92SSnehasish Kumar char BasicBlockSections::ID = 0;
1688d943a92SSnehasish Kumar INITIALIZE_PASS(BasicBlockSections, "bbsections-prepare",
1698d943a92SSnehasish Kumar                 "Prepares for basic block sections, by splitting functions "
1708d943a92SSnehasish Kumar                 "into clusters of basic blocks.",
1718d943a92SSnehasish Kumar                 false, false)
1728d943a92SSnehasish Kumar 
1738d943a92SSnehasish Kumar // This function updates and optimizes the branching instructions of every basic
1748d943a92SSnehasish Kumar // block in a given function to account for changes in the layout.
1758d943a92SSnehasish Kumar static void updateBranches(
1768d943a92SSnehasish Kumar     MachineFunction &MF,
1778d943a92SSnehasish Kumar     const SmallVector<MachineBasicBlock *, 4> &PreLayoutFallThroughs) {
1788d943a92SSnehasish Kumar   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1798d943a92SSnehasish Kumar   SmallVector<MachineOperand, 4> Cond;
1808d943a92SSnehasish Kumar   for (auto &MBB : MF) {
1818d943a92SSnehasish Kumar     auto NextMBBI = std::next(MBB.getIterator());
1828d943a92SSnehasish Kumar     auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];
1838d943a92SSnehasish Kumar     // If this block had a fallthrough before we need an explicit unconditional
1848d943a92SSnehasish Kumar     // branch to that block if either
1858d943a92SSnehasish Kumar     //     1- the block ends a section, which means its next block may be
1868d943a92SSnehasish Kumar     //        reorderd by the linker, or
1878d943a92SSnehasish Kumar     //     2- the fallthrough block is not adjacent to the block in the new
1888d943a92SSnehasish Kumar     //        order.
1898d943a92SSnehasish Kumar     if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))
1908d943a92SSnehasish Kumar       TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
1918d943a92SSnehasish Kumar 
1928d943a92SSnehasish Kumar     // We do not optimize branches for machine basic blocks ending sections, as
1938d943a92SSnehasish Kumar     // their adjacent block might be reordered by the linker.
1948d943a92SSnehasish Kumar     if (MBB.isEndSection())
1958d943a92SSnehasish Kumar       continue;
1968d943a92SSnehasish Kumar 
1978d943a92SSnehasish Kumar     // It might be possible to optimize branches by flipping the branch
1988d943a92SSnehasish Kumar     // condition.
1998d943a92SSnehasish Kumar     Cond.clear();
2008d943a92SSnehasish Kumar     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
2018d943a92SSnehasish Kumar     if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
2028d943a92SSnehasish Kumar       continue;
2038d943a92SSnehasish Kumar     MBB.updateTerminator(FTMBB);
2048d943a92SSnehasish Kumar   }
2058d943a92SSnehasish Kumar }
2068d943a92SSnehasish Kumar 
2078d943a92SSnehasish Kumar // This function provides the BBCluster information associated with a function.
2088d943a92SSnehasish Kumar // Returns true if a valid association exists and false otherwise.
2098d943a92SSnehasish Kumar static bool getBBClusterInfoForFunction(
2108d943a92SSnehasish Kumar     const MachineFunction &MF, const StringMap<StringRef> FuncAliasMap,
2118d943a92SSnehasish Kumar     const ProgramBBClusterInfoMapTy &ProgramBBClusterInfo,
2128d943a92SSnehasish Kumar     std::vector<Optional<BBClusterInfo>> &V) {
2138d943a92SSnehasish Kumar   // Get the main alias name for the function.
2148d943a92SSnehasish Kumar   auto FuncName = MF.getName();
2158d943a92SSnehasish Kumar   auto R = FuncAliasMap.find(FuncName);
2168d943a92SSnehasish Kumar   StringRef AliasName = R == FuncAliasMap.end() ? FuncName : R->second;
2178d943a92SSnehasish Kumar 
2188d943a92SSnehasish Kumar   // Find the assoicated cluster information.
2198d943a92SSnehasish Kumar   auto P = ProgramBBClusterInfo.find(AliasName);
2208d943a92SSnehasish Kumar   if (P == ProgramBBClusterInfo.end())
2218d943a92SSnehasish Kumar     return false;
2228d943a92SSnehasish Kumar 
2238d943a92SSnehasish Kumar   if (P->second.empty()) {
2248d943a92SSnehasish Kumar     // This indicates that sections are desired for all basic blocks of this
2258d943a92SSnehasish Kumar     // function. We clear the BBClusterInfo vector to denote this.
2268d943a92SSnehasish Kumar     V.clear();
2278d943a92SSnehasish Kumar     return true;
2288d943a92SSnehasish Kumar   }
2298d943a92SSnehasish Kumar 
2308d943a92SSnehasish Kumar   V.resize(MF.getNumBlockIDs());
2318d943a92SSnehasish Kumar   for (auto bbClusterInfo : P->second) {
2328d943a92SSnehasish Kumar     // Bail out if the cluster information contains invalid MBB numbers.
2338d943a92SSnehasish Kumar     if (bbClusterInfo.MBBNumber >= MF.getNumBlockIDs())
2348d943a92SSnehasish Kumar       return false;
2358d943a92SSnehasish Kumar     V[bbClusterInfo.MBBNumber] = bbClusterInfo;
2368d943a92SSnehasish Kumar   }
2378d943a92SSnehasish Kumar   return true;
2388d943a92SSnehasish Kumar }
2398d943a92SSnehasish Kumar 
2408d943a92SSnehasish Kumar // This function sorts basic blocks according to the cluster's information.
2418d943a92SSnehasish Kumar // All explicitly specified clusters of basic blocks will be ordered
2428d943a92SSnehasish Kumar // accordingly. All non-specified BBs go into a separate "Cold" section.
2438d943a92SSnehasish Kumar // Additionally, if exception handling landing pads end up in more than one
2448d943a92SSnehasish Kumar // clusters, they are moved into a single "Exception" section. Eventually,
2458d943a92SSnehasish Kumar // clusters are ordered in increasing order of their IDs, with the "Exception"
2468d943a92SSnehasish Kumar // and "Cold" succeeding all other clusters.
2478d943a92SSnehasish Kumar // FuncBBClusterInfo represent the cluster information for basic blocks. If this
2488d943a92SSnehasish Kumar // is empty, it means unique sections for all basic blocks in the function.
24994faadacSSnehasish Kumar static void
25094faadacSSnehasish Kumar assignSections(MachineFunction &MF,
2518d943a92SSnehasish Kumar                const std::vector<Optional<BBClusterInfo>> &FuncBBClusterInfo) {
2528d943a92SSnehasish Kumar   assert(MF.hasBBSections() && "BB Sections is not set for function.");
2538d943a92SSnehasish Kumar   // This variable stores the section ID of the cluster containing eh_pads (if
2548d943a92SSnehasish Kumar   // all eh_pads are one cluster). If more than one cluster contain eh_pads, we
2558d943a92SSnehasish Kumar   // set it equal to ExceptionSectionID.
2568d943a92SSnehasish Kumar   Optional<MBBSectionID> EHPadsSectionID;
2578d943a92SSnehasish Kumar 
2588d943a92SSnehasish Kumar   for (auto &MBB : MF) {
2598d943a92SSnehasish Kumar     // With the 'all' option, every basic block is placed in a unique section.
2608d943a92SSnehasish Kumar     // With the 'list' option, every basic block is placed in a section
2618d943a92SSnehasish Kumar     // associated with its cluster, unless we want individual unique sections
2628d943a92SSnehasish Kumar     // for every basic block in this function (if FuncBBClusterInfo is empty).
2638d943a92SSnehasish Kumar     if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All ||
2648d943a92SSnehasish Kumar         FuncBBClusterInfo.empty()) {
2658d943a92SSnehasish Kumar       // If unique sections are desired for all basic blocks of the function, we
2668d943a92SSnehasish Kumar       // set every basic block's section ID equal to its number (basic block
2678d943a92SSnehasish Kumar       // id). This further ensures that basic blocks are ordered canonically.
2688d943a92SSnehasish Kumar       MBB.setSectionID({static_cast<unsigned int>(MBB.getNumber())});
2698d943a92SSnehasish Kumar     } else if (FuncBBClusterInfo[MBB.getNumber()].hasValue())
2708d943a92SSnehasish Kumar       MBB.setSectionID(FuncBBClusterInfo[MBB.getNumber()]->ClusterID);
2718d943a92SSnehasish Kumar     else {
2728d943a92SSnehasish Kumar       // BB goes into the special cold section if it is not specified in the
2738d943a92SSnehasish Kumar       // cluster info map.
2748d943a92SSnehasish Kumar       MBB.setSectionID(MBBSectionID::ColdSectionID);
2758d943a92SSnehasish Kumar     }
2768d943a92SSnehasish Kumar 
2778d943a92SSnehasish Kumar     if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&
2788d943a92SSnehasish Kumar         EHPadsSectionID != MBBSectionID::ExceptionSectionID) {
2798d943a92SSnehasish Kumar       // If we already have one cluster containing eh_pads, this must be updated
2808d943a92SSnehasish Kumar       // to ExceptionSectionID. Otherwise, we set it equal to the current
2818d943a92SSnehasish Kumar       // section ID.
2828d943a92SSnehasish Kumar       EHPadsSectionID = EHPadsSectionID.hasValue()
2838d943a92SSnehasish Kumar                             ? MBBSectionID::ExceptionSectionID
2848d943a92SSnehasish Kumar                             : MBB.getSectionID();
2858d943a92SSnehasish Kumar     }
2868d943a92SSnehasish Kumar   }
2878d943a92SSnehasish Kumar 
2888d943a92SSnehasish Kumar   // If EHPads are in more than one section, this places all of them in the
2898d943a92SSnehasish Kumar   // special exception section.
2908d943a92SSnehasish Kumar   if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)
2918d943a92SSnehasish Kumar     for (auto &MBB : MF)
2928d943a92SSnehasish Kumar       if (MBB.isEHPad())
2938d943a92SSnehasish Kumar         MBB.setSectionID(EHPadsSectionID.getValue());
29494faadacSSnehasish Kumar }
2958d943a92SSnehasish Kumar 
29694faadacSSnehasish Kumar void llvm::sortBasicBlocksAndUpdateBranches(
29794faadacSSnehasish Kumar     MachineFunction &MF, MachineBasicBlockComparator MBBCmp) {
2988d943a92SSnehasish Kumar   SmallVector<MachineBasicBlock *, 4> PreLayoutFallThroughs(
2998d943a92SSnehasish Kumar       MF.getNumBlockIDs());
3008d943a92SSnehasish Kumar   for (auto &MBB : MF)
3018d943a92SSnehasish Kumar     PreLayoutFallThroughs[MBB.getNumber()] = MBB.getFallThrough();
3028d943a92SSnehasish Kumar 
30394faadacSSnehasish Kumar   MF.sort(MBBCmp);
3048d943a92SSnehasish Kumar 
3058d943a92SSnehasish Kumar   // Set IsBeginSection and IsEndSection according to the assigned section IDs.
3068d943a92SSnehasish Kumar   MF.assignBeginEndSections();
3078d943a92SSnehasish Kumar 
3088d943a92SSnehasish Kumar   // After reordering basic blocks, we must update basic block branches to
3098d943a92SSnehasish Kumar   // insert explicit fallthrough branches when required and optimize branches
3108d943a92SSnehasish Kumar   // when possible.
3118d943a92SSnehasish Kumar   updateBranches(MF, PreLayoutFallThroughs);
3128d943a92SSnehasish Kumar }
3138d943a92SSnehasish Kumar 
3148955950cSRahman Lavaee // If the exception section begins with a landing pad, that landing pad will
3158955950cSRahman Lavaee // assume a zero offset (relative to @LPStart) in the LSDA. However, a value of
3168955950cSRahman Lavaee // zero implies "no landing pad." This function inserts a NOP just before the EH
3178955950cSRahman Lavaee // pad label to ensure a nonzero offset. Returns true if padding is not needed.
3188955950cSRahman Lavaee static bool avoidZeroOffsetLandingPad(MachineFunction &MF) {
3198955950cSRahman Lavaee   for (auto &MBB : MF) {
3208955950cSRahman Lavaee     if (MBB.isBeginSection() && MBB.isEHPad()) {
3218955950cSRahman Lavaee       MachineBasicBlock::iterator MI = MBB.begin();
3228955950cSRahman Lavaee       while (!MI->isEHLabel())
3238955950cSRahman Lavaee         ++MI;
3245d44c92bSFangrui Song       MCInst Nop = MF.getSubtarget().getInstrInfo()->getNop();
3258955950cSRahman Lavaee       BuildMI(MBB, MI, DebugLoc(),
3265d44c92bSFangrui Song               MF.getSubtarget().getInstrInfo()->get(Nop.getOpcode()));
3278955950cSRahman Lavaee       return false;
3288955950cSRahman Lavaee     }
3298955950cSRahman Lavaee   }
3308955950cSRahman Lavaee   return true;
3318955950cSRahman Lavaee }
3328955950cSRahman Lavaee 
333c32f3998SSriraman Tallam // This checks if the source of this function has drifted since this binary was
334c32f3998SSriraman Tallam // profiled previously.  For now, we are piggy backing on what PGO does to
335c32f3998SSriraman Tallam // detect this with instrumented profiles.  PGO emits an hash of the IR and
336c32f3998SSriraman Tallam // checks if the hash has changed.  Advanced basic block layout is usually done
337c32f3998SSriraman Tallam // on top of PGO optimized binaries and hence this check works well in practice.
338c32f3998SSriraman Tallam static bool hasInstrProfHashMismatch(MachineFunction &MF) {
339c32f3998SSriraman Tallam   if (!BBSectionsDetectSourceDrift)
340c32f3998SSriraman Tallam     return false;
341c32f3998SSriraman Tallam 
342c32f3998SSriraman Tallam   const char MetadataName[] = "instr_prof_hash_mismatch";
343c32f3998SSriraman Tallam   auto *Existing = MF.getFunction().getMetadata(LLVMContext::MD_annotation);
344c32f3998SSriraman Tallam   if (Existing) {
345c32f3998SSriraman Tallam     MDTuple *Tuple = cast<MDTuple>(Existing);
346c32f3998SSriraman Tallam     for (auto &N : Tuple->operands())
347c32f3998SSriraman Tallam       if (cast<MDString>(N.get())->getString() == MetadataName)
348c32f3998SSriraman Tallam         return true;
349c32f3998SSriraman Tallam   }
350c32f3998SSriraman Tallam 
351c32f3998SSriraman Tallam   return false;
352c32f3998SSriraman Tallam }
353c32f3998SSriraman Tallam 
3548d943a92SSnehasish Kumar bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {
3558d943a92SSnehasish Kumar   auto BBSectionsType = MF.getTarget().getBBSectionsType();
3568d943a92SSnehasish Kumar   assert(BBSectionsType != BasicBlockSection::None &&
3578d943a92SSnehasish Kumar          "BB Sections not enabled!");
358c32f3998SSriraman Tallam 
359c32f3998SSriraman Tallam   // Check for source drift.  If the source has changed since the profiles
360c32f3998SSriraman Tallam   // were obtained, optimizing basic blocks might be sub-optimal.
361c32f3998SSriraman Tallam   // This only applies to BasicBlockSection::List as it creates
362c32f3998SSriraman Tallam   // clusters of basic blocks using basic block ids. Source drift can
363c32f3998SSriraman Tallam   // invalidate these groupings leading to sub-optimal code generation with
364c32f3998SSriraman Tallam   // regards to performance.
365c32f3998SSriraman Tallam   if (BBSectionsType == BasicBlockSection::List &&
366c32f3998SSriraman Tallam       hasInstrProfHashMismatch(MF))
367c32f3998SSriraman Tallam     return true;
368c32f3998SSriraman Tallam 
3698d943a92SSnehasish Kumar   // Renumber blocks before sorting them for basic block sections.  This is
3708d943a92SSnehasish Kumar   // useful during sorting, basic blocks in the same section will retain the
3718d943a92SSnehasish Kumar   // default order.  This renumbering should also be done for basic block
3728d943a92SSnehasish Kumar   // labels to match the profiles with the correct blocks.
3738d943a92SSnehasish Kumar   MF.RenumberBlocks();
3748d943a92SSnehasish Kumar 
3758d943a92SSnehasish Kumar   if (BBSectionsType == BasicBlockSection::Labels) {
3768d943a92SSnehasish Kumar     MF.setBBSectionsType(BBSectionsType);
3778d943a92SSnehasish Kumar     return true;
3788d943a92SSnehasish Kumar   }
3798d943a92SSnehasish Kumar 
3808d943a92SSnehasish Kumar   std::vector<Optional<BBClusterInfo>> FuncBBClusterInfo;
3818d943a92SSnehasish Kumar   if (BBSectionsType == BasicBlockSection::List &&
3828d943a92SSnehasish Kumar       !getBBClusterInfoForFunction(MF, FuncAliasMap, ProgramBBClusterInfo,
3838d943a92SSnehasish Kumar                                    FuncBBClusterInfo))
3848d943a92SSnehasish Kumar     return true;
3858d943a92SSnehasish Kumar   MF.setBBSectionsType(BBSectionsType);
38694faadacSSnehasish Kumar   assignSections(MF, FuncBBClusterInfo);
38794faadacSSnehasish Kumar 
38894faadacSSnehasish Kumar   // We make sure that the cluster including the entry basic block precedes all
38994faadacSSnehasish Kumar   // other clusters.
39094faadacSSnehasish Kumar   auto EntryBBSectionID = MF.front().getSectionID();
39194faadacSSnehasish Kumar 
39294faadacSSnehasish Kumar   // Helper function for ordering BB sections as follows:
39394faadacSSnehasish Kumar   //   * Entry section (section including the entry block).
39494faadacSSnehasish Kumar   //   * Regular sections (in increasing order of their Number).
39594faadacSSnehasish Kumar   //     ...
39694faadacSSnehasish Kumar   //   * Exception section
39794faadacSSnehasish Kumar   //   * Cold section
39894faadacSSnehasish Kumar   auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,
39994faadacSSnehasish Kumar                                             const MBBSectionID &RHS) {
40094faadacSSnehasish Kumar     // We make sure that the section containing the entry block precedes all the
40194faadacSSnehasish Kumar     // other sections.
40294faadacSSnehasish Kumar     if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)
40394faadacSSnehasish Kumar       return LHS == EntryBBSectionID;
40494faadacSSnehasish Kumar     return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;
40594faadacSSnehasish Kumar   };
40694faadacSSnehasish Kumar 
40794faadacSSnehasish Kumar   // We sort all basic blocks to make sure the basic blocks of every cluster are
40894faadacSSnehasish Kumar   // contiguous and ordered accordingly. Furthermore, clusters are ordered in
40994faadacSSnehasish Kumar   // increasing order of their section IDs, with the exception and the
41094faadacSSnehasish Kumar   // cold section placed at the end of the function.
41194faadacSSnehasish Kumar   auto Comparator = [&](const MachineBasicBlock &X,
41294faadacSSnehasish Kumar                         const MachineBasicBlock &Y) {
41394faadacSSnehasish Kumar     auto XSectionID = X.getSectionID();
41494faadacSSnehasish Kumar     auto YSectionID = Y.getSectionID();
41594faadacSSnehasish Kumar     if (XSectionID != YSectionID)
41694faadacSSnehasish Kumar       return MBBSectionOrder(XSectionID, YSectionID);
41794faadacSSnehasish Kumar     // If the two basic block are in the same section, the order is decided by
41894faadacSSnehasish Kumar     // their position within the section.
41994faadacSSnehasish Kumar     if (XSectionID.Type == MBBSectionID::SectionType::Default)
42094faadacSSnehasish Kumar       return FuncBBClusterInfo[X.getNumber()]->PositionInCluster <
42194faadacSSnehasish Kumar              FuncBBClusterInfo[Y.getNumber()]->PositionInCluster;
42294faadacSSnehasish Kumar     return X.getNumber() < Y.getNumber();
42394faadacSSnehasish Kumar   };
42494faadacSSnehasish Kumar 
42594faadacSSnehasish Kumar   sortBasicBlocksAndUpdateBranches(MF, Comparator);
4268955950cSRahman Lavaee   avoidZeroOffsetLandingPad(MF);
4278d943a92SSnehasish Kumar   return true;
4288d943a92SSnehasish Kumar }
4298d943a92SSnehasish Kumar 
4308d943a92SSnehasish Kumar // Basic Block Sections can be enabled for a subset of machine basic blocks.
4318d943a92SSnehasish Kumar // This is done by passing a file containing names of functions for which basic
4328d943a92SSnehasish Kumar // block sections are desired.  Additionally, machine basic block ids of the
4338d943a92SSnehasish Kumar // functions can also be specified for a finer granularity. Moreover, a cluster
4348d943a92SSnehasish Kumar // of basic blocks could be assigned to the same section.
4358d943a92SSnehasish Kumar // A file with basic block sections for all of function main and three blocks
4368d943a92SSnehasish Kumar // for function foo (of which 1 and 2 are placed in a cluster) looks like this:
4378d943a92SSnehasish Kumar // ----------------------------
4388d943a92SSnehasish Kumar // list.txt:
4398d943a92SSnehasish Kumar // !main
4408d943a92SSnehasish Kumar // !foo
4418d943a92SSnehasish Kumar // !!1 2
4428d943a92SSnehasish Kumar // !!4
4438d943a92SSnehasish Kumar static Error getBBClusterInfo(const MemoryBuffer *MBuf,
4448d943a92SSnehasish Kumar                               ProgramBBClusterInfoMapTy &ProgramBBClusterInfo,
4458d943a92SSnehasish Kumar                               StringMap<StringRef> &FuncAliasMap) {
4468d943a92SSnehasish Kumar   assert(MBuf);
4478d943a92SSnehasish Kumar   line_iterator LineIt(*MBuf, /*SkipBlanks=*/true, /*CommentMarker=*/'#');
4488d943a92SSnehasish Kumar 
4498d943a92SSnehasish Kumar   auto invalidProfileError = [&](auto Message) {
4508d943a92SSnehasish Kumar     return make_error<StringError>(
4518d943a92SSnehasish Kumar         Twine("Invalid profile " + MBuf->getBufferIdentifier() + " at line " +
4528d943a92SSnehasish Kumar               Twine(LineIt.line_number()) + ": " + Message),
4538d943a92SSnehasish Kumar         inconvertibleErrorCode());
4548d943a92SSnehasish Kumar   };
4558d943a92SSnehasish Kumar 
4568d943a92SSnehasish Kumar   auto FI = ProgramBBClusterInfo.end();
4578d943a92SSnehasish Kumar 
4588d943a92SSnehasish Kumar   // Current cluster ID corresponding to this function.
4598d943a92SSnehasish Kumar   unsigned CurrentCluster = 0;
4608d943a92SSnehasish Kumar   // Current position in the current cluster.
4618d943a92SSnehasish Kumar   unsigned CurrentPosition = 0;
4628d943a92SSnehasish Kumar 
4638d943a92SSnehasish Kumar   // Temporary set to ensure every basic block ID appears once in the clusters
4648d943a92SSnehasish Kumar   // of a function.
4658d943a92SSnehasish Kumar   SmallSet<unsigned, 4> FuncBBIDs;
4668d943a92SSnehasish Kumar 
4678d943a92SSnehasish Kumar   for (; !LineIt.is_at_eof(); ++LineIt) {
4688d943a92SSnehasish Kumar     StringRef S(*LineIt);
4698d943a92SSnehasish Kumar     if (S[0] == '@')
4708d943a92SSnehasish Kumar       continue;
4718d943a92SSnehasish Kumar     // Check for the leading "!"
4728d943a92SSnehasish Kumar     if (!S.consume_front("!") || S.empty())
4738d943a92SSnehasish Kumar       break;
4748d943a92SSnehasish Kumar     // Check for second "!" which indicates a cluster of basic blocks.
4758d943a92SSnehasish Kumar     if (S.consume_front("!")) {
4768d943a92SSnehasish Kumar       if (FI == ProgramBBClusterInfo.end())
4778d943a92SSnehasish Kumar         return invalidProfileError(
4788d943a92SSnehasish Kumar             "Cluster list does not follow a function name specifier.");
4798d943a92SSnehasish Kumar       SmallVector<StringRef, 4> BBIndexes;
4808d943a92SSnehasish Kumar       S.split(BBIndexes, ' ');
4818d943a92SSnehasish Kumar       // Reset current cluster position.
4828d943a92SSnehasish Kumar       CurrentPosition = 0;
4838d943a92SSnehasish Kumar       for (auto BBIndexStr : BBIndexes) {
4848d943a92SSnehasish Kumar         unsigned long long BBIndex;
4858d943a92SSnehasish Kumar         if (getAsUnsignedInteger(BBIndexStr, 10, BBIndex))
4868d943a92SSnehasish Kumar           return invalidProfileError(Twine("Unsigned integer expected: '") +
4878d943a92SSnehasish Kumar                                      BBIndexStr + "'.");
4888d943a92SSnehasish Kumar         if (!FuncBBIDs.insert(BBIndex).second)
4898d943a92SSnehasish Kumar           return invalidProfileError(Twine("Duplicate basic block id found '") +
4908d943a92SSnehasish Kumar                                      BBIndexStr + "'.");
4918d943a92SSnehasish Kumar         if (!BBIndex && CurrentPosition)
4928d943a92SSnehasish Kumar           return invalidProfileError("Entry BB (0) does not begin a cluster.");
4938d943a92SSnehasish Kumar 
4948d943a92SSnehasish Kumar         FI->second.emplace_back(BBClusterInfo{
4958d943a92SSnehasish Kumar             ((unsigned)BBIndex), CurrentCluster, CurrentPosition++});
4968d943a92SSnehasish Kumar       }
4978d943a92SSnehasish Kumar       CurrentCluster++;
4988d943a92SSnehasish Kumar     } else { // This is a function name specifier.
4998d943a92SSnehasish Kumar       // Function aliases are separated using '/'. We use the first function
5008d943a92SSnehasish Kumar       // name for the cluster info mapping and delegate all other aliases to
5018d943a92SSnehasish Kumar       // this one.
5028d943a92SSnehasish Kumar       SmallVector<StringRef, 4> Aliases;
5038d943a92SSnehasish Kumar       S.split(Aliases, '/');
5048d943a92SSnehasish Kumar       for (size_t i = 1; i < Aliases.size(); ++i)
5058d943a92SSnehasish Kumar         FuncAliasMap.try_emplace(Aliases[i], Aliases.front());
5068d943a92SSnehasish Kumar 
5078d943a92SSnehasish Kumar       // Prepare for parsing clusters of this function name.
5088d943a92SSnehasish Kumar       // Start a new cluster map for this function name.
5098d943a92SSnehasish Kumar       FI = ProgramBBClusterInfo.try_emplace(Aliases.front()).first;
5108d943a92SSnehasish Kumar       CurrentCluster = 0;
5118d943a92SSnehasish Kumar       FuncBBIDs.clear();
5128d943a92SSnehasish Kumar     }
5138d943a92SSnehasish Kumar   }
5148d943a92SSnehasish Kumar   return Error::success();
5158d943a92SSnehasish Kumar }
5168d943a92SSnehasish Kumar 
5178d943a92SSnehasish Kumar bool BasicBlockSections::doInitialization(Module &M) {
5188d943a92SSnehasish Kumar   if (!MBuf)
5198d943a92SSnehasish Kumar     return false;
5208d943a92SSnehasish Kumar   if (auto Err = getBBClusterInfo(MBuf, ProgramBBClusterInfo, FuncAliasMap))
5218d943a92SSnehasish Kumar     report_fatal_error(std::move(Err));
5228d943a92SSnehasish Kumar   return false;
5238d943a92SSnehasish Kumar }
5248d943a92SSnehasish Kumar 
5258d943a92SSnehasish Kumar void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {
5268d943a92SSnehasish Kumar   AU.setPreservesAll();
5278d943a92SSnehasish Kumar   MachineFunctionPass::getAnalysisUsage(AU);
5288d943a92SSnehasish Kumar }
5298d943a92SSnehasish Kumar 
5308d943a92SSnehasish Kumar MachineFunctionPass *
5318d943a92SSnehasish Kumar llvm::createBasicBlockSectionsPass(const MemoryBuffer *Buf) {
5328d943a92SSnehasish Kumar   return new BasicBlockSections(Buf);
5338d943a92SSnehasish Kumar }
534