1af732203SDimitry Andric //===-- BasicBlockSections.cpp ---=========--------------------------------===//
2af732203SDimitry Andric //
3af732203SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4af732203SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5af732203SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6af732203SDimitry Andric //
7af732203SDimitry Andric //===----------------------------------------------------------------------===//
8af732203SDimitry Andric //
9af732203SDimitry Andric // BasicBlockSections implementation.
10af732203SDimitry Andric //
11af732203SDimitry Andric // The purpose of this pass is to assign sections to basic blocks when
12af732203SDimitry Andric // -fbasic-block-sections= option is used. Further, with profile information
13af732203SDimitry Andric // only the subset of basic blocks with profiles are placed in separate sections
14af732203SDimitry Andric // and the rest are grouped in a cold section. The exception handling blocks are
15af732203SDimitry Andric // treated specially to ensure they are all in one seciton.
16af732203SDimitry Andric //
17af732203SDimitry Andric // Basic Block Sections
18af732203SDimitry Andric // ====================
19af732203SDimitry Andric //
20af732203SDimitry Andric // With option, -fbasic-block-sections=list, every function may be split into
21af732203SDimitry Andric // clusters of basic blocks. Every cluster will be emitted into a separate
22af732203SDimitry Andric // section with its basic blocks sequenced in the given order. To get the
23af732203SDimitry Andric // optimized performance, the clusters must form an optimal BB layout for the
24af732203SDimitry Andric // function. Every cluster's section is labeled with a symbol to allow the
25af732203SDimitry Andric // linker to reorder the sections in any arbitrary sequence. A global order of
26af732203SDimitry Andric // these sections would encapsulate the function layout.
27af732203SDimitry Andric //
28af732203SDimitry Andric // There are a couple of challenges to be addressed:
29af732203SDimitry Andric //
30af732203SDimitry Andric // 1. The last basic block of every cluster should not have any implicit
31af732203SDimitry Andric //    fallthrough to its next basic block, as it can be reordered by the linker.
32af732203SDimitry Andric //    The compiler should make these fallthroughs explicit by adding
33af732203SDimitry Andric //    unconditional jumps..
34af732203SDimitry Andric //
35af732203SDimitry Andric // 2. All inter-cluster branch targets would now need to be resolved by the
36af732203SDimitry Andric //    linker as they cannot be calculated during compile time. This is done
37af732203SDimitry Andric //    using static relocations. Further, the compiler tries to use short branch
38af732203SDimitry Andric //    instructions on some ISAs for small branch offsets. This is not possible
39af732203SDimitry Andric //    for inter-cluster branches as the offset is not determined at compile
40af732203SDimitry Andric //    time, and therefore, long branch instructions have to be used for those.
41af732203SDimitry Andric //
42af732203SDimitry Andric // 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission
43af732203SDimitry Andric //    needs special handling with basic block sections. DebugInfo needs to be
44af732203SDimitry Andric //    emitted with more relocations as basic block sections can break a
45af732203SDimitry Andric //    function into potentially several disjoint pieces, and CFI needs to be
46af732203SDimitry Andric //    emitted per cluster. This also bloats the object file and binary sizes.
47af732203SDimitry Andric //
48af732203SDimitry Andric // Basic Block Labels
49af732203SDimitry Andric // ==================
50af732203SDimitry Andric //
51af732203SDimitry Andric // With -fbasic-block-sections=labels, we emit the offsets of BB addresses of
52af732203SDimitry Andric // every function into the .llvm_bb_addr_map section. Along with the function
53af732203SDimitry Andric // symbols, this allows for mapping of virtual addresses in PMU profiles back to
54af732203SDimitry Andric // the corresponding basic blocks. This logic is implemented in AsmPrinter. This
55af732203SDimitry Andric // pass only assigns the BBSectionType of every function to ``labels``.
56af732203SDimitry Andric //
57af732203SDimitry Andric //===----------------------------------------------------------------------===//
58af732203SDimitry Andric 
59af732203SDimitry Andric #include "llvm/ADT/Optional.h"
60af732203SDimitry Andric #include "llvm/ADT/SmallSet.h"
61af732203SDimitry Andric #include "llvm/ADT/SmallVector.h"
62af732203SDimitry Andric #include "llvm/ADT/StringMap.h"
63af732203SDimitry Andric #include "llvm/ADT/StringRef.h"
64af732203SDimitry Andric #include "llvm/CodeGen/BasicBlockSectionUtils.h"
65af732203SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
66af732203SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
67af732203SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
68af732203SDimitry Andric #include "llvm/CodeGen/Passes.h"
69af732203SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
70af732203SDimitry Andric #include "llvm/InitializePasses.h"
71af732203SDimitry Andric #include "llvm/Support/Error.h"
72af732203SDimitry Andric #include "llvm/Support/LineIterator.h"
73af732203SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
74af732203SDimitry Andric #include "llvm/Target/TargetMachine.h"
75af732203SDimitry Andric 
76af732203SDimitry Andric using llvm::SmallSet;
77af732203SDimitry Andric using llvm::SmallVector;
78af732203SDimitry Andric using llvm::StringMap;
79af732203SDimitry Andric using llvm::StringRef;
80af732203SDimitry Andric using namespace llvm;
81af732203SDimitry Andric 
82af732203SDimitry Andric // Placing the cold clusters in a separate section mitigates against poor
83af732203SDimitry Andric // profiles and allows optimizations such as hugepage mapping to be applied at a
84af732203SDimitry Andric // section granularity. Defaults to ".text.split." which is recognized by lld
85af732203SDimitry Andric // via the `-z keep-text-section-prefix` flag.
86af732203SDimitry Andric cl::opt<std::string> llvm::BBSectionsColdTextPrefix(
87af732203SDimitry Andric     "bbsections-cold-text-prefix",
88af732203SDimitry Andric     cl::desc("The text prefix to use for cold basic block clusters"),
89af732203SDimitry Andric     cl::init(".text.split."), cl::Hidden);
90af732203SDimitry Andric 
91*5f7ddb14SDimitry Andric cl::opt<bool> BBSectionsDetectSourceDrift(
92*5f7ddb14SDimitry Andric     "bbsections-detect-source-drift",
93*5f7ddb14SDimitry Andric     cl::desc("This checks if there is a fdo instr. profile hash "
94*5f7ddb14SDimitry Andric              "mismatch for this function"),
95*5f7ddb14SDimitry Andric     cl::init(true), cl::Hidden);
96*5f7ddb14SDimitry Andric 
97af732203SDimitry Andric namespace {
98af732203SDimitry Andric 
99af732203SDimitry Andric // This struct represents the cluster information for a machine basic block.
100af732203SDimitry Andric struct BBClusterInfo {
101af732203SDimitry Andric   // MachineBasicBlock ID.
102af732203SDimitry Andric   unsigned MBBNumber;
103af732203SDimitry Andric   // Cluster ID this basic block belongs to.
104af732203SDimitry Andric   unsigned ClusterID;
105af732203SDimitry Andric   // Position of basic block within the cluster.
106af732203SDimitry Andric   unsigned PositionInCluster;
107af732203SDimitry Andric };
108af732203SDimitry Andric 
109af732203SDimitry Andric using ProgramBBClusterInfoMapTy = StringMap<SmallVector<BBClusterInfo, 4>>;
110af732203SDimitry Andric 
111af732203SDimitry Andric class BasicBlockSections : public MachineFunctionPass {
112af732203SDimitry Andric public:
113af732203SDimitry Andric   static char ID;
114af732203SDimitry Andric 
115af732203SDimitry Andric   // This contains the basic-block-sections profile.
116af732203SDimitry Andric   const MemoryBuffer *MBuf = nullptr;
117af732203SDimitry Andric 
118af732203SDimitry Andric   // This encapsulates the BB cluster information for the whole program.
119af732203SDimitry Andric   //
120af732203SDimitry Andric   // For every function name, it contains the cluster information for (all or
121af732203SDimitry Andric   // some of) its basic blocks. The cluster information for every basic block
122af732203SDimitry Andric   // includes its cluster ID along with the position of the basic block in that
123af732203SDimitry Andric   // cluster.
124af732203SDimitry Andric   ProgramBBClusterInfoMapTy ProgramBBClusterInfo;
125af732203SDimitry Andric 
126af732203SDimitry Andric   // Some functions have alias names. We use this map to find the main alias
127af732203SDimitry Andric   // name for which we have mapping in ProgramBBClusterInfo.
128af732203SDimitry Andric   StringMap<StringRef> FuncAliasMap;
129af732203SDimitry Andric 
BasicBlockSections(const MemoryBuffer * Buf)130af732203SDimitry Andric   BasicBlockSections(const MemoryBuffer *Buf)
131af732203SDimitry Andric       : MachineFunctionPass(ID), MBuf(Buf) {
132af732203SDimitry Andric     initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
133af732203SDimitry Andric   };
134af732203SDimitry Andric 
BasicBlockSections()135af732203SDimitry Andric   BasicBlockSections() : MachineFunctionPass(ID) {
136af732203SDimitry Andric     initializeBasicBlockSectionsPass(*PassRegistry::getPassRegistry());
137af732203SDimitry Andric   }
138af732203SDimitry Andric 
getPassName() const139af732203SDimitry Andric   StringRef getPassName() const override {
140af732203SDimitry Andric     return "Basic Block Sections Analysis";
141af732203SDimitry Andric   }
142af732203SDimitry Andric 
143af732203SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override;
144af732203SDimitry Andric 
145af732203SDimitry Andric   /// Read profiles of basic blocks if available here.
146af732203SDimitry Andric   bool doInitialization(Module &M) override;
147af732203SDimitry Andric 
148af732203SDimitry Andric   /// Identify basic blocks that need separate sections and prepare to emit them
149af732203SDimitry Andric   /// accordingly.
150af732203SDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
151af732203SDimitry Andric };
152af732203SDimitry Andric 
153af732203SDimitry Andric } // end anonymous namespace
154af732203SDimitry Andric 
155af732203SDimitry Andric char BasicBlockSections::ID = 0;
156af732203SDimitry Andric INITIALIZE_PASS(BasicBlockSections, "bbsections-prepare",
157af732203SDimitry Andric                 "Prepares for basic block sections, by splitting functions "
158af732203SDimitry Andric                 "into clusters of basic blocks.",
159af732203SDimitry Andric                 false, false)
160af732203SDimitry Andric 
161af732203SDimitry Andric // This function updates and optimizes the branching instructions of every basic
162af732203SDimitry Andric // block in a given function to account for changes in the layout.
updateBranches(MachineFunction & MF,const SmallVector<MachineBasicBlock *,4> & PreLayoutFallThroughs)163af732203SDimitry Andric static void updateBranches(
164af732203SDimitry Andric     MachineFunction &MF,
165af732203SDimitry Andric     const SmallVector<MachineBasicBlock *, 4> &PreLayoutFallThroughs) {
166af732203SDimitry Andric   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
167af732203SDimitry Andric   SmallVector<MachineOperand, 4> Cond;
168af732203SDimitry Andric   for (auto &MBB : MF) {
169af732203SDimitry Andric     auto NextMBBI = std::next(MBB.getIterator());
170af732203SDimitry Andric     auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];
171af732203SDimitry Andric     // If this block had a fallthrough before we need an explicit unconditional
172af732203SDimitry Andric     // branch to that block if either
173af732203SDimitry Andric     //     1- the block ends a section, which means its next block may be
174af732203SDimitry Andric     //        reorderd by the linker, or
175af732203SDimitry Andric     //     2- the fallthrough block is not adjacent to the block in the new
176af732203SDimitry Andric     //        order.
177af732203SDimitry Andric     if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))
178af732203SDimitry Andric       TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
179af732203SDimitry Andric 
180af732203SDimitry Andric     // We do not optimize branches for machine basic blocks ending sections, as
181af732203SDimitry Andric     // their adjacent block might be reordered by the linker.
182af732203SDimitry Andric     if (MBB.isEndSection())
183af732203SDimitry Andric       continue;
184af732203SDimitry Andric 
185af732203SDimitry Andric     // It might be possible to optimize branches by flipping the branch
186af732203SDimitry Andric     // condition.
187af732203SDimitry Andric     Cond.clear();
188af732203SDimitry Andric     MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
189af732203SDimitry Andric     if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
190af732203SDimitry Andric       continue;
191af732203SDimitry Andric     MBB.updateTerminator(FTMBB);
192af732203SDimitry Andric   }
193af732203SDimitry Andric }
194af732203SDimitry Andric 
195af732203SDimitry Andric // This function provides the BBCluster information associated with a function.
196af732203SDimitry Andric // Returns true if a valid association exists and false otherwise.
getBBClusterInfoForFunction(const MachineFunction & MF,const StringMap<StringRef> FuncAliasMap,const ProgramBBClusterInfoMapTy & ProgramBBClusterInfo,std::vector<Optional<BBClusterInfo>> & V)197af732203SDimitry Andric static bool getBBClusterInfoForFunction(
198af732203SDimitry Andric     const MachineFunction &MF, const StringMap<StringRef> FuncAliasMap,
199af732203SDimitry Andric     const ProgramBBClusterInfoMapTy &ProgramBBClusterInfo,
200af732203SDimitry Andric     std::vector<Optional<BBClusterInfo>> &V) {
201af732203SDimitry Andric   // Get the main alias name for the function.
202af732203SDimitry Andric   auto FuncName = MF.getName();
203af732203SDimitry Andric   auto R = FuncAliasMap.find(FuncName);
204af732203SDimitry Andric   StringRef AliasName = R == FuncAliasMap.end() ? FuncName : R->second;
205af732203SDimitry Andric 
206af732203SDimitry Andric   // Find the assoicated cluster information.
207af732203SDimitry Andric   auto P = ProgramBBClusterInfo.find(AliasName);
208af732203SDimitry Andric   if (P == ProgramBBClusterInfo.end())
209af732203SDimitry Andric     return false;
210af732203SDimitry Andric 
211af732203SDimitry Andric   if (P->second.empty()) {
212af732203SDimitry Andric     // This indicates that sections are desired for all basic blocks of this
213af732203SDimitry Andric     // function. We clear the BBClusterInfo vector to denote this.
214af732203SDimitry Andric     V.clear();
215af732203SDimitry Andric     return true;
216af732203SDimitry Andric   }
217af732203SDimitry Andric 
218af732203SDimitry Andric   V.resize(MF.getNumBlockIDs());
219af732203SDimitry Andric   for (auto bbClusterInfo : P->second) {
220af732203SDimitry Andric     // Bail out if the cluster information contains invalid MBB numbers.
221af732203SDimitry Andric     if (bbClusterInfo.MBBNumber >= MF.getNumBlockIDs())
222af732203SDimitry Andric       return false;
223af732203SDimitry Andric     V[bbClusterInfo.MBBNumber] = bbClusterInfo;
224af732203SDimitry Andric   }
225af732203SDimitry Andric   return true;
226af732203SDimitry Andric }
227af732203SDimitry Andric 
228af732203SDimitry Andric // This function sorts basic blocks according to the cluster's information.
229af732203SDimitry Andric // All explicitly specified clusters of basic blocks will be ordered
230af732203SDimitry Andric // accordingly. All non-specified BBs go into a separate "Cold" section.
231af732203SDimitry Andric // Additionally, if exception handling landing pads end up in more than one
232af732203SDimitry Andric // clusters, they are moved into a single "Exception" section. Eventually,
233af732203SDimitry Andric // clusters are ordered in increasing order of their IDs, with the "Exception"
234af732203SDimitry Andric // and "Cold" succeeding all other clusters.
235af732203SDimitry Andric // FuncBBClusterInfo represent the cluster information for basic blocks. If this
236af732203SDimitry Andric // is empty, it means unique sections for all basic blocks in the function.
237af732203SDimitry Andric static void
assignSections(MachineFunction & MF,const std::vector<Optional<BBClusterInfo>> & FuncBBClusterInfo)238af732203SDimitry Andric assignSections(MachineFunction &MF,
239af732203SDimitry Andric                const std::vector<Optional<BBClusterInfo>> &FuncBBClusterInfo) {
240af732203SDimitry Andric   assert(MF.hasBBSections() && "BB Sections is not set for function.");
241af732203SDimitry Andric   // This variable stores the section ID of the cluster containing eh_pads (if
242af732203SDimitry Andric   // all eh_pads are one cluster). If more than one cluster contain eh_pads, we
243af732203SDimitry Andric   // set it equal to ExceptionSectionID.
244af732203SDimitry Andric   Optional<MBBSectionID> EHPadsSectionID;
245af732203SDimitry Andric 
246af732203SDimitry Andric   for (auto &MBB : MF) {
247af732203SDimitry Andric     // With the 'all' option, every basic block is placed in a unique section.
248af732203SDimitry Andric     // With the 'list' option, every basic block is placed in a section
249af732203SDimitry Andric     // associated with its cluster, unless we want individual unique sections
250af732203SDimitry Andric     // for every basic block in this function (if FuncBBClusterInfo is empty).
251af732203SDimitry Andric     if (MF.getTarget().getBBSectionsType() == llvm::BasicBlockSection::All ||
252af732203SDimitry Andric         FuncBBClusterInfo.empty()) {
253af732203SDimitry Andric       // If unique sections are desired for all basic blocks of the function, we
254af732203SDimitry Andric       // set every basic block's section ID equal to its number (basic block
255af732203SDimitry Andric       // id). This further ensures that basic blocks are ordered canonically.
256af732203SDimitry Andric       MBB.setSectionID({static_cast<unsigned int>(MBB.getNumber())});
257af732203SDimitry Andric     } else if (FuncBBClusterInfo[MBB.getNumber()].hasValue())
258af732203SDimitry Andric       MBB.setSectionID(FuncBBClusterInfo[MBB.getNumber()]->ClusterID);
259af732203SDimitry Andric     else {
260af732203SDimitry Andric       // BB goes into the special cold section if it is not specified in the
261af732203SDimitry Andric       // cluster info map.
262af732203SDimitry Andric       MBB.setSectionID(MBBSectionID::ColdSectionID);
263af732203SDimitry Andric     }
264af732203SDimitry Andric 
265af732203SDimitry Andric     if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&
266af732203SDimitry Andric         EHPadsSectionID != MBBSectionID::ExceptionSectionID) {
267af732203SDimitry Andric       // If we already have one cluster containing eh_pads, this must be updated
268af732203SDimitry Andric       // to ExceptionSectionID. Otherwise, we set it equal to the current
269af732203SDimitry Andric       // section ID.
270af732203SDimitry Andric       EHPadsSectionID = EHPadsSectionID.hasValue()
271af732203SDimitry Andric                             ? MBBSectionID::ExceptionSectionID
272af732203SDimitry Andric                             : MBB.getSectionID();
273af732203SDimitry Andric     }
274af732203SDimitry Andric   }
275af732203SDimitry Andric 
276af732203SDimitry Andric   // If EHPads are in more than one section, this places all of them in the
277af732203SDimitry Andric   // special exception section.
278af732203SDimitry Andric   if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)
279af732203SDimitry Andric     for (auto &MBB : MF)
280af732203SDimitry Andric       if (MBB.isEHPad())
281af732203SDimitry Andric         MBB.setSectionID(EHPadsSectionID.getValue());
282af732203SDimitry Andric }
283af732203SDimitry Andric 
sortBasicBlocksAndUpdateBranches(MachineFunction & MF,MachineBasicBlockComparator MBBCmp)284af732203SDimitry Andric void llvm::sortBasicBlocksAndUpdateBranches(
285af732203SDimitry Andric     MachineFunction &MF, MachineBasicBlockComparator MBBCmp) {
286af732203SDimitry Andric   SmallVector<MachineBasicBlock *, 4> PreLayoutFallThroughs(
287af732203SDimitry Andric       MF.getNumBlockIDs());
288af732203SDimitry Andric   for (auto &MBB : MF)
289af732203SDimitry Andric     PreLayoutFallThroughs[MBB.getNumber()] = MBB.getFallThrough();
290af732203SDimitry Andric 
291af732203SDimitry Andric   MF.sort(MBBCmp);
292af732203SDimitry Andric 
293af732203SDimitry Andric   // Set IsBeginSection and IsEndSection according to the assigned section IDs.
294af732203SDimitry Andric   MF.assignBeginEndSections();
295af732203SDimitry Andric 
296af732203SDimitry Andric   // After reordering basic blocks, we must update basic block branches to
297af732203SDimitry Andric   // insert explicit fallthrough branches when required and optimize branches
298af732203SDimitry Andric   // when possible.
299af732203SDimitry Andric   updateBranches(MF, PreLayoutFallThroughs);
300af732203SDimitry Andric }
301af732203SDimitry Andric 
302af732203SDimitry Andric // If the exception section begins with a landing pad, that landing pad will
303af732203SDimitry Andric // assume a zero offset (relative to @LPStart) in the LSDA. However, a value of
304af732203SDimitry Andric // zero implies "no landing pad." This function inserts a NOP just before the EH
305af732203SDimitry Andric // pad label to ensure a nonzero offset. Returns true if padding is not needed.
avoidZeroOffsetLandingPad(MachineFunction & MF)306af732203SDimitry Andric static bool avoidZeroOffsetLandingPad(MachineFunction &MF) {
307af732203SDimitry Andric   for (auto &MBB : MF) {
308af732203SDimitry Andric     if (MBB.isBeginSection() && MBB.isEHPad()) {
309af732203SDimitry Andric       MachineBasicBlock::iterator MI = MBB.begin();
310af732203SDimitry Andric       while (!MI->isEHLabel())
311af732203SDimitry Andric         ++MI;
312*5f7ddb14SDimitry Andric       MCInst Nop = MF.getSubtarget().getInstrInfo()->getNop();
313af732203SDimitry Andric       BuildMI(MBB, MI, DebugLoc(),
314*5f7ddb14SDimitry Andric               MF.getSubtarget().getInstrInfo()->get(Nop.getOpcode()));
315af732203SDimitry Andric       return false;
316af732203SDimitry Andric     }
317af732203SDimitry Andric   }
318af732203SDimitry Andric   return true;
319af732203SDimitry Andric }
320af732203SDimitry Andric 
321*5f7ddb14SDimitry Andric // This checks if the source of this function has drifted since this binary was
322*5f7ddb14SDimitry Andric // profiled previously.  For now, we are piggy backing on what PGO does to
323*5f7ddb14SDimitry Andric // detect this with instrumented profiles.  PGO emits an hash of the IR and
324*5f7ddb14SDimitry Andric // checks if the hash has changed.  Advanced basic block layout is usually done
325*5f7ddb14SDimitry Andric // on top of PGO optimized binaries and hence this check works well in practice.
hasInstrProfHashMismatch(MachineFunction & MF)326*5f7ddb14SDimitry Andric static bool hasInstrProfHashMismatch(MachineFunction &MF) {
327*5f7ddb14SDimitry Andric   if (!BBSectionsDetectSourceDrift)
328*5f7ddb14SDimitry Andric     return false;
329*5f7ddb14SDimitry Andric 
330*5f7ddb14SDimitry Andric   const char MetadataName[] = "instr_prof_hash_mismatch";
331*5f7ddb14SDimitry Andric   auto *Existing = MF.getFunction().getMetadata(LLVMContext::MD_annotation);
332*5f7ddb14SDimitry Andric   if (Existing) {
333*5f7ddb14SDimitry Andric     MDTuple *Tuple = cast<MDTuple>(Existing);
334*5f7ddb14SDimitry Andric     for (auto &N : Tuple->operands())
335*5f7ddb14SDimitry Andric       if (cast<MDString>(N.get())->getString() == MetadataName)
336*5f7ddb14SDimitry Andric         return true;
337*5f7ddb14SDimitry Andric   }
338*5f7ddb14SDimitry Andric 
339*5f7ddb14SDimitry Andric   return false;
340*5f7ddb14SDimitry Andric }
341*5f7ddb14SDimitry Andric 
runOnMachineFunction(MachineFunction & MF)342af732203SDimitry Andric bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {
343af732203SDimitry Andric   auto BBSectionsType = MF.getTarget().getBBSectionsType();
344af732203SDimitry Andric   assert(BBSectionsType != BasicBlockSection::None &&
345af732203SDimitry Andric          "BB Sections not enabled!");
346*5f7ddb14SDimitry Andric 
347*5f7ddb14SDimitry Andric   // Check for source drift.  If the source has changed since the profiles
348*5f7ddb14SDimitry Andric   // were obtained, optimizing basic blocks might be sub-optimal.
349*5f7ddb14SDimitry Andric   // This only applies to BasicBlockSection::List as it creates
350*5f7ddb14SDimitry Andric   // clusters of basic blocks using basic block ids. Source drift can
351*5f7ddb14SDimitry Andric   // invalidate these groupings leading to sub-optimal code generation with
352*5f7ddb14SDimitry Andric   // regards to performance.
353*5f7ddb14SDimitry Andric   if (BBSectionsType == BasicBlockSection::List &&
354*5f7ddb14SDimitry Andric       hasInstrProfHashMismatch(MF))
355*5f7ddb14SDimitry Andric     return true;
356*5f7ddb14SDimitry Andric 
357af732203SDimitry Andric   // Renumber blocks before sorting them for basic block sections.  This is
358af732203SDimitry Andric   // useful during sorting, basic blocks in the same section will retain the
359af732203SDimitry Andric   // default order.  This renumbering should also be done for basic block
360af732203SDimitry Andric   // labels to match the profiles with the correct blocks.
361af732203SDimitry Andric   MF.RenumberBlocks();
362af732203SDimitry Andric 
363af732203SDimitry Andric   if (BBSectionsType == BasicBlockSection::Labels) {
364af732203SDimitry Andric     MF.setBBSectionsType(BBSectionsType);
365af732203SDimitry Andric     return true;
366af732203SDimitry Andric   }
367af732203SDimitry Andric 
368af732203SDimitry Andric   std::vector<Optional<BBClusterInfo>> FuncBBClusterInfo;
369af732203SDimitry Andric   if (BBSectionsType == BasicBlockSection::List &&
370af732203SDimitry Andric       !getBBClusterInfoForFunction(MF, FuncAliasMap, ProgramBBClusterInfo,
371af732203SDimitry Andric                                    FuncBBClusterInfo))
372af732203SDimitry Andric     return true;
373af732203SDimitry Andric   MF.setBBSectionsType(BBSectionsType);
374af732203SDimitry Andric   assignSections(MF, FuncBBClusterInfo);
375af732203SDimitry Andric 
376af732203SDimitry Andric   // We make sure that the cluster including the entry basic block precedes all
377af732203SDimitry Andric   // other clusters.
378af732203SDimitry Andric   auto EntryBBSectionID = MF.front().getSectionID();
379af732203SDimitry Andric 
380af732203SDimitry Andric   // Helper function for ordering BB sections as follows:
381af732203SDimitry Andric   //   * Entry section (section including the entry block).
382af732203SDimitry Andric   //   * Regular sections (in increasing order of their Number).
383af732203SDimitry Andric   //     ...
384af732203SDimitry Andric   //   * Exception section
385af732203SDimitry Andric   //   * Cold section
386af732203SDimitry Andric   auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,
387af732203SDimitry Andric                                             const MBBSectionID &RHS) {
388af732203SDimitry Andric     // We make sure that the section containing the entry block precedes all the
389af732203SDimitry Andric     // other sections.
390af732203SDimitry Andric     if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)
391af732203SDimitry Andric       return LHS == EntryBBSectionID;
392af732203SDimitry Andric     return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;
393af732203SDimitry Andric   };
394af732203SDimitry Andric 
395af732203SDimitry Andric   // We sort all basic blocks to make sure the basic blocks of every cluster are
396af732203SDimitry Andric   // contiguous and ordered accordingly. Furthermore, clusters are ordered in
397af732203SDimitry Andric   // increasing order of their section IDs, with the exception and the
398af732203SDimitry Andric   // cold section placed at the end of the function.
399af732203SDimitry Andric   auto Comparator = [&](const MachineBasicBlock &X,
400af732203SDimitry Andric                         const MachineBasicBlock &Y) {
401af732203SDimitry Andric     auto XSectionID = X.getSectionID();
402af732203SDimitry Andric     auto YSectionID = Y.getSectionID();
403af732203SDimitry Andric     if (XSectionID != YSectionID)
404af732203SDimitry Andric       return MBBSectionOrder(XSectionID, YSectionID);
405af732203SDimitry Andric     // If the two basic block are in the same section, the order is decided by
406af732203SDimitry Andric     // their position within the section.
407af732203SDimitry Andric     if (XSectionID.Type == MBBSectionID::SectionType::Default)
408af732203SDimitry Andric       return FuncBBClusterInfo[X.getNumber()]->PositionInCluster <
409af732203SDimitry Andric              FuncBBClusterInfo[Y.getNumber()]->PositionInCluster;
410af732203SDimitry Andric     return X.getNumber() < Y.getNumber();
411af732203SDimitry Andric   };
412af732203SDimitry Andric 
413af732203SDimitry Andric   sortBasicBlocksAndUpdateBranches(MF, Comparator);
414af732203SDimitry Andric   avoidZeroOffsetLandingPad(MF);
415af732203SDimitry Andric   return true;
416af732203SDimitry Andric }
417af732203SDimitry Andric 
418af732203SDimitry Andric // Basic Block Sections can be enabled for a subset of machine basic blocks.
419af732203SDimitry Andric // This is done by passing a file containing names of functions for which basic
420af732203SDimitry Andric // block sections are desired.  Additionally, machine basic block ids of the
421af732203SDimitry Andric // functions can also be specified for a finer granularity. Moreover, a cluster
422af732203SDimitry Andric // of basic blocks could be assigned to the same section.
423af732203SDimitry Andric // A file with basic block sections for all of function main and three blocks
424af732203SDimitry Andric // for function foo (of which 1 and 2 are placed in a cluster) looks like this:
425af732203SDimitry Andric // ----------------------------
426af732203SDimitry Andric // list.txt:
427af732203SDimitry Andric // !main
428af732203SDimitry Andric // !foo
429af732203SDimitry Andric // !!1 2
430af732203SDimitry Andric // !!4
getBBClusterInfo(const MemoryBuffer * MBuf,ProgramBBClusterInfoMapTy & ProgramBBClusterInfo,StringMap<StringRef> & FuncAliasMap)431af732203SDimitry Andric static Error getBBClusterInfo(const MemoryBuffer *MBuf,
432af732203SDimitry Andric                               ProgramBBClusterInfoMapTy &ProgramBBClusterInfo,
433af732203SDimitry Andric                               StringMap<StringRef> &FuncAliasMap) {
434af732203SDimitry Andric   assert(MBuf);
435af732203SDimitry Andric   line_iterator LineIt(*MBuf, /*SkipBlanks=*/true, /*CommentMarker=*/'#');
436af732203SDimitry Andric 
437af732203SDimitry Andric   auto invalidProfileError = [&](auto Message) {
438af732203SDimitry Andric     return make_error<StringError>(
439af732203SDimitry Andric         Twine("Invalid profile " + MBuf->getBufferIdentifier() + " at line " +
440af732203SDimitry Andric               Twine(LineIt.line_number()) + ": " + Message),
441af732203SDimitry Andric         inconvertibleErrorCode());
442af732203SDimitry Andric   };
443af732203SDimitry Andric 
444af732203SDimitry Andric   auto FI = ProgramBBClusterInfo.end();
445af732203SDimitry Andric 
446af732203SDimitry Andric   // Current cluster ID corresponding to this function.
447af732203SDimitry Andric   unsigned CurrentCluster = 0;
448af732203SDimitry Andric   // Current position in the current cluster.
449af732203SDimitry Andric   unsigned CurrentPosition = 0;
450af732203SDimitry Andric 
451af732203SDimitry Andric   // Temporary set to ensure every basic block ID appears once in the clusters
452af732203SDimitry Andric   // of a function.
453af732203SDimitry Andric   SmallSet<unsigned, 4> FuncBBIDs;
454af732203SDimitry Andric 
455af732203SDimitry Andric   for (; !LineIt.is_at_eof(); ++LineIt) {
456af732203SDimitry Andric     StringRef S(*LineIt);
457af732203SDimitry Andric     if (S[0] == '@')
458af732203SDimitry Andric       continue;
459af732203SDimitry Andric     // Check for the leading "!"
460af732203SDimitry Andric     if (!S.consume_front("!") || S.empty())
461af732203SDimitry Andric       break;
462af732203SDimitry Andric     // Check for second "!" which indicates a cluster of basic blocks.
463af732203SDimitry Andric     if (S.consume_front("!")) {
464af732203SDimitry Andric       if (FI == ProgramBBClusterInfo.end())
465af732203SDimitry Andric         return invalidProfileError(
466af732203SDimitry Andric             "Cluster list does not follow a function name specifier.");
467af732203SDimitry Andric       SmallVector<StringRef, 4> BBIndexes;
468af732203SDimitry Andric       S.split(BBIndexes, ' ');
469af732203SDimitry Andric       // Reset current cluster position.
470af732203SDimitry Andric       CurrentPosition = 0;
471af732203SDimitry Andric       for (auto BBIndexStr : BBIndexes) {
472af732203SDimitry Andric         unsigned long long BBIndex;
473af732203SDimitry Andric         if (getAsUnsignedInteger(BBIndexStr, 10, BBIndex))
474af732203SDimitry Andric           return invalidProfileError(Twine("Unsigned integer expected: '") +
475af732203SDimitry Andric                                      BBIndexStr + "'.");
476af732203SDimitry Andric         if (!FuncBBIDs.insert(BBIndex).second)
477af732203SDimitry Andric           return invalidProfileError(Twine("Duplicate basic block id found '") +
478af732203SDimitry Andric                                      BBIndexStr + "'.");
479af732203SDimitry Andric         if (!BBIndex && CurrentPosition)
480af732203SDimitry Andric           return invalidProfileError("Entry BB (0) does not begin a cluster.");
481af732203SDimitry Andric 
482af732203SDimitry Andric         FI->second.emplace_back(BBClusterInfo{
483af732203SDimitry Andric             ((unsigned)BBIndex), CurrentCluster, CurrentPosition++});
484af732203SDimitry Andric       }
485af732203SDimitry Andric       CurrentCluster++;
486af732203SDimitry Andric     } else { // This is a function name specifier.
487af732203SDimitry Andric       // Function aliases are separated using '/'. We use the first function
488af732203SDimitry Andric       // name for the cluster info mapping and delegate all other aliases to
489af732203SDimitry Andric       // this one.
490af732203SDimitry Andric       SmallVector<StringRef, 4> Aliases;
491af732203SDimitry Andric       S.split(Aliases, '/');
492af732203SDimitry Andric       for (size_t i = 1; i < Aliases.size(); ++i)
493af732203SDimitry Andric         FuncAliasMap.try_emplace(Aliases[i], Aliases.front());
494af732203SDimitry Andric 
495af732203SDimitry Andric       // Prepare for parsing clusters of this function name.
496af732203SDimitry Andric       // Start a new cluster map for this function name.
497af732203SDimitry Andric       FI = ProgramBBClusterInfo.try_emplace(Aliases.front()).first;
498af732203SDimitry Andric       CurrentCluster = 0;
499af732203SDimitry Andric       FuncBBIDs.clear();
500af732203SDimitry Andric     }
501af732203SDimitry Andric   }
502af732203SDimitry Andric   return Error::success();
503af732203SDimitry Andric }
504af732203SDimitry Andric 
doInitialization(Module & M)505af732203SDimitry Andric bool BasicBlockSections::doInitialization(Module &M) {
506af732203SDimitry Andric   if (!MBuf)
507af732203SDimitry Andric     return false;
508af732203SDimitry Andric   if (auto Err = getBBClusterInfo(MBuf, ProgramBBClusterInfo, FuncAliasMap))
509af732203SDimitry Andric     report_fatal_error(std::move(Err));
510af732203SDimitry Andric   return false;
511af732203SDimitry Andric }
512af732203SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const513af732203SDimitry Andric void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {
514af732203SDimitry Andric   AU.setPreservesAll();
515af732203SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
516af732203SDimitry Andric }
517af732203SDimitry Andric 
518af732203SDimitry Andric MachineFunctionPass *
createBasicBlockSectionsPass(const MemoryBuffer * Buf)519af732203SDimitry Andric llvm::createBasicBlockSectionsPass(const MemoryBuffer *Buf) {
520af732203SDimitry Andric   return new BasicBlockSections(Buf);
521af732203SDimitry Andric }
522