18d943a92SSnehasish Kumar //===-- BasicBlockSections.cpp ---=========--------------------------------===// 28d943a92SSnehasish Kumar // 38d943a92SSnehasish Kumar // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 48d943a92SSnehasish Kumar // See https://llvm.org/LICENSE.txt for license information. 58d943a92SSnehasish Kumar // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 68d943a92SSnehasish Kumar // 78d943a92SSnehasish Kumar //===----------------------------------------------------------------------===// 88d943a92SSnehasish Kumar // 98d943a92SSnehasish Kumar // BasicBlockSections implementation. 108d943a92SSnehasish Kumar // 118d943a92SSnehasish Kumar // The purpose of this pass is to assign sections to basic blocks when 128d943a92SSnehasish Kumar // -fbasic-block-sections= option is used. Further, with profile information 138d943a92SSnehasish Kumar // only the subset of basic blocks with profiles are placed in separate sections 148d943a92SSnehasish Kumar // and the rest are grouped in a cold section. The exception handling blocks are 158d943a92SSnehasish Kumar // treated specially to ensure they are all in one seciton. 168d943a92SSnehasish Kumar // 178d943a92SSnehasish Kumar // Basic Block Sections 188d943a92SSnehasish Kumar // ==================== 198d943a92SSnehasish Kumar // 208d943a92SSnehasish Kumar // With option, -fbasic-block-sections=list, every function may be split into 218d943a92SSnehasish Kumar // clusters of basic blocks. Every cluster will be emitted into a separate 228d943a92SSnehasish Kumar // section with its basic blocks sequenced in the given order. To get the 238d943a92SSnehasish Kumar // optimized performance, the clusters must form an optimal BB layout for the 248d943a92SSnehasish Kumar // function. Every cluster's section is labeled with a symbol to allow the 258d943a92SSnehasish Kumar // linker to reorder the sections in any arbitrary sequence. A global order of 268d943a92SSnehasish Kumar // these sections would encapsulate the function layout. 278d943a92SSnehasish Kumar // 288d943a92SSnehasish Kumar // There are a couple of challenges to be addressed: 298d943a92SSnehasish Kumar // 308d943a92SSnehasish Kumar // 1. The last basic block of every cluster should not have any implicit 318d943a92SSnehasish Kumar // fallthrough to its next basic block, as it can be reordered by the linker. 328d943a92SSnehasish Kumar // The compiler should make these fallthroughs explicit by adding 338d943a92SSnehasish Kumar // unconditional jumps.. 348d943a92SSnehasish Kumar // 358d943a92SSnehasish Kumar // 2. All inter-cluster branch targets would now need to be resolved by the 368d943a92SSnehasish Kumar // linker as they cannot be calculated during compile time. This is done 378d943a92SSnehasish Kumar // using static relocations. Further, the compiler tries to use short branch 388d943a92SSnehasish Kumar // instructions on some ISAs for small branch offsets. This is not possible 398d943a92SSnehasish Kumar // for inter-cluster branches as the offset is not determined at compile 408d943a92SSnehasish Kumar // time, and therefore, long branch instructions have to be used for those. 418d943a92SSnehasish Kumar // 428d943a92SSnehasish Kumar // 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission 438d943a92SSnehasish Kumar // needs special handling with basic block sections. DebugInfo needs to be 448d943a92SSnehasish Kumar // emitted with more relocations as basic block sections can break a 458d943a92SSnehasish Kumar // function into potentially several disjoint pieces, and CFI needs to be 468d943a92SSnehasish Kumar // emitted per cluster. This also bloats the object file and binary sizes. 478d943a92SSnehasish Kumar // 488d943a92SSnehasish Kumar // Basic Block Labels 498d943a92SSnehasish Kumar // ================== 508d943a92SSnehasish Kumar // 517841e21cSRahman Lavaee // With -fbasic-block-sections=labels, we emit the offsets of BB addresses of 522b0c5d76SRahman Lavaee // every function into the .llvm_bb_addr_map section. Along with the function 532b0c5d76SRahman Lavaee // symbols, this allows for mapping of virtual addresses in PMU profiles back to 542b0c5d76SRahman Lavaee // the corresponding basic blocks. This logic is implemented in AsmPrinter. This 557841e21cSRahman Lavaee // pass only assigns the BBSectionType of every function to ``labels``. 568d943a92SSnehasish Kumar // 578d943a92SSnehasish Kumar //===----------------------------------------------------------------------===// 588d943a92SSnehasish Kumar 598d943a92SSnehasish Kumar #include "llvm/ADT/Optional.h" 608d943a92SSnehasish Kumar #include "llvm/ADT/SmallSet.h" 618d943a92SSnehasish Kumar #include "llvm/ADT/SmallVector.h" 628d943a92SSnehasish Kumar #include "llvm/ADT/StringMap.h" 638d943a92SSnehasish Kumar #include "llvm/ADT/StringRef.h" 6494faadacSSnehasish Kumar #include "llvm/CodeGen/BasicBlockSectionUtils.h" 658d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineFunction.h" 668d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineFunctionPass.h" 678d943a92SSnehasish Kumar #include "llvm/CodeGen/MachineModuleInfo.h" 688d943a92SSnehasish Kumar #include "llvm/CodeGen/Passes.h" 698d943a92SSnehasish Kumar #include "llvm/CodeGen/TargetInstrInfo.h" 708d943a92SSnehasish Kumar #include "llvm/InitializePasses.h" 718d943a92SSnehasish Kumar #include "llvm/Support/Error.h" 728d943a92SSnehasish Kumar #include "llvm/Support/LineIterator.h" 738d943a92SSnehasish Kumar #include "llvm/Support/MemoryBuffer.h" 748d943a92SSnehasish Kumar #include "llvm/Target/TargetMachine.h" 758d943a92SSnehasish Kumar 768d943a92SSnehasish Kumar using llvm::SmallSet; 778d943a92SSnehasish Kumar using llvm::SmallVector; 788d943a92SSnehasish Kumar using llvm::StringMap; 798d943a92SSnehasish Kumar using llvm::StringRef; 808d943a92SSnehasish Kumar using namespace llvm; 818d943a92SSnehasish Kumar 82d2696decSSnehasish Kumar // Placing the cold clusters in a separate section mitigates against poor 83d2696decSSnehasish Kumar // profiles and allows optimizations such as hugepage mapping to be applied at a 8477638a53SSnehasish Kumar // section granularity. Defaults to ".text.split." which is recognized by lld 8577638a53SSnehasish Kumar // via the `-z keep-text-section-prefix` flag. 86d2696decSSnehasish Kumar cl::opt<std::string> llvm::BBSectionsColdTextPrefix( 87d2696decSSnehasish Kumar "bbsections-cold-text-prefix", 88d2696decSSnehasish Kumar cl::desc("The text prefix to use for cold basic block clusters"), 8977638a53SSnehasish Kumar cl::init(".text.split."), cl::Hidden); 90d2696decSSnehasish Kumar 91c32f3998SSriraman Tallam cl::opt<bool> BBSectionsDetectSourceDrift( 92c32f3998SSriraman Tallam "bbsections-detect-source-drift", 93c32f3998SSriraman Tallam cl::desc("This checks if there is a fdo instr. profile hash " 94c32f3998SSriraman Tallam "mismatch for this function"), 95c32f3998SSriraman Tallam cl::init(true), cl::Hidden); 96c32f3998SSriraman Tallam 978d943a92SSnehasish Kumar namespace { 988d943a92SSnehasish Kumar 998d943a92SSnehasish Kumar // This struct represents the cluster information for a machine basic block. 1008d943a92SSnehasish Kumar struct BBClusterInfo { 1018d943a92SSnehasish Kumar // MachineBasicBlock ID. 1028d943a92SSnehasish Kumar unsigned MBBNumber; 1038d943a92SSnehasish Kumar // Cluster ID this basic block belongs to. 1048d943a92SSnehasish Kumar unsigned ClusterID; 1058d943a92SSnehasish Kumar // Position of basic block within the cluster. 1068d943a92SSnehasish Kumar unsigned PositionInCluster; 1078d943a92SSnehasish Kumar }; 1088d943a92SSnehasish Kumar 1098d943a92SSnehasish Kumar using ProgramBBClusterInfoMapTy = StringMap<SmallVector<BBClusterInfo, 4>>; 1108d943a92SSnehasish Kumar 1118d943a92SSnehasish Kumar class BasicBlockSections : public MachineFunctionPass { 1128d943a92SSnehasish Kumar public: 1138d943a92SSnehasish Kumar static char ID; 1148d943a92SSnehasish Kumar 1158d943a92SSnehasish Kumar // This contains the basic-block-sections profile. 1168d943a92SSnehasish Kumar const MemoryBuffer *MBuf = nullptr; 1178d943a92SSnehasish Kumar 1188d943a92SSnehasish Kumar // This encapsulates the BB cluster information for the whole program. 1198d943a92SSnehasish Kumar // 1208d943a92SSnehasish Kumar // For every function name, it contains the cluster information for (all or 1218d943a92SSnehasish Kumar // some of) its basic blocks. The cluster information for every basic block 1228d943a92SSnehasish Kumar // includes its cluster ID along with the position of the basic block in that 1238d943a92SSnehasish Kumar // cluster. 1248d943a92SSnehasish Kumar ProgramBBClusterInfoMapTy ProgramBBClusterInfo; 1258d943a92SSnehasish Kumar 1268d943a92SSnehasish Kumar // Some functions have alias names. We use this map to find the main alias 1278d943a92SSnehasish Kumar // name for which we have mapping in ProgramBBClusterInfo. 1288d943a92SSnehasish Kumar StringMap<StringRef> FuncAliasMap; 1298d943a92SSnehasish Kumar 1308d943a92SSnehasish Kumar BasicBlockSections(const MemoryBuffer *Buf) 1318d943a92SSnehasish Kumar : MachineFunctionPass(ID), MBuf(Buf) { 1328d943a92SSnehasish Kumar initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry()); 1338d943a92SSnehasish Kumar }; 1348d943a92SSnehasish Kumar 1358d943a92SSnehasish Kumar BasicBlockSections() : MachineFunctionPass(ID) { 1368d943a92SSnehasish Kumar initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry()); 1378d943a92SSnehasish Kumar } 1388d943a92SSnehasish Kumar 1398d943a92SSnehasish Kumar StringRef getPassName() const override { 1408d943a92SSnehasish Kumar return "Basic Block Sections Analysis"; 1418d943a92SSnehasish Kumar } 1428d943a92SSnehasish Kumar 1438d943a92SSnehasish Kumar void getAnalysisUsage(AnalysisUsage &AU) const override; 1448d943a92SSnehasish Kumar 1458d943a92SSnehasish Kumar /// Read profiles of basic blocks if available here. 1468d943a92SSnehasish Kumar bool doInitialization(Module &M) override; 1478d943a92SSnehasish Kumar 1488d943a92SSnehasish Kumar /// Identify basic blocks that need separate sections and prepare to emit them 1498d943a92SSnehasish Kumar /// accordingly. 1508d943a92SSnehasish Kumar bool runOnMachineFunction(MachineFunction &MF) override; 1518d943a92SSnehasish Kumar }; 1528d943a92SSnehasish Kumar 1538d943a92SSnehasish Kumar } // end anonymous namespace 1548d943a92SSnehasish Kumar 1558d943a92SSnehasish Kumar char BasicBlockSections::ID = 0; 1568d943a92SSnehasish Kumar INITIALIZE_PASS(BasicBlockSections, "bbsections-prepare", 1578d943a92SSnehasish Kumar "Prepares for basic block sections, by splitting functions " 1588d943a92SSnehasish Kumar "into clusters of basic blocks.", 1598d943a92SSnehasish Kumar false, false) 1608d943a92SSnehasish Kumar 1618d943a92SSnehasish Kumar // This function updates and optimizes the branching instructions of every basic 1628d943a92SSnehasish Kumar // block in a given function to account for changes in the layout. 1638d943a92SSnehasish Kumar static void updateBranches( 1648d943a92SSnehasish Kumar MachineFunction &MF, 1658d943a92SSnehasish Kumar const SmallVector<MachineBasicBlock *, 4> &PreLayoutFallThroughs) { 1668d943a92SSnehasish Kumar const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 1678d943a92SSnehasish Kumar SmallVector<MachineOperand, 4> Cond; 1688d943a92SSnehasish Kumar for (auto &MBB : MF) { 1698d943a92SSnehasish Kumar auto NextMBBI = std::next(MBB.getIterator()); 1708d943a92SSnehasish Kumar auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()]; 1718d943a92SSnehasish Kumar // If this block had a fallthrough before we need an explicit unconditional 1728d943a92SSnehasish Kumar // branch to that block if either 1738d943a92SSnehasish Kumar // 1- the block ends a section, which means its next block may be 1748d943a92SSnehasish Kumar // reorderd by the linker, or 1758d943a92SSnehasish Kumar // 2- the fallthrough block is not adjacent to the block in the new 1768d943a92SSnehasish Kumar // order. 1778d943a92SSnehasish Kumar if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB)) 1788d943a92SSnehasish Kumar TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc()); 1798d943a92SSnehasish Kumar 1808d943a92SSnehasish Kumar // We do not optimize branches for machine basic blocks ending sections, as 1818d943a92SSnehasish Kumar // their adjacent block might be reordered by the linker. 1828d943a92SSnehasish Kumar if (MBB.isEndSection()) 1838d943a92SSnehasish Kumar continue; 1848d943a92SSnehasish Kumar 1858d943a92SSnehasish Kumar // It might be possible to optimize branches by flipping the branch 1868d943a92SSnehasish Kumar // condition. 1878d943a92SSnehasish Kumar Cond.clear(); 1888d943a92SSnehasish Kumar MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch. 1898d943a92SSnehasish Kumar if (TII->analyzeBranch(MBB, TBB, FBB, Cond)) 1908d943a92SSnehasish Kumar continue; 1918d943a92SSnehasish Kumar MBB.updateTerminator(FTMBB); 1928d943a92SSnehasish Kumar } 1938d943a92SSnehasish Kumar } 1948d943a92SSnehasish Kumar 1958d943a92SSnehasish Kumar // This function provides the BBCluster information associated with a function. 1968d943a92SSnehasish Kumar // Returns true if a valid association exists and false otherwise. 1978d943a92SSnehasish Kumar static bool getBBClusterInfoForFunction( 1988d943a92SSnehasish Kumar const MachineFunction &MF, const StringMap<StringRef> FuncAliasMap, 1998d943a92SSnehasish Kumar const ProgramBBClusterInfoMapTy &ProgramBBClusterInfo, 2008d943a92SSnehasish Kumar std::vector<Optional<BBClusterInfo>> &V) { 2018d943a92SSnehasish Kumar // Get the main alias name for the function. 2028d943a92SSnehasish Kumar auto FuncName = MF.getName(); 2038d943a92SSnehasish Kumar auto R = FuncAliasMap.find(FuncName); 2048d943a92SSnehasish Kumar StringRef AliasName = R == FuncAliasMap.end() ? FuncName : R->second; 2058d943a92SSnehasish Kumar 2068d943a92SSnehasish Kumar // Find the assoicated cluster information. 2078d943a92SSnehasish Kumar auto P = ProgramBBClusterInfo.find(AliasName); 2088d943a92SSnehasish Kumar if (P == ProgramBBClusterInfo.end()) 2098d943a92SSnehasish Kumar return false; 2108d943a92SSnehasish Kumar 2118d943a92SSnehasish Kumar if (P->second.empty()) { 2128d943a92SSnehasish Kumar // This indicates that sections are desired for all basic blocks of this 2138d943a92SSnehasish Kumar // function. We clear the BBClusterInfo vector to denote this. 2148d943a92SSnehasish Kumar V.clear(); 2158d943a92SSnehasish Kumar return true; 2168d943a92SSnehasish Kumar } 2178d943a92SSnehasish Kumar 2188d943a92SSnehasish Kumar V.resize(MF.getNumBlockIDs()); 2198d943a92SSnehasish Kumar for (auto bbClusterInfo : P->second) { 2208d943a92SSnehasish Kumar // Bail out if the cluster information contains invalid MBB numbers. 2218d943a92SSnehasish Kumar if (bbClusterInfo.MBBNumber >= MF.getNumBlockIDs()) 2228d943a92SSnehasish Kumar return false; 2238d943a92SSnehasish Kumar V[bbClusterInfo.MBBNumber] = bbClusterInfo; 2248d943a92SSnehasish Kumar } 2258d943a92SSnehasish Kumar return true; 2268d943a92SSnehasish Kumar } 2278d943a92SSnehasish Kumar 2288d943a92SSnehasish Kumar // This function sorts basic blocks according to the cluster's information. 2298d943a92SSnehasish Kumar // All explicitly specified clusters of basic blocks will be ordered 2308d943a92SSnehasish Kumar // accordingly. All non-specified BBs go into a separate "Cold" section. 2318d943a92SSnehasish Kumar // Additionally, if exception handling landing pads end up in more than one 2328d943a92SSnehasish Kumar // clusters, they are moved into a single "Exception" section. Eventually, 2338d943a92SSnehasish Kumar // clusters are ordered in increasing order of their IDs, with the "Exception" 2348d943a92SSnehasish Kumar // and "Cold" succeeding all other clusters. 2358d943a92SSnehasish Kumar // FuncBBClusterInfo represent the cluster information for basic blocks. If this 2368d943a92SSnehasish Kumar // is empty, it means unique sections for all basic blocks in the function. 23794faadacSSnehasish Kumar static void 23894faadacSSnehasish Kumar assignSections(MachineFunction &MF, 2398d943a92SSnehasish Kumar const std::vector<Optional<BBClusterInfo>> &FuncBBClusterInfo) { 2408d943a92SSnehasish Kumar assert(MF.hasBBSections() && "BB Sections is not set for function."); 2418d943a92SSnehasish Kumar // This variable stores the section ID of the cluster containing eh_pads (if 2428d943a92SSnehasish Kumar // all eh_pads are one cluster). If more than one cluster contain eh_pads, we 2438d943a92SSnehasish Kumar // set it equal to ExceptionSectionID. 2448d943a92SSnehasish Kumar Optional<MBBSectionID> EHPadsSectionID; 2458d943a92SSnehasish Kumar 2468d943a92SSnehasish Kumar for (auto &MBB : MF) { 2478d943a92SSnehasish Kumar // With the 'all' option, every basic block is placed in a unique section. 2488d943a92SSnehasish Kumar // With the 'list' option, every basic block is placed in a section 2498d943a92SSnehasish Kumar // associated with its cluster, unless we want individual unique sections 2508d943a92SSnehasish Kumar // for every basic block in this function (if FuncBBClusterInfo is empty). 2518d943a92SSnehasish Kumar if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All || 2528d943a92SSnehasish Kumar FuncBBClusterInfo.empty()) { 2538d943a92SSnehasish Kumar // If unique sections are desired for all basic blocks of the function, we 2548d943a92SSnehasish Kumar // set every basic block's section ID equal to its number (basic block 2558d943a92SSnehasish Kumar // id). This further ensures that basic blocks are ordered canonically. 2568d943a92SSnehasish Kumar MBB.setSectionID({static_cast<unsigned int>(MBB.getNumber())}); 2578d943a92SSnehasish Kumar } else if (FuncBBClusterInfo[MBB.getNumber()].hasValue()) 2588d943a92SSnehasish Kumar MBB.setSectionID(FuncBBClusterInfo[MBB.getNumber()]->ClusterID); 2598d943a92SSnehasish Kumar else { 2608d943a92SSnehasish Kumar // BB goes into the special cold section if it is not specified in the 2618d943a92SSnehasish Kumar // cluster info map. 2628d943a92SSnehasish Kumar MBB.setSectionID(MBBSectionID::ColdSectionID); 2638d943a92SSnehasish Kumar } 2648d943a92SSnehasish Kumar 2658d943a92SSnehasish Kumar if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() && 2668d943a92SSnehasish Kumar EHPadsSectionID != MBBSectionID::ExceptionSectionID) { 2678d943a92SSnehasish Kumar // If we already have one cluster containing eh_pads, this must be updated 2688d943a92SSnehasish Kumar // to ExceptionSectionID. Otherwise, we set it equal to the current 2698d943a92SSnehasish Kumar // section ID. 2708d943a92SSnehasish Kumar EHPadsSectionID = EHPadsSectionID.hasValue() 2718d943a92SSnehasish Kumar ? MBBSectionID::ExceptionSectionID 2728d943a92SSnehasish Kumar : MBB.getSectionID(); 2738d943a92SSnehasish Kumar } 2748d943a92SSnehasish Kumar } 2758d943a92SSnehasish Kumar 2768d943a92SSnehasish Kumar // If EHPads are in more than one section, this places all of them in the 2778d943a92SSnehasish Kumar // special exception section. 2788d943a92SSnehasish Kumar if (EHPadsSectionID == MBBSectionID::ExceptionSectionID) 2798d943a92SSnehasish Kumar for (auto &MBB : MF) 2808d943a92SSnehasish Kumar if (MBB.isEHPad()) 2818d943a92SSnehasish Kumar MBB.setSectionID(EHPadsSectionID.getValue()); 28294faadacSSnehasish Kumar } 2838d943a92SSnehasish Kumar 28494faadacSSnehasish Kumar void llvm::sortBasicBlocksAndUpdateBranches( 28594faadacSSnehasish Kumar MachineFunction &MF, MachineBasicBlockComparator MBBCmp) { 2868d943a92SSnehasish Kumar SmallVector<MachineBasicBlock *, 4> PreLayoutFallThroughs( 2878d943a92SSnehasish Kumar MF.getNumBlockIDs()); 2888d943a92SSnehasish Kumar for (auto &MBB : MF) 2898d943a92SSnehasish Kumar PreLayoutFallThroughs[MBB.getNumber()] = MBB.getFallThrough(); 2908d943a92SSnehasish Kumar 29194faadacSSnehasish Kumar MF.sort(MBBCmp); 2928d943a92SSnehasish Kumar 2938d943a92SSnehasish Kumar // Set IsBeginSection and IsEndSection according to the assigned section IDs. 2948d943a92SSnehasish Kumar MF.assignBeginEndSections(); 2958d943a92SSnehasish Kumar 2968d943a92SSnehasish Kumar // After reordering basic blocks, we must update basic block branches to 2978d943a92SSnehasish Kumar // insert explicit fallthrough branches when required and optimize branches 2988d943a92SSnehasish Kumar // when possible. 2998d943a92SSnehasish Kumar updateBranches(MF, PreLayoutFallThroughs); 3008d943a92SSnehasish Kumar } 3018d943a92SSnehasish Kumar 3028955950cSRahman Lavaee // If the exception section begins with a landing pad, that landing pad will 3038955950cSRahman Lavaee // assume a zero offset (relative to @LPStart) in the LSDA. However, a value of 3048955950cSRahman Lavaee // zero implies "no landing pad." This function inserts a NOP just before the EH 3058955950cSRahman Lavaee // pad label to ensure a nonzero offset. Returns true if padding is not needed. 3068955950cSRahman Lavaee static bool avoidZeroOffsetLandingPad(MachineFunction &MF) { 3078955950cSRahman Lavaee for (auto &MBB : MF) { 3088955950cSRahman Lavaee if (MBB.isBeginSection() && MBB.isEHPad()) { 3098955950cSRahman Lavaee MachineBasicBlock::iterator MI = MBB.begin(); 3108955950cSRahman Lavaee while (!MI->isEHLabel()) 3118955950cSRahman Lavaee ++MI; 312*5d44c92bSFangrui Song MCInst Nop = MF.getSubtarget().getInstrInfo()->getNop(); 3138955950cSRahman Lavaee BuildMI(MBB, MI, DebugLoc(), 314*5d44c92bSFangrui Song MF.getSubtarget().getInstrInfo()->get(Nop.getOpcode())); 3158955950cSRahman Lavaee return false; 3168955950cSRahman Lavaee } 3178955950cSRahman Lavaee } 3188955950cSRahman Lavaee return true; 3198955950cSRahman Lavaee } 3208955950cSRahman Lavaee 321c32f3998SSriraman Tallam // This checks if the source of this function has drifted since this binary was 322c32f3998SSriraman Tallam // profiled previously. For now, we are piggy backing on what PGO does to 323c32f3998SSriraman Tallam // detect this with instrumented profiles. PGO emits an hash of the IR and 324c32f3998SSriraman Tallam // checks if the hash has changed. Advanced basic block layout is usually done 325c32f3998SSriraman Tallam // on top of PGO optimized binaries and hence this check works well in practice. 326c32f3998SSriraman Tallam static bool hasInstrProfHashMismatch(MachineFunction &MF) { 327c32f3998SSriraman Tallam if (!BBSectionsDetectSourceDrift) 328c32f3998SSriraman Tallam return false; 329c32f3998SSriraman Tallam 330c32f3998SSriraman Tallam const char MetadataName[] = "instr_prof_hash_mismatch"; 331c32f3998SSriraman Tallam auto *Existing = MF.getFunction().getMetadata(LLVMContext::MD_annotation); 332c32f3998SSriraman Tallam if (Existing) { 333c32f3998SSriraman Tallam MDTuple *Tuple = cast<MDTuple>(Existing); 334c32f3998SSriraman Tallam for (auto &N : Tuple->operands()) 335c32f3998SSriraman Tallam if (cast<MDString>(N.get())->getString() == MetadataName) 336c32f3998SSriraman Tallam return true; 337c32f3998SSriraman Tallam } 338c32f3998SSriraman Tallam 339c32f3998SSriraman Tallam return false; 340c32f3998SSriraman Tallam } 341c32f3998SSriraman Tallam 3428d943a92SSnehasish Kumar bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) { 3438d943a92SSnehasish Kumar auto BBSectionsType = MF.getTarget().getBBSectionsType(); 3448d943a92SSnehasish Kumar assert(BBSectionsType != BasicBlockSection::None && 3458d943a92SSnehasish Kumar "BB Sections not enabled!"); 346c32f3998SSriraman Tallam 347c32f3998SSriraman Tallam // Check for source drift. If the source has changed since the profiles 348c32f3998SSriraman Tallam // were obtained, optimizing basic blocks might be sub-optimal. 349c32f3998SSriraman Tallam // This only applies to BasicBlockSection::List as it creates 350c32f3998SSriraman Tallam // clusters of basic blocks using basic block ids. Source drift can 351c32f3998SSriraman Tallam // invalidate these groupings leading to sub-optimal code generation with 352c32f3998SSriraman Tallam // regards to performance. 353c32f3998SSriraman Tallam if (BBSectionsType == BasicBlockSection::List && 354c32f3998SSriraman Tallam hasInstrProfHashMismatch(MF)) 355c32f3998SSriraman Tallam return true; 356c32f3998SSriraman Tallam 3578d943a92SSnehasish Kumar // Renumber blocks before sorting them for basic block sections. This is 3588d943a92SSnehasish Kumar // useful during sorting, basic blocks in the same section will retain the 3598d943a92SSnehasish Kumar // default order. This renumbering should also be done for basic block 3608d943a92SSnehasish Kumar // labels to match the profiles with the correct blocks. 3618d943a92SSnehasish Kumar MF.RenumberBlocks(); 3628d943a92SSnehasish Kumar 3638d943a92SSnehasish Kumar if (BBSectionsType == BasicBlockSection::Labels) { 3648d943a92SSnehasish Kumar MF.setBBSectionsType(BBSectionsType); 3658d943a92SSnehasish Kumar return true; 3668d943a92SSnehasish Kumar } 3678d943a92SSnehasish Kumar 3688d943a92SSnehasish Kumar std::vector<Optional<BBClusterInfo>> FuncBBClusterInfo; 3698d943a92SSnehasish Kumar if (BBSectionsType == BasicBlockSection::List && 3708d943a92SSnehasish Kumar !getBBClusterInfoForFunction(MF, FuncAliasMap, ProgramBBClusterInfo, 3718d943a92SSnehasish Kumar FuncBBClusterInfo)) 3728d943a92SSnehasish Kumar return true; 3738d943a92SSnehasish Kumar MF.setBBSectionsType(BBSectionsType); 37494faadacSSnehasish Kumar assignSections(MF, FuncBBClusterInfo); 37594faadacSSnehasish Kumar 37694faadacSSnehasish Kumar // We make sure that the cluster including the entry basic block precedes all 37794faadacSSnehasish Kumar // other clusters. 37894faadacSSnehasish Kumar auto EntryBBSectionID = MF.front().getSectionID(); 37994faadacSSnehasish Kumar 38094faadacSSnehasish Kumar // Helper function for ordering BB sections as follows: 38194faadacSSnehasish Kumar // * Entry section (section including the entry block). 38294faadacSSnehasish Kumar // * Regular sections (in increasing order of their Number). 38394faadacSSnehasish Kumar // ... 38494faadacSSnehasish Kumar // * Exception section 38594faadacSSnehasish Kumar // * Cold section 38694faadacSSnehasish Kumar auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS, 38794faadacSSnehasish Kumar const MBBSectionID &RHS) { 38894faadacSSnehasish Kumar // We make sure that the section containing the entry block precedes all the 38994faadacSSnehasish Kumar // other sections. 39094faadacSSnehasish Kumar if (LHS == EntryBBSectionID || RHS == EntryBBSectionID) 39194faadacSSnehasish Kumar return LHS == EntryBBSectionID; 39294faadacSSnehasish Kumar return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type; 39394faadacSSnehasish Kumar }; 39494faadacSSnehasish Kumar 39594faadacSSnehasish Kumar // We sort all basic blocks to make sure the basic blocks of every cluster are 39694faadacSSnehasish Kumar // contiguous and ordered accordingly. Furthermore, clusters are ordered in 39794faadacSSnehasish Kumar // increasing order of their section IDs, with the exception and the 39894faadacSSnehasish Kumar // cold section placed at the end of the function. 39994faadacSSnehasish Kumar auto Comparator = [&](const MachineBasicBlock &X, 40094faadacSSnehasish Kumar const MachineBasicBlock &Y) { 40194faadacSSnehasish Kumar auto XSectionID = X.getSectionID(); 40294faadacSSnehasish Kumar auto YSectionID = Y.getSectionID(); 40394faadacSSnehasish Kumar if (XSectionID != YSectionID) 40494faadacSSnehasish Kumar return MBBSectionOrder(XSectionID, YSectionID); 40594faadacSSnehasish Kumar // If the two basic block are in the same section, the order is decided by 40694faadacSSnehasish Kumar // their position within the section. 40794faadacSSnehasish Kumar if (XSectionID.Type == MBBSectionID::SectionType::Default) 40894faadacSSnehasish Kumar return FuncBBClusterInfo[X.getNumber()]->PositionInCluster < 40994faadacSSnehasish Kumar FuncBBClusterInfo[Y.getNumber()]->PositionInCluster; 41094faadacSSnehasish Kumar return X.getNumber() < Y.getNumber(); 41194faadacSSnehasish Kumar }; 41294faadacSSnehasish Kumar 41394faadacSSnehasish Kumar sortBasicBlocksAndUpdateBranches(MF, Comparator); 4148955950cSRahman Lavaee avoidZeroOffsetLandingPad(MF); 4158d943a92SSnehasish Kumar return true; 4168d943a92SSnehasish Kumar } 4178d943a92SSnehasish Kumar 4188d943a92SSnehasish Kumar // Basic Block Sections can be enabled for a subset of machine basic blocks. 4198d943a92SSnehasish Kumar // This is done by passing a file containing names of functions for which basic 4208d943a92SSnehasish Kumar // block sections are desired. Additionally, machine basic block ids of the 4218d943a92SSnehasish Kumar // functions can also be specified for a finer granularity. Moreover, a cluster 4228d943a92SSnehasish Kumar // of basic blocks could be assigned to the same section. 4238d943a92SSnehasish Kumar // A file with basic block sections for all of function main and three blocks 4248d943a92SSnehasish Kumar // for function foo (of which 1 and 2 are placed in a cluster) looks like this: 4258d943a92SSnehasish Kumar // ---------------------------- 4268d943a92SSnehasish Kumar // list.txt: 4278d943a92SSnehasish Kumar // !main 4288d943a92SSnehasish Kumar // !foo 4298d943a92SSnehasish Kumar // !!1 2 4308d943a92SSnehasish Kumar // !!4 4318d943a92SSnehasish Kumar static Error getBBClusterInfo(const MemoryBuffer *MBuf, 4328d943a92SSnehasish Kumar ProgramBBClusterInfoMapTy &ProgramBBClusterInfo, 4338d943a92SSnehasish Kumar StringMap<StringRef> &FuncAliasMap) { 4348d943a92SSnehasish Kumar assert(MBuf); 4358d943a92SSnehasish Kumar line_iterator LineIt(*MBuf, /*SkipBlanks=*/true, /*CommentMarker=*/'#'); 4368d943a92SSnehasish Kumar 4378d943a92SSnehasish Kumar auto invalidProfileError = [&](auto Message) { 4388d943a92SSnehasish Kumar return make_error<StringError>( 4398d943a92SSnehasish Kumar Twine("Invalid profile " + MBuf->getBufferIdentifier() + " at line " + 4408d943a92SSnehasish Kumar Twine(LineIt.line_number()) + ": " + Message), 4418d943a92SSnehasish Kumar inconvertibleErrorCode()); 4428d943a92SSnehasish Kumar }; 4438d943a92SSnehasish Kumar 4448d943a92SSnehasish Kumar auto FI = ProgramBBClusterInfo.end(); 4458d943a92SSnehasish Kumar 4468d943a92SSnehasish Kumar // Current cluster ID corresponding to this function. 4478d943a92SSnehasish Kumar unsigned CurrentCluster = 0; 4488d943a92SSnehasish Kumar // Current position in the current cluster. 4498d943a92SSnehasish Kumar unsigned CurrentPosition = 0; 4508d943a92SSnehasish Kumar 4518d943a92SSnehasish Kumar // Temporary set to ensure every basic block ID appears once in the clusters 4528d943a92SSnehasish Kumar // of a function. 4538d943a92SSnehasish Kumar SmallSet<unsigned, 4> FuncBBIDs; 4548d943a92SSnehasish Kumar 4558d943a92SSnehasish Kumar for (; !LineIt.is_at_eof(); ++LineIt) { 4568d943a92SSnehasish Kumar StringRef S(*LineIt); 4578d943a92SSnehasish Kumar if (S[0] == '@') 4588d943a92SSnehasish Kumar continue; 4598d943a92SSnehasish Kumar // Check for the leading "!" 4608d943a92SSnehasish Kumar if (!S.consume_front("!") || S.empty()) 4618d943a92SSnehasish Kumar break; 4628d943a92SSnehasish Kumar // Check for second "!" which indicates a cluster of basic blocks. 4638d943a92SSnehasish Kumar if (S.consume_front("!")) { 4648d943a92SSnehasish Kumar if (FI == ProgramBBClusterInfo.end()) 4658d943a92SSnehasish Kumar return invalidProfileError( 4668d943a92SSnehasish Kumar "Cluster list does not follow a function name specifier."); 4678d943a92SSnehasish Kumar SmallVector<StringRef, 4> BBIndexes; 4688d943a92SSnehasish Kumar S.split(BBIndexes, ' '); 4698d943a92SSnehasish Kumar // Reset current cluster position. 4708d943a92SSnehasish Kumar CurrentPosition = 0; 4718d943a92SSnehasish Kumar for (auto BBIndexStr : BBIndexes) { 4728d943a92SSnehasish Kumar unsigned long long BBIndex; 4738d943a92SSnehasish Kumar if (getAsUnsignedInteger(BBIndexStr, 10, BBIndex)) 4748d943a92SSnehasish Kumar return invalidProfileError(Twine("Unsigned integer expected: '") + 4758d943a92SSnehasish Kumar BBIndexStr + "'."); 4768d943a92SSnehasish Kumar if (!FuncBBIDs.insert(BBIndex).second) 4778d943a92SSnehasish Kumar return invalidProfileError(Twine("Duplicate basic block id found '") + 4788d943a92SSnehasish Kumar BBIndexStr + "'."); 4798d943a92SSnehasish Kumar if (!BBIndex && CurrentPosition) 4808d943a92SSnehasish Kumar return invalidProfileError("Entry BB (0) does not begin a cluster."); 4818d943a92SSnehasish Kumar 4828d943a92SSnehasish Kumar FI->second.emplace_back(BBClusterInfo{ 4838d943a92SSnehasish Kumar ((unsigned)BBIndex), CurrentCluster, CurrentPosition++}); 4848d943a92SSnehasish Kumar } 4858d943a92SSnehasish Kumar CurrentCluster++; 4868d943a92SSnehasish Kumar } else { // This is a function name specifier. 4878d943a92SSnehasish Kumar // Function aliases are separated using '/'. We use the first function 4888d943a92SSnehasish Kumar // name for the cluster info mapping and delegate all other aliases to 4898d943a92SSnehasish Kumar // this one. 4908d943a92SSnehasish Kumar SmallVector<StringRef, 4> Aliases; 4918d943a92SSnehasish Kumar S.split(Aliases, '/'); 4928d943a92SSnehasish Kumar for (size_t i = 1; i < Aliases.size(); ++i) 4938d943a92SSnehasish Kumar FuncAliasMap.try_emplace(Aliases[i], Aliases.front()); 4948d943a92SSnehasish Kumar 4958d943a92SSnehasish Kumar // Prepare for parsing clusters of this function name. 4968d943a92SSnehasish Kumar // Start a new cluster map for this function name. 4978d943a92SSnehasish Kumar FI = ProgramBBClusterInfo.try_emplace(Aliases.front()).first; 4988d943a92SSnehasish Kumar CurrentCluster = 0; 4998d943a92SSnehasish Kumar FuncBBIDs.clear(); 5008d943a92SSnehasish Kumar } 5018d943a92SSnehasish Kumar } 5028d943a92SSnehasish Kumar return Error::success(); 5038d943a92SSnehasish Kumar } 5048d943a92SSnehasish Kumar 5058d943a92SSnehasish Kumar bool BasicBlockSections::doInitialization(Module &M) { 5068d943a92SSnehasish Kumar if (!MBuf) 5078d943a92SSnehasish Kumar return false; 5088d943a92SSnehasish Kumar if (auto Err = getBBClusterInfo(MBuf, ProgramBBClusterInfo, FuncAliasMap)) 5098d943a92SSnehasish Kumar report_fatal_error(std::move(Err)); 5108d943a92SSnehasish Kumar return false; 5118d943a92SSnehasish Kumar } 5128d943a92SSnehasish Kumar 5138d943a92SSnehasish Kumar void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const { 5148d943a92SSnehasish Kumar AU.setPreservesAll(); 5158d943a92SSnehasish Kumar MachineFunctionPass::getAnalysisUsage(AU); 5168d943a92SSnehasish Kumar } 5178d943a92SSnehasish Kumar 5188d943a92SSnehasish Kumar MachineFunctionPass * 5198d943a92SSnehasish Kumar llvm::createBasicBlockSectionsPass(const MemoryBuffer *Buf) { 5208d943a92SSnehasish Kumar return new BasicBlockSections(Buf); 5218d943a92SSnehasish Kumar } 522