Path: blob/main/contrib/llvm-project/llvm/lib/CodeGen/BasicBlockSections.cpp
35232 views
//===-- BasicBlockSections.cpp ---=========--------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// BasicBlockSections implementation.9//10// The purpose of this pass is to assign sections to basic blocks when11// -fbasic-block-sections= option is used. Further, with profile information12// only the subset of basic blocks with profiles are placed in separate sections13// and the rest are grouped in a cold section. The exception handling blocks are14// treated specially to ensure they are all in one seciton.15//16// Basic Block Sections17// ====================18//19// With option, -fbasic-block-sections=list, every function may be split into20// clusters of basic blocks. Every cluster will be emitted into a separate21// section with its basic blocks sequenced in the given order. To get the22// optimized performance, the clusters must form an optimal BB layout for the23// function. We insert a symbol at the beginning of every cluster's section to24// allow the linker to reorder the sections in any arbitrary sequence. A global25// order of these sections would encapsulate the function layout.26// For example, consider the following clusters for a function foo (consisting27// of 6 basic blocks 0, 1, ..., 5).28//29// 0 230// 1 3 531//32// * Basic blocks 0 and 2 are placed in one section with symbol `foo`33// referencing the beginning of this section.34// * Basic blocks 1, 3, 5 are placed in a separate section. A new symbol35// `foo.__part.1` will reference the beginning of this section.36// * Basic block 4 (note that it is not referenced in the list) is placed in37// one section, and a new symbol `foo.cold` will point to it.38//39// There are a couple of challenges to be addressed:40//41// 1. The last basic block of every cluster should not have any implicit42// fallthrough to its next basic block, as it can be reordered by the linker.43// The compiler should make these fallthroughs explicit by adding44// unconditional jumps..45//46// 2. All inter-cluster branch targets would now need to be resolved by the47// linker as they cannot be calculated during compile time. This is done48// using static relocations. Further, the compiler tries to use short branch49// instructions on some ISAs for small branch offsets. This is not possible50// for inter-cluster branches as the offset is not determined at compile51// time, and therefore, long branch instructions have to be used for those.52//53// 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission54// needs special handling with basic block sections. DebugInfo needs to be55// emitted with more relocations as basic block sections can break a56// function into potentially several disjoint pieces, and CFI needs to be57// emitted per cluster. This also bloats the object file and binary sizes.58//59// Basic Block Address Map60// ==================61//62// With -fbasic-block-address-map, we emit the offsets of BB addresses of63// every function into the .llvm_bb_addr_map section. Along with the function64// symbols, this allows for mapping of virtual addresses in PMU profiles back to65// the corresponding basic blocks. This logic is implemented in AsmPrinter. This66// pass only assigns the BBSectionType of every function to ``labels``.67//68//===----------------------------------------------------------------------===//6970#include "llvm/ADT/SmallVector.h"71#include "llvm/ADT/StringRef.h"72#include "llvm/CodeGen/BasicBlockSectionUtils.h"73#include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"74#include "llvm/CodeGen/MachineFunction.h"75#include "llvm/CodeGen/MachineFunctionPass.h"76#include "llvm/CodeGen/Passes.h"77#include "llvm/CodeGen/TargetInstrInfo.h"78#include "llvm/InitializePasses.h"79#include "llvm/Target/TargetMachine.h"80#include <optional>8182using namespace llvm;8384// Placing the cold clusters in a separate section mitigates against poor85// profiles and allows optimizations such as hugepage mapping to be applied at a86// section granularity. Defaults to ".text.split." which is recognized by lld87// via the `-z keep-text-section-prefix` flag.88cl::opt<std::string> llvm::BBSectionsColdTextPrefix(89"bbsections-cold-text-prefix",90cl::desc("The text prefix to use for cold basic block clusters"),91cl::init(".text.split."), cl::Hidden);9293static cl::opt<bool> BBSectionsDetectSourceDrift(94"bbsections-detect-source-drift",95cl::desc("This checks if there is a fdo instr. profile hash "96"mismatch for this function"),97cl::init(true), cl::Hidden);9899namespace {100101class BasicBlockSections : public MachineFunctionPass {102public:103static char ID;104105BasicBlockSectionsProfileReaderWrapperPass *BBSectionsProfileReader = nullptr;106107BasicBlockSections() : MachineFunctionPass(ID) {108initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());109}110111StringRef getPassName() const override {112return "Basic Block Sections Analysis";113}114115void getAnalysisUsage(AnalysisUsage &AU) const override;116117/// Identify basic blocks that need separate sections and prepare to emit them118/// accordingly.119bool runOnMachineFunction(MachineFunction &MF) override;120121private:122bool handleBBSections(MachineFunction &MF);123bool handleBBAddrMap(MachineFunction &MF);124};125126} // end anonymous namespace127128char BasicBlockSections::ID = 0;129INITIALIZE_PASS_BEGIN(130BasicBlockSections, "bbsections-prepare",131"Prepares for basic block sections, by splitting functions "132"into clusters of basic blocks.",133false, false)134INITIALIZE_PASS_DEPENDENCY(BasicBlockSectionsProfileReaderWrapperPass)135INITIALIZE_PASS_END(BasicBlockSections, "bbsections-prepare",136"Prepares for basic block sections, by splitting functions "137"into clusters of basic blocks.",138false, false)139140// This function updates and optimizes the branching instructions of every basic141// block in a given function to account for changes in the layout.142static void143updateBranches(MachineFunction &MF,144const SmallVector<MachineBasicBlock *> &PreLayoutFallThroughs) {145const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();146SmallVector<MachineOperand, 4> Cond;147for (auto &MBB : MF) {148auto NextMBBI = std::next(MBB.getIterator());149auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];150// If this block had a fallthrough before we need an explicit unconditional151// branch to that block if either152// 1- the block ends a section, which means its next block may be153// reorderd by the linker, or154// 2- the fallthrough block is not adjacent to the block in the new155// order.156if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))157TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());158159// We do not optimize branches for machine basic blocks ending sections, as160// their adjacent block might be reordered by the linker.161if (MBB.isEndSection())162continue;163164// It might be possible to optimize branches by flipping the branch165// condition.166Cond.clear();167MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.168if (TII->analyzeBranch(MBB, TBB, FBB, Cond))169continue;170MBB.updateTerminator(FTMBB);171}172}173174// This function sorts basic blocks according to the cluster's information.175// All explicitly specified clusters of basic blocks will be ordered176// accordingly. All non-specified BBs go into a separate "Cold" section.177// Additionally, if exception handling landing pads end up in more than one178// clusters, they are moved into a single "Exception" section. Eventually,179// clusters are ordered in increasing order of their IDs, with the "Exception"180// and "Cold" succeeding all other clusters.181// FuncClusterInfo represents the cluster information for basic blocks. It182// maps from BBID of basic blocks to their cluster information. If this is183// empty, it means unique sections for all basic blocks in the function.184static void185assignSections(MachineFunction &MF,186const DenseMap<UniqueBBID, BBClusterInfo> &FuncClusterInfo) {187assert(MF.hasBBSections() && "BB Sections is not set for function.");188// This variable stores the section ID of the cluster containing eh_pads (if189// all eh_pads are one cluster). If more than one cluster contain eh_pads, we190// set it equal to ExceptionSectionID.191std::optional<MBBSectionID> EHPadsSectionID;192193for (auto &MBB : MF) {194// With the 'all' option, every basic block is placed in a unique section.195// With the 'list' option, every basic block is placed in a section196// associated with its cluster, unless we want individual unique sections197// for every basic block in this function (if FuncClusterInfo is empty).198if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All ||199FuncClusterInfo.empty()) {200// If unique sections are desired for all basic blocks of the function, we201// set every basic block's section ID equal to its original position in202// the layout (which is equal to its number). This ensures that basic203// blocks are ordered canonically.204MBB.setSectionID(MBB.getNumber());205} else {206auto I = FuncClusterInfo.find(*MBB.getBBID());207if (I != FuncClusterInfo.end()) {208MBB.setSectionID(I->second.ClusterID);209} else {210const TargetInstrInfo &TII =211*MBB.getParent()->getSubtarget().getInstrInfo();212213if (TII.isMBBSafeToSplitToCold(MBB)) {214// BB goes into the special cold section if it is not specified in the215// cluster info map.216MBB.setSectionID(MBBSectionID::ColdSectionID);217}218}219}220221if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&222EHPadsSectionID != MBBSectionID::ExceptionSectionID) {223// If we already have one cluster containing eh_pads, this must be updated224// to ExceptionSectionID. Otherwise, we set it equal to the current225// section ID.226EHPadsSectionID = EHPadsSectionID ? MBBSectionID::ExceptionSectionID227: MBB.getSectionID();228}229}230231// If EHPads are in more than one section, this places all of them in the232// special exception section.233if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)234for (auto &MBB : MF)235if (MBB.isEHPad())236MBB.setSectionID(*EHPadsSectionID);237}238239void llvm::sortBasicBlocksAndUpdateBranches(240MachineFunction &MF, MachineBasicBlockComparator MBBCmp) {241[[maybe_unused]] const MachineBasicBlock *EntryBlock = &MF.front();242SmallVector<MachineBasicBlock *> PreLayoutFallThroughs(MF.getNumBlockIDs());243for (auto &MBB : MF)244PreLayoutFallThroughs[MBB.getNumber()] =245MBB.getFallThrough(/*JumpToFallThrough=*/false);246247MF.sort(MBBCmp);248assert(&MF.front() == EntryBlock &&249"Entry block should not be displaced by basic block sections");250251// Set IsBeginSection and IsEndSection according to the assigned section IDs.252MF.assignBeginEndSections();253254// After reordering basic blocks, we must update basic block branches to255// insert explicit fallthrough branches when required and optimize branches256// when possible.257updateBranches(MF, PreLayoutFallThroughs);258}259260// If the exception section begins with a landing pad, that landing pad will261// assume a zero offset (relative to @LPStart) in the LSDA. However, a value of262// zero implies "no landing pad." This function inserts a NOP just before the EH263// pad label to ensure a nonzero offset.264void llvm::avoidZeroOffsetLandingPad(MachineFunction &MF) {265for (auto &MBB : MF) {266if (MBB.isBeginSection() && MBB.isEHPad()) {267MachineBasicBlock::iterator MI = MBB.begin();268while (!MI->isEHLabel())269++MI;270MF.getSubtarget().getInstrInfo()->insertNoop(MBB, MI);271}272}273}274275bool llvm::hasInstrProfHashMismatch(MachineFunction &MF) {276if (!BBSectionsDetectSourceDrift)277return false;278279const char MetadataName[] = "instr_prof_hash_mismatch";280auto *Existing = MF.getFunction().getMetadata(LLVMContext::MD_annotation);281if (Existing) {282MDTuple *Tuple = cast<MDTuple>(Existing);283for (const auto &N : Tuple->operands())284if (N.equalsStr(MetadataName))285return true;286}287288return false;289}290291// Identify, arrange, and modify basic blocks which need separate sections292// according to the specification provided by the -fbasic-block-sections flag.293bool BasicBlockSections::handleBBSections(MachineFunction &MF) {294auto BBSectionsType = MF.getTarget().getBBSectionsType();295if (BBSectionsType == BasicBlockSection::None)296return false;297298// Check for source drift. If the source has changed since the profiles299// were obtained, optimizing basic blocks might be sub-optimal.300// This only applies to BasicBlockSection::List as it creates301// clusters of basic blocks using basic block ids. Source drift can302// invalidate these groupings leading to sub-optimal code generation with303// regards to performance.304if (BBSectionsType == BasicBlockSection::List &&305hasInstrProfHashMismatch(MF))306return false;307// Renumber blocks before sorting them. This is useful for accessing the308// original layout positions and finding the original fallthroughs.309MF.RenumberBlocks();310311if (BBSectionsType == BasicBlockSection::Labels) {312MF.setBBSectionsType(BBSectionsType);313return true;314}315316DenseMap<UniqueBBID, BBClusterInfo> FuncClusterInfo;317if (BBSectionsType == BasicBlockSection::List) {318auto [HasProfile, ClusterInfo] =319getAnalysis<BasicBlockSectionsProfileReaderWrapperPass>()320.getClusterInfoForFunction(MF.getName());321if (!HasProfile)322return false;323for (auto &BBClusterInfo : ClusterInfo) {324FuncClusterInfo.try_emplace(BBClusterInfo.BBID, BBClusterInfo);325}326}327328MF.setBBSectionsType(BBSectionsType);329assignSections(MF, FuncClusterInfo);330331const MachineBasicBlock &EntryBB = MF.front();332auto EntryBBSectionID = EntryBB.getSectionID();333334// Helper function for ordering BB sections as follows:335// * Entry section (section including the entry block).336// * Regular sections (in increasing order of their Number).337// ...338// * Exception section339// * Cold section340auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,341const MBBSectionID &RHS) {342// We make sure that the section containing the entry block precedes all the343// other sections.344if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)345return LHS == EntryBBSectionID;346return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;347};348349// We sort all basic blocks to make sure the basic blocks of every cluster are350// contiguous and ordered accordingly. Furthermore, clusters are ordered in351// increasing order of their section IDs, with the exception and the352// cold section placed at the end of the function.353// Also, we force the entry block of the function to be placed at the354// beginning of the function, regardless of the requested order.355auto Comparator = [&](const MachineBasicBlock &X,356const MachineBasicBlock &Y) {357auto XSectionID = X.getSectionID();358auto YSectionID = Y.getSectionID();359if (XSectionID != YSectionID)360return MBBSectionOrder(XSectionID, YSectionID);361// Make sure that the entry block is placed at the beginning.362if (&X == &EntryBB || &Y == &EntryBB)363return &X == &EntryBB;364// If the two basic block are in the same section, the order is decided by365// their position within the section.366if (XSectionID.Type == MBBSectionID::SectionType::Default)367return FuncClusterInfo.lookup(*X.getBBID()).PositionInCluster <368FuncClusterInfo.lookup(*Y.getBBID()).PositionInCluster;369return X.getNumber() < Y.getNumber();370};371372sortBasicBlocksAndUpdateBranches(MF, Comparator);373avoidZeroOffsetLandingPad(MF);374return true;375}376377// When the BB address map needs to be generated, this renumbers basic blocks to378// make them appear in increasing order of their IDs in the function. This379// avoids the need to store basic block IDs in the BB address map section, since380// they can be determined implicitly.381bool BasicBlockSections::handleBBAddrMap(MachineFunction &MF) {382if (MF.getTarget().getBBSectionsType() == BasicBlockSection::Labels)383return false;384if (!MF.getTarget().Options.BBAddrMap)385return false;386MF.RenumberBlocks();387return true;388}389390bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {391// First handle the basic block sections.392auto R1 = handleBBSections(MF);393// Handle basic block address map after basic block sections are finalized.394auto R2 = handleBBAddrMap(MF);395return R1 || R2;396}397398void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {399AU.setPreservesAll();400AU.addRequired<BasicBlockSectionsProfileReaderWrapperPass>();401MachineFunctionPass::getAnalysisUsage(AU);402}403404MachineFunctionPass *llvm::createBasicBlockSectionsPass() {405return new BasicBlockSections();406}407408409