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
242256b359SRahman Lavaee // function. We insert a symbol at the beginning of every cluster's section to
252256b359SRahman Lavaee // allow the linker to reorder the sections in any arbitrary sequence. A global
262256b359SRahman Lavaee // order of these sections would encapsulate the function layout.
272256b359SRahman Lavaee // For example, consider the following clusters for a function foo (consisting
282256b359SRahman Lavaee // of 6 basic blocks 0, 1, ..., 5).
292256b359SRahman Lavaee //
302256b359SRahman Lavaee // 0 2
312256b359SRahman Lavaee // 1 3 5
322256b359SRahman Lavaee //
332256b359SRahman Lavaee // * Basic blocks 0 and 2 are placed in one section with symbol `foo`
342256b359SRahman Lavaee //   referencing the beginning of this section.
352256b359SRahman Lavaee // * Basic blocks 1, 3, 5 are placed in a separate section. A new symbol
362256b359SRahman Lavaee //   `foo.__part.1` will reference the beginning of this section.
372256b359SRahman Lavaee // * Basic block 4 (note that it is not referenced in the list) is placed in
382256b359SRahman 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 //
63*0aa6df65SRahman Lavaee // With -fbasic-block-sections=labels, we encode 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/SmallVector.h"
738d943a92SSnehasish Kumar #include "llvm/ADT/StringRef.h"
7408cc0585SRahman Lavaee #include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
7594faadacSSnehasish Kumar #include "llvm/CodeGen/BasicBlockSectionUtils.h"
768d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineFunction.h"
778d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineFunctionPass.h"
788d943a92SSnehasish Kumar #include "llvm/CodeGen/Passes.h"
798d943a92SSnehasish Kumar #include "llvm/CodeGen/TargetInstrInfo.h"
808d943a92SSnehasish Kumar #include "llvm/InitializePasses.h"
818d943a92SSnehasish Kumar #include "llvm/Target/TargetMachine.h"
828d943a92SSnehasish Kumar 
838d943a92SSnehasish Kumar using namespace llvm;
848d943a92SSnehasish Kumar 
85d2696decSSnehasish Kumar // Placing the cold clusters in a separate section mitigates against poor
86d2696decSSnehasish Kumar // profiles and allows optimizations such as hugepage mapping to be applied at a
8777638a53SSnehasish Kumar // section granularity. Defaults to ".text.split." which is recognized by lld
8877638a53SSnehasish Kumar // via the `-z keep-text-section-prefix` flag.
89d2696decSSnehasish Kumar cl::opt<std::string> llvm::BBSectionsColdTextPrefix(
90d2696decSSnehasish Kumar     "bbsections-cold-text-prefix",
91d2696decSSnehasish Kumar     cl::desc("The text prefix to use for cold basic block clusters"),
9277638a53SSnehasish Kumar     cl::init(".text.split."), cl::Hidden);
93d2696decSSnehasish Kumar 
94c32f3998SSriraman Tallam cl::opt<bool> BBSectionsDetectSourceDrift(
95c32f3998SSriraman Tallam     "bbsections-detect-source-drift",
96c32f3998SSriraman Tallam     cl::desc("This checks if there is a fdo instr. profile hash "
97c32f3998SSriraman Tallam              "mismatch for this function"),
98c32f3998SSriraman Tallam     cl::init(true), cl::Hidden);
99c32f3998SSriraman Tallam 
1008d943a92SSnehasish Kumar namespace {
1018d943a92SSnehasish Kumar 
1028d943a92SSnehasish Kumar class BasicBlockSections : public MachineFunctionPass {
1038d943a92SSnehasish Kumar public:
1048d943a92SSnehasish Kumar   static char ID;
1058d943a92SSnehasish Kumar 
10608cc0585SRahman Lavaee   BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
1078d943a92SSnehasish Kumar 
1088d943a92SSnehasish Kumar   BasicBlockSections() : MachineFunctionPass(ID) {
1098d943a92SSnehasish Kumar     initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
1108d943a92SSnehasish Kumar   }
1118d943a92SSnehasish Kumar 
1128d943a92SSnehasish Kumar   StringRef getPassName() const override {
1138d943a92SSnehasish Kumar     return "Basic Block Sections Analysis";
1148d943a92SSnehasish Kumar   }
1158d943a92SSnehasish Kumar 
1168d943a92SSnehasish Kumar   void getAnalysisUsage(AnalysisUsage &AU) const override;
1178d943a92SSnehasish Kumar 
1188d943a92SSnehasish Kumar   /// Identify basic blocks that need separate sections and prepare to emit them
1198d943a92SSnehasish Kumar   /// accordingly.
1208d943a92SSnehasish Kumar   bool runOnMachineFunction(MachineFunction &MF) override;
1218d943a92SSnehasish Kumar };
1228d943a92SSnehasish Kumar 
1238d943a92SSnehasish Kumar } // end anonymous namespace
1248d943a92SSnehasish Kumar 
1258d943a92SSnehasish Kumar char BasicBlockSections::ID = 0;
1268d943a92SSnehasish Kumar INITIALIZE_PASS(BasicBlockSections, "bbsections-prepare",
1278d943a92SSnehasish Kumar                 "Prepares for basic block sections, by splitting functions "
1288d943a92SSnehasish Kumar                 "into clusters of basic blocks.",
1298d943a92SSnehasish Kumar                 false, false)
1308d943a92SSnehasish Kumar 
1318d943a92SSnehasish Kumar // This function updates and optimizes the branching instructions of every basic
1328d943a92SSnehasish Kumar // block in a given function to account for changes in the layout.
1338d943a92SSnehasish Kumar static void updateBranches(
1348d943a92SSnehasish Kumar     MachineFunction &MF,
1358d943a92SSnehasish Kumar     const SmallVector<MachineBasicBlock *, 4> &PreLayoutFallThroughs) {
1368d943a92SSnehasish Kumar   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1378d943a92SSnehasish Kumar   SmallVector<MachineOperand, 4> Cond;
1388d943a92SSnehasish Kumar   for (auto &MBB : MF) {
1398d943a92SSnehasish Kumar     auto NextMBBI = std::next(MBB.getIterator());
1408d943a92SSnehasish Kumar     auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];
1418d943a92SSnehasish Kumar     // If this block had a fallthrough before we need an explicit unconditional
1428d943a92SSnehasish Kumar     // branch to that block if either
1438d943a92SSnehasish Kumar     //     1- the block ends a section, which means its next block may be
1448d943a92SSnehasish Kumar     //        reorderd by the linker, or
1458d943a92SSnehasish Kumar     //     2- the fallthrough block is not adjacent to the block in the new
1468d943a92SSnehasish Kumar     //        order.
1478d943a92SSnehasish Kumar     if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))
1488d943a92SSnehasish Kumar       TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
1498d943a92SSnehasish Kumar 
1508d943a92SSnehasish Kumar     // We do not optimize branches for machine basic blocks ending sections, as
1518d943a92SSnehasish Kumar     // their adjacent block might be reordered by the linker.
1528d943a92SSnehasish Kumar     if (MBB.isEndSection())
1538d943a92SSnehasish Kumar       continue;
1548d943a92SSnehasish Kumar 
1558d943a92SSnehasish Kumar     // It might be possible to optimize branches by flipping the branch
1568d943a92SSnehasish Kumar     // condition.
1578d943a92SSnehasish Kumar     Cond.clear();
1588d943a92SSnehasish Kumar     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
1598d943a92SSnehasish Kumar     if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
1608d943a92SSnehasish Kumar       continue;
1618d943a92SSnehasish Kumar     MBB.updateTerminator(FTMBB);
1628d943a92SSnehasish Kumar   }
1638d943a92SSnehasish Kumar }
1648d943a92SSnehasish Kumar 
1658d943a92SSnehasish Kumar // This function provides the BBCluster information associated with a function.
1668d943a92SSnehasish Kumar // Returns true if a valid association exists and false otherwise.
16708cc0585SRahman Lavaee bool getBBClusterInfoForFunction(
16808cc0585SRahman Lavaee     const MachineFunction &MF,
16908cc0585SRahman Lavaee     BasicBlockSectionsProfileReader *BBSectionsProfileReader,
1708d943a92SSnehasish Kumar     std::vector<Optional<BBClusterInfo>> &V) {
1718d943a92SSnehasish Kumar 
1728d943a92SSnehasish Kumar   // Find the assoicated cluster information.
17308cc0585SRahman Lavaee   std::pair<bool, SmallVector<BBClusterInfo, 4>> P =
17408cc0585SRahman Lavaee       BBSectionsProfileReader->getBBClusterInfoForFunction(MF.getName());
17508cc0585SRahman Lavaee   if (!P.first)
1768d943a92SSnehasish Kumar     return false;
1778d943a92SSnehasish Kumar 
17808cc0585SRahman Lavaee   if (P.second.empty()) {
1798d943a92SSnehasish Kumar     // This indicates that sections are desired for all basic blocks of this
1808d943a92SSnehasish Kumar     // function. We clear the BBClusterInfo vector to denote this.
1818d943a92SSnehasish Kumar     V.clear();
1828d943a92SSnehasish Kumar     return true;
1838d943a92SSnehasish Kumar   }
1848d943a92SSnehasish Kumar 
1858d943a92SSnehasish Kumar   V.resize(MF.getNumBlockIDs());
18608cc0585SRahman Lavaee   for (auto bbClusterInfo : P.second) {
1878d943a92SSnehasish Kumar     // Bail out if the cluster information contains invalid MBB numbers.
1888d943a92SSnehasish Kumar     if (bbClusterInfo.MBBNumber >= MF.getNumBlockIDs())
1898d943a92SSnehasish Kumar       return false;
1908d943a92SSnehasish Kumar     V[bbClusterInfo.MBBNumber] = bbClusterInfo;
1918d943a92SSnehasish Kumar   }
1928d943a92SSnehasish Kumar   return true;
1938d943a92SSnehasish Kumar }
1948d943a92SSnehasish Kumar 
1958d943a92SSnehasish Kumar // This function sorts basic blocks according to the cluster's information.
1968d943a92SSnehasish Kumar // All explicitly specified clusters of basic blocks will be ordered
1978d943a92SSnehasish Kumar // accordingly. All non-specified BBs go into a separate "Cold" section.
1988d943a92SSnehasish Kumar // Additionally, if exception handling landing pads end up in more than one
1998d943a92SSnehasish Kumar // clusters, they are moved into a single "Exception" section. Eventually,
2008d943a92SSnehasish Kumar // clusters are ordered in increasing order of their IDs, with the "Exception"
2018d943a92SSnehasish Kumar // and "Cold" succeeding all other clusters.
2028d943a92SSnehasish Kumar // FuncBBClusterInfo represent the cluster information for basic blocks. If this
2038d943a92SSnehasish Kumar // is empty, it means unique sections for all basic blocks in the function.
20494faadacSSnehasish Kumar static void
20594faadacSSnehasish Kumar assignSections(MachineFunction &MF,
2068d943a92SSnehasish Kumar                const std::vector<Optional<BBClusterInfo>> &FuncBBClusterInfo) {
2078d943a92SSnehasish Kumar   assert(MF.hasBBSections() && "BB Sections is not set for function.");
2088d943a92SSnehasish Kumar   // This variable stores the section ID of the cluster containing eh_pads (if
2098d943a92SSnehasish Kumar   // all eh_pads are one cluster). If more than one cluster contain eh_pads, we
2108d943a92SSnehasish Kumar   // set it equal to ExceptionSectionID.
2118d943a92SSnehasish Kumar   Optional<MBBSectionID> EHPadsSectionID;
2128d943a92SSnehasish Kumar 
2138d943a92SSnehasish Kumar   for (auto &MBB : MF) {
2148d943a92SSnehasish Kumar     // With the 'all' option, every basic block is placed in a unique section.
2158d943a92SSnehasish Kumar     // With the 'list' option, every basic block is placed in a section
2168d943a92SSnehasish Kumar     // associated with its cluster, unless we want individual unique sections
2178d943a92SSnehasish Kumar     // for every basic block in this function (if FuncBBClusterInfo is empty).
2188d943a92SSnehasish Kumar     if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All ||
2198d943a92SSnehasish Kumar         FuncBBClusterInfo.empty()) {
2208d943a92SSnehasish Kumar       // If unique sections are desired for all basic blocks of the function, we
2218d943a92SSnehasish Kumar       // set every basic block's section ID equal to its number (basic block
2228d943a92SSnehasish Kumar       // id). This further ensures that basic blocks are ordered canonically.
2238d943a92SSnehasish Kumar       MBB.setSectionID({static_cast<unsigned int>(MBB.getNumber())});
224e0e687a6SKazu Hirata     } else if (FuncBBClusterInfo[MBB.getNumber()])
2258d943a92SSnehasish Kumar       MBB.setSectionID(FuncBBClusterInfo[MBB.getNumber()]->ClusterID);
2268d943a92SSnehasish Kumar     else {
2278d943a92SSnehasish Kumar       // BB goes into the special cold section if it is not specified in the
2288d943a92SSnehasish Kumar       // cluster info map.
2298d943a92SSnehasish Kumar       MBB.setSectionID(MBBSectionID::ColdSectionID);
2308d943a92SSnehasish Kumar     }
2318d943a92SSnehasish Kumar 
2328d943a92SSnehasish Kumar     if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&
2338d943a92SSnehasish Kumar         EHPadsSectionID != MBBSectionID::ExceptionSectionID) {
2348d943a92SSnehasish Kumar       // If we already have one cluster containing eh_pads, this must be updated
2358d943a92SSnehasish Kumar       // to ExceptionSectionID. Otherwise, we set it equal to the current
2368d943a92SSnehasish Kumar       // section ID.
237d08f34b5SKazu Hirata       EHPadsSectionID = EHPadsSectionID ? MBBSectionID::ExceptionSectionID
2388d943a92SSnehasish Kumar                                         : MBB.getSectionID();
2398d943a92SSnehasish Kumar     }
2408d943a92SSnehasish Kumar   }
2418d943a92SSnehasish Kumar 
2428d943a92SSnehasish Kumar   // If EHPads are in more than one section, this places all of them in the
2438d943a92SSnehasish Kumar   // special exception section.
2448d943a92SSnehasish Kumar   if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)
2458d943a92SSnehasish Kumar     for (auto &MBB : MF)
2468d943a92SSnehasish Kumar       if (MBB.isEHPad())
2477a47ee51SKazu Hirata         MBB.setSectionID(*EHPadsSectionID);
24894faadacSSnehasish Kumar }
2498d943a92SSnehasish Kumar 
25094faadacSSnehasish Kumar void llvm::sortBasicBlocksAndUpdateBranches(
25194faadacSSnehasish Kumar     MachineFunction &MF, MachineBasicBlockComparator MBBCmp) {
2528d943a92SSnehasish Kumar   SmallVector<MachineBasicBlock *, 4> PreLayoutFallThroughs(
2538d943a92SSnehasish Kumar       MF.getNumBlockIDs());
2548d943a92SSnehasish Kumar   for (auto &MBB : MF)
2558d943a92SSnehasish Kumar     PreLayoutFallThroughs[MBB.getNumber()] = MBB.getFallThrough();
2568d943a92SSnehasish Kumar 
25794faadacSSnehasish Kumar   MF.sort(MBBCmp);
2588d943a92SSnehasish Kumar 
2598d943a92SSnehasish Kumar   // Set IsBeginSection and IsEndSection according to the assigned section IDs.
2608d943a92SSnehasish Kumar   MF.assignBeginEndSections();
2618d943a92SSnehasish Kumar 
2628d943a92SSnehasish Kumar   // After reordering basic blocks, we must update basic block branches to
2638d943a92SSnehasish Kumar   // insert explicit fallthrough branches when required and optimize branches
2648d943a92SSnehasish Kumar   // when possible.
2658d943a92SSnehasish Kumar   updateBranches(MF, PreLayoutFallThroughs);
2668d943a92SSnehasish Kumar }
2678d943a92SSnehasish Kumar 
2688955950cSRahman Lavaee // If the exception section begins with a landing pad, that landing pad will
2698955950cSRahman Lavaee // assume a zero offset (relative to @LPStart) in the LSDA. However, a value of
2708955950cSRahman Lavaee // zero implies "no landing pad." This function inserts a NOP just before the EH
2718955950cSRahman Lavaee // pad label to ensure a nonzero offset. Returns true if padding is not needed.
2728955950cSRahman Lavaee static bool avoidZeroOffsetLandingPad(MachineFunction &MF) {
2738955950cSRahman Lavaee   for (auto &MBB : MF) {
2748955950cSRahman Lavaee     if (MBB.isBeginSection() && MBB.isEHPad()) {
2758955950cSRahman Lavaee       MachineBasicBlock::iterator MI = MBB.begin();
2768955950cSRahman Lavaee       while (!MI->isEHLabel())
2778955950cSRahman Lavaee         ++MI;
2785d44c92bSFangrui Song       MCInst Nop = MF.getSubtarget().getInstrInfo()->getNop();
2798955950cSRahman Lavaee       BuildMI(MBB, MI, DebugLoc(),
2805d44c92bSFangrui Song               MF.getSubtarget().getInstrInfo()->get(Nop.getOpcode()));
2818955950cSRahman Lavaee       return false;
2828955950cSRahman Lavaee     }
2838955950cSRahman Lavaee   }
2848955950cSRahman Lavaee   return true;
2858955950cSRahman Lavaee }
2868955950cSRahman Lavaee 
287c32f3998SSriraman Tallam // This checks if the source of this function has drifted since this binary was
288c32f3998SSriraman Tallam // profiled previously.  For now, we are piggy backing on what PGO does to
289c32f3998SSriraman Tallam // detect this with instrumented profiles.  PGO emits an hash of the IR and
290c32f3998SSriraman Tallam // checks if the hash has changed.  Advanced basic block layout is usually done
291c32f3998SSriraman Tallam // on top of PGO optimized binaries and hence this check works well in practice.
292c32f3998SSriraman Tallam static bool hasInstrProfHashMismatch(MachineFunction &MF) {
293c32f3998SSriraman Tallam   if (!BBSectionsDetectSourceDrift)
294c32f3998SSriraman Tallam     return false;
295c32f3998SSriraman Tallam 
296c32f3998SSriraman Tallam   const char MetadataName[] = "instr_prof_hash_mismatch";
297c32f3998SSriraman Tallam   auto *Existing = MF.getFunction().getMetadata(LLVMContext::MD_annotation);
298c32f3998SSriraman Tallam   if (Existing) {
299c32f3998SSriraman Tallam     MDTuple *Tuple = cast<MDTuple>(Existing);
300c32f3998SSriraman Tallam     for (auto &N : Tuple->operands())
301c32f3998SSriraman Tallam       if (cast<MDString>(N.get())->getString() == MetadataName)
302c32f3998SSriraman Tallam         return true;
303c32f3998SSriraman Tallam   }
304c32f3998SSriraman Tallam 
305c32f3998SSriraman Tallam   return false;
306c32f3998SSriraman Tallam }
307c32f3998SSriraman Tallam 
3088d943a92SSnehasish Kumar bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {
3098d943a92SSnehasish Kumar   auto BBSectionsType = MF.getTarget().getBBSectionsType();
3108d943a92SSnehasish Kumar   assert(BBSectionsType != BasicBlockSection::None &&
3118d943a92SSnehasish Kumar          "BB Sections not enabled!");
312c32f3998SSriraman Tallam 
313c32f3998SSriraman Tallam   // Check for source drift.  If the source has changed since the profiles
314c32f3998SSriraman Tallam   // were obtained, optimizing basic blocks might be sub-optimal.
315c32f3998SSriraman Tallam   // This only applies to BasicBlockSection::List as it creates
316c32f3998SSriraman Tallam   // clusters of basic blocks using basic block ids. Source drift can
317c32f3998SSriraman Tallam   // invalidate these groupings leading to sub-optimal code generation with
318c32f3998SSriraman Tallam   // regards to performance.
319c32f3998SSriraman Tallam   if (BBSectionsType == BasicBlockSection::List &&
320c32f3998SSriraman Tallam       hasInstrProfHashMismatch(MF))
321c32f3998SSriraman Tallam     return true;
322c32f3998SSriraman Tallam 
3238d943a92SSnehasish Kumar   // Renumber blocks before sorting them for basic block sections.  This is
3248d943a92SSnehasish Kumar   // useful during sorting, basic blocks in the same section will retain the
3258d943a92SSnehasish Kumar   // default order.  This renumbering should also be done for basic block
3268d943a92SSnehasish Kumar   // labels to match the profiles with the correct blocks.
3278d943a92SSnehasish Kumar   MF.RenumberBlocks();
3288d943a92SSnehasish Kumar 
3298d943a92SSnehasish Kumar   if (BBSectionsType == BasicBlockSection::Labels) {
3308d943a92SSnehasish Kumar     MF.setBBSectionsType(BBSectionsType);
3318d943a92SSnehasish Kumar     return true;
3328d943a92SSnehasish Kumar   }
3338d943a92SSnehasish Kumar 
33408cc0585SRahman Lavaee   BBSectionsProfileReader = &getAnalysis<BasicBlockSectionsProfileReader>();
33508cc0585SRahman Lavaee 
3368d943a92SSnehasish Kumar   std::vector<Optional<BBClusterInfo>> FuncBBClusterInfo;
3378d943a92SSnehasish Kumar   if (BBSectionsType == BasicBlockSection::List &&
33808cc0585SRahman Lavaee       !getBBClusterInfoForFunction(MF, BBSectionsProfileReader,
3398d943a92SSnehasish Kumar                                    FuncBBClusterInfo))
3408d943a92SSnehasish Kumar     return true;
3418d943a92SSnehasish Kumar   MF.setBBSectionsType(BBSectionsType);
34294faadacSSnehasish Kumar   assignSections(MF, FuncBBClusterInfo);
34394faadacSSnehasish Kumar 
34494faadacSSnehasish Kumar   // We make sure that the cluster including the entry basic block precedes all
34594faadacSSnehasish Kumar   // other clusters.
34694faadacSSnehasish Kumar   auto EntryBBSectionID = MF.front().getSectionID();
34794faadacSSnehasish Kumar 
34894faadacSSnehasish Kumar   // Helper function for ordering BB sections as follows:
34994faadacSSnehasish Kumar   //   * Entry section (section including the entry block).
35094faadacSSnehasish Kumar   //   * Regular sections (in increasing order of their Number).
35194faadacSSnehasish Kumar   //     ...
35294faadacSSnehasish Kumar   //   * Exception section
35394faadacSSnehasish Kumar   //   * Cold section
35494faadacSSnehasish Kumar   auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,
35594faadacSSnehasish Kumar                                             const MBBSectionID &RHS) {
35694faadacSSnehasish Kumar     // We make sure that the section containing the entry block precedes all the
35794faadacSSnehasish Kumar     // other sections.
35894faadacSSnehasish Kumar     if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)
35994faadacSSnehasish Kumar       return LHS == EntryBBSectionID;
36094faadacSSnehasish Kumar     return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;
36194faadacSSnehasish Kumar   };
36294faadacSSnehasish Kumar 
36394faadacSSnehasish Kumar   // We sort all basic blocks to make sure the basic blocks of every cluster are
36494faadacSSnehasish Kumar   // contiguous and ordered accordingly. Furthermore, clusters are ordered in
36594faadacSSnehasish Kumar   // increasing order of their section IDs, with the exception and the
36694faadacSSnehasish Kumar   // cold section placed at the end of the function.
36794faadacSSnehasish Kumar   auto Comparator = [&](const MachineBasicBlock &X,
36894faadacSSnehasish Kumar                         const MachineBasicBlock &Y) {
36994faadacSSnehasish Kumar     auto XSectionID = X.getSectionID();
37094faadacSSnehasish Kumar     auto YSectionID = Y.getSectionID();
37194faadacSSnehasish Kumar     if (XSectionID != YSectionID)
37294faadacSSnehasish Kumar       return MBBSectionOrder(XSectionID, YSectionID);
37394faadacSSnehasish Kumar     // If the two basic block are in the same section, the order is decided by
37494faadacSSnehasish Kumar     // their position within the section.
37594faadacSSnehasish Kumar     if (XSectionID.Type == MBBSectionID::SectionType::Default)
37694faadacSSnehasish Kumar       return FuncBBClusterInfo[X.getNumber()]->PositionInCluster <
37794faadacSSnehasish Kumar              FuncBBClusterInfo[Y.getNumber()]->PositionInCluster;
37894faadacSSnehasish Kumar     return X.getNumber() < Y.getNumber();
37994faadacSSnehasish Kumar   };
38094faadacSSnehasish Kumar 
38194faadacSSnehasish Kumar   sortBasicBlocksAndUpdateBranches(MF, Comparator);
3828955950cSRahman Lavaee   avoidZeroOffsetLandingPad(MF);
3838d943a92SSnehasish Kumar   return true;
3848d943a92SSnehasish Kumar }
3858d943a92SSnehasish Kumar 
3868d943a92SSnehasish Kumar void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {
3878d943a92SSnehasish Kumar   AU.setPreservesAll();
38808cc0585SRahman Lavaee   AU.addRequired<BasicBlockSectionsProfileReader>();
3898d943a92SSnehasish Kumar   MachineFunctionPass::getAnalysisUsage(AU);
3908d943a92SSnehasish Kumar }
3918d943a92SSnehasish Kumar 
39208cc0585SRahman Lavaee MachineFunctionPass *llvm::createBasicBlockSectionsPass() {
39308cc0585SRahman Lavaee   return new BasicBlockSections();
3948d943a92SSnehasish Kumar }
395