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 // 51*7841e21cSRahman Lavaee // With -fbasic-block-sections=labels, we emit the offsets of BB addresses of 52*7841e21cSRahman Lavaee // every function into a .bb_addr_map section. Along with the function symbols, 53*7841e21cSRahman Lavaee // this allows for mapping of virtual addresses in PMU profiles back to the 54*7841e21cSRahman Lavaee // corresponding basic blocks. This logic is implemented in AsmPrinter. This 55*7841e21cSRahman 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 828d943a92SSnehasish Kumar namespace { 838d943a92SSnehasish Kumar 848d943a92SSnehasish Kumar // This struct represents the cluster information for a machine basic block. 858d943a92SSnehasish Kumar struct BBClusterInfo { 868d943a92SSnehasish Kumar // MachineBasicBlock ID. 878d943a92SSnehasish Kumar unsigned MBBNumber; 888d943a92SSnehasish Kumar // Cluster ID this basic block belongs to. 898d943a92SSnehasish Kumar unsigned ClusterID; 908d943a92SSnehasish Kumar // Position of basic block within the cluster. 918d943a92SSnehasish Kumar unsigned PositionInCluster; 928d943a92SSnehasish Kumar }; 938d943a92SSnehasish Kumar 948d943a92SSnehasish Kumar using ProgramBBClusterInfoMapTy = StringMap<SmallVector<BBClusterInfo, 4>>; 958d943a92SSnehasish Kumar 968d943a92SSnehasish Kumar class BasicBlockSections : public MachineFunctionPass { 978d943a92SSnehasish Kumar public: 988d943a92SSnehasish Kumar static char ID; 998d943a92SSnehasish Kumar 1008d943a92SSnehasish Kumar // This contains the basic-block-sections profile. 1018d943a92SSnehasish Kumar const MemoryBuffer *MBuf = nullptr; 1028d943a92SSnehasish Kumar 1038d943a92SSnehasish Kumar // This encapsulates the BB cluster information for the whole program. 1048d943a92SSnehasish Kumar // 1058d943a92SSnehasish Kumar // For every function name, it contains the cluster information for (all or 1068d943a92SSnehasish Kumar // some of) its basic blocks. The cluster information for every basic block 1078d943a92SSnehasish Kumar // includes its cluster ID along with the position of the basic block in that 1088d943a92SSnehasish Kumar // cluster. 1098d943a92SSnehasish Kumar ProgramBBClusterInfoMapTy ProgramBBClusterInfo; 1108d943a92SSnehasish Kumar 1118d943a92SSnehasish Kumar // Some functions have alias names. We use this map to find the main alias 1128d943a92SSnehasish Kumar // name for which we have mapping in ProgramBBClusterInfo. 1138d943a92SSnehasish Kumar StringMap<StringRef> FuncAliasMap; 1148d943a92SSnehasish Kumar 1158d943a92SSnehasish Kumar BasicBlockSections(const MemoryBuffer *Buf) 1168d943a92SSnehasish Kumar : MachineFunctionPass(ID), MBuf(Buf) { 1178d943a92SSnehasish Kumar initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry()); 1188d943a92SSnehasish Kumar }; 1198d943a92SSnehasish Kumar 1208d943a92SSnehasish Kumar BasicBlockSections() : MachineFunctionPass(ID) { 1218d943a92SSnehasish Kumar initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry()); 1228d943a92SSnehasish Kumar } 1238d943a92SSnehasish Kumar 1248d943a92SSnehasish Kumar StringRef getPassName() const override { 1258d943a92SSnehasish Kumar return "Basic Block Sections Analysis"; 1268d943a92SSnehasish Kumar } 1278d943a92SSnehasish Kumar 1288d943a92SSnehasish Kumar void getAnalysisUsage(AnalysisUsage &AU) const override; 1298d943a92SSnehasish Kumar 1308d943a92SSnehasish Kumar /// Read profiles of basic blocks if available here. 1318d943a92SSnehasish Kumar bool doInitialization(Module &M) override; 1328d943a92SSnehasish Kumar 1338d943a92SSnehasish Kumar /// Identify basic blocks that need separate sections and prepare to emit them 1348d943a92SSnehasish Kumar /// accordingly. 1358d943a92SSnehasish Kumar bool runOnMachineFunction(MachineFunction &MF) override; 1368d943a92SSnehasish Kumar }; 1378d943a92SSnehasish Kumar 1388d943a92SSnehasish Kumar } // end anonymous namespace 1398d943a92SSnehasish Kumar 1408d943a92SSnehasish Kumar char BasicBlockSections::ID = 0; 1418d943a92SSnehasish Kumar INITIALIZE_PASS(BasicBlockSections, "bbsections-prepare", 1428d943a92SSnehasish Kumar "Prepares for basic block sections, by splitting functions " 1438d943a92SSnehasish Kumar "into clusters of basic blocks.", 1448d943a92SSnehasish Kumar false, false) 1458d943a92SSnehasish Kumar 1468d943a92SSnehasish Kumar // This function updates and optimizes the branching instructions of every basic 1478d943a92SSnehasish Kumar // block in a given function to account for changes in the layout. 1488d943a92SSnehasish Kumar static void updateBranches( 1498d943a92SSnehasish Kumar MachineFunction &MF, 1508d943a92SSnehasish Kumar const SmallVector<MachineBasicBlock *, 4> &PreLayoutFallThroughs) { 1518d943a92SSnehasish Kumar const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 1528d943a92SSnehasish Kumar SmallVector<MachineOperand, 4> Cond; 1538d943a92SSnehasish Kumar for (auto &MBB : MF) { 1548d943a92SSnehasish Kumar auto NextMBBI = std::next(MBB.getIterator()); 1558d943a92SSnehasish Kumar auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()]; 1568d943a92SSnehasish Kumar // If this block had a fallthrough before we need an explicit unconditional 1578d943a92SSnehasish Kumar // branch to that block if either 1588d943a92SSnehasish Kumar // 1- the block ends a section, which means its next block may be 1598d943a92SSnehasish Kumar // reorderd by the linker, or 1608d943a92SSnehasish Kumar // 2- the fallthrough block is not adjacent to the block in the new 1618d943a92SSnehasish Kumar // order. 1628d943a92SSnehasish Kumar if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB)) 1638d943a92SSnehasish Kumar TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc()); 1648d943a92SSnehasish Kumar 1658d943a92SSnehasish Kumar // We do not optimize branches for machine basic blocks ending sections, as 1668d943a92SSnehasish Kumar // their adjacent block might be reordered by the linker. 1678d943a92SSnehasish Kumar if (MBB.isEndSection()) 1688d943a92SSnehasish Kumar continue; 1698d943a92SSnehasish Kumar 1708d943a92SSnehasish Kumar // It might be possible to optimize branches by flipping the branch 1718d943a92SSnehasish Kumar // condition. 1728d943a92SSnehasish Kumar Cond.clear(); 1738d943a92SSnehasish Kumar MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 1748d943a92SSnehasish Kumar if (TII->analyzeBranch(MBB, TBB, FBB, Cond)) 1758d943a92SSnehasish Kumar continue; 1768d943a92SSnehasish Kumar MBB.updateTerminator(FTMBB); 1778d943a92SSnehasish Kumar } 1788d943a92SSnehasish Kumar } 1798d943a92SSnehasish Kumar 1808d943a92SSnehasish Kumar // This function provides the BBCluster information associated with a function. 1818d943a92SSnehasish Kumar // Returns true if a valid association exists and false otherwise. 1828d943a92SSnehasish Kumar static bool getBBClusterInfoForFunction( 1838d943a92SSnehasish Kumar const MachineFunction &MF, const StringMap<StringRef> FuncAliasMap, 1848d943a92SSnehasish Kumar const ProgramBBClusterInfoMapTy &ProgramBBClusterInfo, 1858d943a92SSnehasish Kumar std::vector<Optional<BBClusterInfo>> &V) { 1868d943a92SSnehasish Kumar // Get the main alias name for the function. 1878d943a92SSnehasish Kumar auto FuncName = MF.getName(); 1888d943a92SSnehasish Kumar auto R = FuncAliasMap.find(FuncName); 1898d943a92SSnehasish Kumar StringRef AliasName = R == FuncAliasMap.end() ? FuncName : R->second; 1908d943a92SSnehasish Kumar 1918d943a92SSnehasish Kumar // Find the assoicated cluster information. 1928d943a92SSnehasish Kumar auto P = ProgramBBClusterInfo.find(AliasName); 1938d943a92SSnehasish Kumar if (P == ProgramBBClusterInfo.end()) 1948d943a92SSnehasish Kumar return false; 1958d943a92SSnehasish Kumar 1968d943a92SSnehasish Kumar if (P->second.empty()) { 1978d943a92SSnehasish Kumar // This indicates that sections are desired for all basic blocks of this 1988d943a92SSnehasish Kumar // function. We clear the BBClusterInfo vector to denote this. 1998d943a92SSnehasish Kumar V.clear(); 2008d943a92SSnehasish Kumar return true; 2018d943a92SSnehasish Kumar } 2028d943a92SSnehasish Kumar 2038d943a92SSnehasish Kumar V.resize(MF.getNumBlockIDs()); 2048d943a92SSnehasish Kumar for (auto bbClusterInfo : P->second) { 2058d943a92SSnehasish Kumar // Bail out if the cluster information contains invalid MBB numbers. 2068d943a92SSnehasish Kumar if (bbClusterInfo.MBBNumber >= MF.getNumBlockIDs()) 2078d943a92SSnehasish Kumar return false; 2088d943a92SSnehasish Kumar V[bbClusterInfo.MBBNumber] = bbClusterInfo; 2098d943a92SSnehasish Kumar } 2108d943a92SSnehasish Kumar return true; 2118d943a92SSnehasish Kumar } 2128d943a92SSnehasish Kumar 2138d943a92SSnehasish Kumar // This function sorts basic blocks according to the cluster's information. 2148d943a92SSnehasish Kumar // All explicitly specified clusters of basic blocks will be ordered 2158d943a92SSnehasish Kumar // accordingly. All non-specified BBs go into a separate "Cold" section. 2168d943a92SSnehasish Kumar // Additionally, if exception handling landing pads end up in more than one 2178d943a92SSnehasish Kumar // clusters, they are moved into a single "Exception" section. Eventually, 2188d943a92SSnehasish Kumar // clusters are ordered in increasing order of their IDs, with the "Exception" 2198d943a92SSnehasish Kumar // and "Cold" succeeding all other clusters. 2208d943a92SSnehasish Kumar // FuncBBClusterInfo represent the cluster information for basic blocks. If this 2218d943a92SSnehasish Kumar // is empty, it means unique sections for all basic blocks in the function. 22294faadacSSnehasish Kumar static void 22394faadacSSnehasish Kumar assignSections(MachineFunction &MF, 2248d943a92SSnehasish Kumar const std::vector<Optional<BBClusterInfo>> &FuncBBClusterInfo) { 2258d943a92SSnehasish Kumar assert(MF.hasBBSections() && "BB Sections is not set for function."); 2268d943a92SSnehasish Kumar // This variable stores the section ID of the cluster containing eh_pads (if 2278d943a92SSnehasish Kumar // all eh_pads are one cluster). If more than one cluster contain eh_pads, we 2288d943a92SSnehasish Kumar // set it equal to ExceptionSectionID. 2298d943a92SSnehasish Kumar Optional<MBBSectionID> EHPadsSectionID; 2308d943a92SSnehasish Kumar 2318d943a92SSnehasish Kumar for (auto &MBB : MF) { 2328d943a92SSnehasish Kumar // With the 'all' option, every basic block is placed in a unique section. 2338d943a92SSnehasish Kumar // With the 'list' option, every basic block is placed in a section 2348d943a92SSnehasish Kumar // associated with its cluster, unless we want individual unique sections 2358d943a92SSnehasish Kumar // for every basic block in this function (if FuncBBClusterInfo is empty). 2368d943a92SSnehasish Kumar if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All || 2378d943a92SSnehasish Kumar FuncBBClusterInfo.empty()) { 2388d943a92SSnehasish Kumar // If unique sections are desired for all basic blocks of the function, we 2398d943a92SSnehasish Kumar // set every basic block's section ID equal to its number (basic block 2408d943a92SSnehasish Kumar // id). This further ensures that basic blocks are ordered canonically. 2418d943a92SSnehasish Kumar MBB.setSectionID({static_cast<unsigned int>(MBB.getNumber())}); 2428d943a92SSnehasish Kumar } else if (FuncBBClusterInfo[MBB.getNumber()].hasValue()) 2438d943a92SSnehasish Kumar MBB.setSectionID(FuncBBClusterInfo[MBB.getNumber()]->ClusterID); 2448d943a92SSnehasish Kumar else { 2458d943a92SSnehasish Kumar // BB goes into the special cold section if it is not specified in the 2468d943a92SSnehasish Kumar // cluster info map. 2478d943a92SSnehasish Kumar MBB.setSectionID(MBBSectionID::ColdSectionID); 2488d943a92SSnehasish Kumar } 2498d943a92SSnehasish Kumar 2508d943a92SSnehasish Kumar if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() && 2518d943a92SSnehasish Kumar EHPadsSectionID != MBBSectionID::ExceptionSectionID) { 2528d943a92SSnehasish Kumar // If we already have one cluster containing eh_pads, this must be updated 2538d943a92SSnehasish Kumar // to ExceptionSectionID. Otherwise, we set it equal to the current 2548d943a92SSnehasish Kumar // section ID. 2558d943a92SSnehasish Kumar EHPadsSectionID = EHPadsSectionID.hasValue() 2568d943a92SSnehasish Kumar ? MBBSectionID::ExceptionSectionID 2578d943a92SSnehasish Kumar : MBB.getSectionID(); 2588d943a92SSnehasish Kumar } 2598d943a92SSnehasish Kumar } 2608d943a92SSnehasish Kumar 2618d943a92SSnehasish Kumar // If EHPads are in more than one section, this places all of them in the 2628d943a92SSnehasish Kumar // special exception section. 2638d943a92SSnehasish Kumar if (EHPadsSectionID == MBBSectionID::ExceptionSectionID) 2648d943a92SSnehasish Kumar for (auto &MBB : MF) 2658d943a92SSnehasish Kumar if (MBB.isEHPad()) 2668d943a92SSnehasish Kumar MBB.setSectionID(EHPadsSectionID.getValue()); 26794faadacSSnehasish Kumar } 2688d943a92SSnehasish Kumar 26994faadacSSnehasish Kumar void llvm::sortBasicBlocksAndUpdateBranches( 27094faadacSSnehasish Kumar MachineFunction &MF, MachineBasicBlockComparator MBBCmp) { 2718d943a92SSnehasish Kumar SmallVector<MachineBasicBlock *, 4> PreLayoutFallThroughs( 2728d943a92SSnehasish Kumar MF.getNumBlockIDs()); 2738d943a92SSnehasish Kumar for (auto &MBB : MF) 2748d943a92SSnehasish Kumar PreLayoutFallThroughs[MBB.getNumber()] = MBB.getFallThrough(); 2758d943a92SSnehasish Kumar 27694faadacSSnehasish Kumar MF.sort(MBBCmp); 2778d943a92SSnehasish Kumar 2788d943a92SSnehasish Kumar // Set IsBeginSection and IsEndSection according to the assigned section IDs. 2798d943a92SSnehasish Kumar MF.assignBeginEndSections(); 2808d943a92SSnehasish Kumar 2818d943a92SSnehasish Kumar // After reordering basic blocks, we must update basic block branches to 2828d943a92SSnehasish Kumar // insert explicit fallthrough branches when required and optimize branches 2838d943a92SSnehasish Kumar // when possible. 2848d943a92SSnehasish Kumar updateBranches(MF, PreLayoutFallThroughs); 2858d943a92SSnehasish Kumar } 2868d943a92SSnehasish Kumar 2878d943a92SSnehasish Kumar bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) { 2888d943a92SSnehasish Kumar auto BBSectionsType = MF.getTarget().getBBSectionsType(); 2898d943a92SSnehasish Kumar assert(BBSectionsType != BasicBlockSection::None && 2908d943a92SSnehasish Kumar "BB Sections not enabled!"); 2918d943a92SSnehasish Kumar // Renumber blocks before sorting them for basic block sections. This is 2928d943a92SSnehasish Kumar // useful during sorting, basic blocks in the same section will retain the 2938d943a92SSnehasish Kumar // default order. This renumbering should also be done for basic block 2948d943a92SSnehasish Kumar // labels to match the profiles with the correct blocks. 2958d943a92SSnehasish Kumar MF.RenumberBlocks(); 2968d943a92SSnehasish Kumar 2978d943a92SSnehasish Kumar if (BBSectionsType == BasicBlockSection::Labels) { 2988d943a92SSnehasish Kumar MF.setBBSectionsType(BBSectionsType); 2998d943a92SSnehasish Kumar return true; 3008d943a92SSnehasish Kumar } 3018d943a92SSnehasish Kumar 3028d943a92SSnehasish Kumar std::vector<Optional<BBClusterInfo>> FuncBBClusterInfo; 3038d943a92SSnehasish Kumar if (BBSectionsType == BasicBlockSection::List && 3048d943a92SSnehasish Kumar !getBBClusterInfoForFunction(MF, FuncAliasMap, ProgramBBClusterInfo, 3058d943a92SSnehasish Kumar FuncBBClusterInfo)) 3068d943a92SSnehasish Kumar return true; 3078d943a92SSnehasish Kumar MF.setBBSectionsType(BBSectionsType); 30894faadacSSnehasish Kumar assignSections(MF, FuncBBClusterInfo); 30994faadacSSnehasish Kumar 31094faadacSSnehasish Kumar // We make sure that the cluster including the entry basic block precedes all 31194faadacSSnehasish Kumar // other clusters. 31294faadacSSnehasish Kumar auto EntryBBSectionID = MF.front().getSectionID(); 31394faadacSSnehasish Kumar 31494faadacSSnehasish Kumar // Helper function for ordering BB sections as follows: 31594faadacSSnehasish Kumar // * Entry section (section including the entry block). 31694faadacSSnehasish Kumar // * Regular sections (in increasing order of their Number). 31794faadacSSnehasish Kumar // ... 31894faadacSSnehasish Kumar // * Exception section 31994faadacSSnehasish Kumar // * Cold section 32094faadacSSnehasish Kumar auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS, 32194faadacSSnehasish Kumar const MBBSectionID &RHS) { 32294faadacSSnehasish Kumar // We make sure that the section containing the entry block precedes all the 32394faadacSSnehasish Kumar // other sections. 32494faadacSSnehasish Kumar if (LHS == EntryBBSectionID || RHS == EntryBBSectionID) 32594faadacSSnehasish Kumar return LHS == EntryBBSectionID; 32694faadacSSnehasish Kumar return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type; 32794faadacSSnehasish Kumar }; 32894faadacSSnehasish Kumar 32994faadacSSnehasish Kumar // We sort all basic blocks to make sure the basic blocks of every cluster are 33094faadacSSnehasish Kumar // contiguous and ordered accordingly. Furthermore, clusters are ordered in 33194faadacSSnehasish Kumar // increasing order of their section IDs, with the exception and the 33294faadacSSnehasish Kumar // cold section placed at the end of the function. 33394faadacSSnehasish Kumar auto Comparator = [&](const MachineBasicBlock &X, 33494faadacSSnehasish Kumar const MachineBasicBlock &Y) { 33594faadacSSnehasish Kumar auto XSectionID = X.getSectionID(); 33694faadacSSnehasish Kumar auto YSectionID = Y.getSectionID(); 33794faadacSSnehasish Kumar if (XSectionID != YSectionID) 33894faadacSSnehasish Kumar return MBBSectionOrder(XSectionID, YSectionID); 33994faadacSSnehasish Kumar // If the two basic block are in the same section, the order is decided by 34094faadacSSnehasish Kumar // their position within the section. 34194faadacSSnehasish Kumar if (XSectionID.Type == MBBSectionID::SectionType::Default) 34294faadacSSnehasish Kumar return FuncBBClusterInfo[X.getNumber()]->PositionInCluster < 34394faadacSSnehasish Kumar FuncBBClusterInfo[Y.getNumber()]->PositionInCluster; 34494faadacSSnehasish Kumar return X.getNumber() < Y.getNumber(); 34594faadacSSnehasish Kumar }; 34694faadacSSnehasish Kumar 34794faadacSSnehasish Kumar sortBasicBlocksAndUpdateBranches(MF, Comparator); 3488d943a92SSnehasish Kumar return true; 3498d943a92SSnehasish Kumar } 3508d943a92SSnehasish Kumar 3518d943a92SSnehasish Kumar // Basic Block Sections can be enabled for a subset of machine basic blocks. 3528d943a92SSnehasish Kumar // This is done by passing a file containing names of functions for which basic 3538d943a92SSnehasish Kumar // block sections are desired. Additionally, machine basic block ids of the 3548d943a92SSnehasish Kumar // functions can also be specified for a finer granularity. Moreover, a cluster 3558d943a92SSnehasish Kumar // of basic blocks could be assigned to the same section. 3568d943a92SSnehasish Kumar // A file with basic block sections for all of function main and three blocks 3578d943a92SSnehasish Kumar // for function foo (of which 1 and 2 are placed in a cluster) looks like this: 3588d943a92SSnehasish Kumar // ---------------------------- 3598d943a92SSnehasish Kumar // list.txt: 3608d943a92SSnehasish Kumar // !main 3618d943a92SSnehasish Kumar // !foo 3628d943a92SSnehasish Kumar // !!1 2 3638d943a92SSnehasish Kumar // !!4 3648d943a92SSnehasish Kumar static Error getBBClusterInfo(const MemoryBuffer *MBuf, 3658d943a92SSnehasish Kumar ProgramBBClusterInfoMapTy &ProgramBBClusterInfo, 3668d943a92SSnehasish Kumar StringMap<StringRef> &FuncAliasMap) { 3678d943a92SSnehasish Kumar assert(MBuf); 3688d943a92SSnehasish Kumar line_iterator LineIt(*MBuf, /*SkipBlanks=*/true, /*CommentMarker=*/'#'); 3698d943a92SSnehasish Kumar 3708d943a92SSnehasish Kumar auto invalidProfileError = [&](auto Message) { 3718d943a92SSnehasish Kumar return make_error<StringError>( 3728d943a92SSnehasish Kumar Twine("Invalid profile " + MBuf->getBufferIdentifier() + " at line " + 3738d943a92SSnehasish Kumar Twine(LineIt.line_number()) + ": " + Message), 3748d943a92SSnehasish Kumar inconvertibleErrorCode()); 3758d943a92SSnehasish Kumar }; 3768d943a92SSnehasish Kumar 3778d943a92SSnehasish Kumar auto FI = ProgramBBClusterInfo.end(); 3788d943a92SSnehasish Kumar 3798d943a92SSnehasish Kumar // Current cluster ID corresponding to this function. 3808d943a92SSnehasish Kumar unsigned CurrentCluster = 0; 3818d943a92SSnehasish Kumar // Current position in the current cluster. 3828d943a92SSnehasish Kumar unsigned CurrentPosition = 0; 3838d943a92SSnehasish Kumar 3848d943a92SSnehasish Kumar // Temporary set to ensure every basic block ID appears once in the clusters 3858d943a92SSnehasish Kumar // of a function. 3868d943a92SSnehasish Kumar SmallSet<unsigned, 4> FuncBBIDs; 3878d943a92SSnehasish Kumar 3888d943a92SSnehasish Kumar for (; !LineIt.is_at_eof(); ++LineIt) { 3898d943a92SSnehasish Kumar StringRef S(*LineIt); 3908d943a92SSnehasish Kumar if (S[0] == '@') 3918d943a92SSnehasish Kumar continue; 3928d943a92SSnehasish Kumar // Check for the leading "!" 3938d943a92SSnehasish Kumar if (!S.consume_front("!") || S.empty()) 3948d943a92SSnehasish Kumar break; 3958d943a92SSnehasish Kumar // Check for second "!" which indicates a cluster of basic blocks. 3968d943a92SSnehasish Kumar if (S.consume_front("!")) { 3978d943a92SSnehasish Kumar if (FI == ProgramBBClusterInfo.end()) 3988d943a92SSnehasish Kumar return invalidProfileError( 3998d943a92SSnehasish Kumar "Cluster list does not follow a function name specifier."); 4008d943a92SSnehasish Kumar SmallVector<StringRef, 4> BBIndexes; 4018d943a92SSnehasish Kumar S.split(BBIndexes, ' '); 4028d943a92SSnehasish Kumar // Reset current cluster position. 4038d943a92SSnehasish Kumar CurrentPosition = 0; 4048d943a92SSnehasish Kumar for (auto BBIndexStr : BBIndexes) { 4058d943a92SSnehasish Kumar unsigned long long BBIndex; 4068d943a92SSnehasish Kumar if (getAsUnsignedInteger(BBIndexStr, 10, BBIndex)) 4078d943a92SSnehasish Kumar return invalidProfileError(Twine("Unsigned integer expected: '") + 4088d943a92SSnehasish Kumar BBIndexStr + "'."); 4098d943a92SSnehasish Kumar if (!FuncBBIDs.insert(BBIndex).second) 4108d943a92SSnehasish Kumar return invalidProfileError(Twine("Duplicate basic block id found '") + 4118d943a92SSnehasish Kumar BBIndexStr + "'."); 4128d943a92SSnehasish Kumar if (!BBIndex && CurrentPosition) 4138d943a92SSnehasish Kumar return invalidProfileError("Entry BB (0) does not begin a cluster."); 4148d943a92SSnehasish Kumar 4158d943a92SSnehasish Kumar FI->second.emplace_back(BBClusterInfo{ 4168d943a92SSnehasish Kumar ((unsigned)BBIndex), CurrentCluster, CurrentPosition++}); 4178d943a92SSnehasish Kumar } 4188d943a92SSnehasish Kumar CurrentCluster++; 4198d943a92SSnehasish Kumar } else { // This is a function name specifier. 4208d943a92SSnehasish Kumar // Function aliases are separated using '/'. We use the first function 4218d943a92SSnehasish Kumar // name for the cluster info mapping and delegate all other aliases to 4228d943a92SSnehasish Kumar // this one. 4238d943a92SSnehasish Kumar SmallVector<StringRef, 4> Aliases; 4248d943a92SSnehasish Kumar S.split(Aliases, '/'); 4258d943a92SSnehasish Kumar for (size_t i = 1; i < Aliases.size(); ++i) 4268d943a92SSnehasish Kumar FuncAliasMap.try_emplace(Aliases[i], Aliases.front()); 4278d943a92SSnehasish Kumar 4288d943a92SSnehasish Kumar // Prepare for parsing clusters of this function name. 4298d943a92SSnehasish Kumar // Start a new cluster map for this function name. 4308d943a92SSnehasish Kumar FI = ProgramBBClusterInfo.try_emplace(Aliases.front()).first; 4318d943a92SSnehasish Kumar CurrentCluster = 0; 4328d943a92SSnehasish Kumar FuncBBIDs.clear(); 4338d943a92SSnehasish Kumar } 4348d943a92SSnehasish Kumar } 4358d943a92SSnehasish Kumar return Error::success(); 4368d943a92SSnehasish Kumar } 4378d943a92SSnehasish Kumar 4388d943a92SSnehasish Kumar bool BasicBlockSections::doInitialization(Module &M) { 4398d943a92SSnehasish Kumar if (!MBuf) 4408d943a92SSnehasish Kumar return false; 4418d943a92SSnehasish Kumar if (auto Err = getBBClusterInfo(MBuf, ProgramBBClusterInfo, FuncAliasMap)) 4428d943a92SSnehasish Kumar report_fatal_error(std::move(Err)); 4438d943a92SSnehasish Kumar return false; 4448d943a92SSnehasish Kumar } 4458d943a92SSnehasish Kumar 4468d943a92SSnehasish Kumar void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const { 4478d943a92SSnehasish Kumar AU.setPreservesAll(); 4488d943a92SSnehasish Kumar MachineFunctionPass::getAnalysisUsage(AU); 4498d943a92SSnehasish Kumar } 4508d943a92SSnehasish Kumar 4518d943a92SSnehasish Kumar MachineFunctionPass * 4528d943a92SSnehasish Kumar llvm::createBasicBlockSectionsPass(const MemoryBuffer *Buf) { 4538d943a92SSnehasish Kumar return new BasicBlockSections(Buf); 4548d943a92SSnehasish Kumar } 455