LLVM 24.0.0git
BasicBlockSections.cpp
Go to the documentation of this file.
1//===-- BasicBlockSections.cpp ---=========--------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// BasicBlockSections implementation.
10//
11// The purpose of this pass is to assign sections to basic blocks when
12// -fbasic-block-sections= option is used. Further, with profile information
13// only the subset of basic blocks with profiles are placed in separate sections
14// and the rest are grouped in a cold section. The exception handling blocks are
15// treated specially to ensure they are all in one seciton.
16//
17// This pass also implements machine function splitting
18// (-function-splitting=all). Functions without a basic block sections profile
19// are split using PGO/AutoFDO profiles: cold blocks are moved into a separate
20// section with the symbol `foo.cold`.
21//
22// Basic Block Sections
23// ====================
24//
25// With option, -fbasic-block-sections=list, every function may be split into
26// clusters of basic blocks. Every cluster will be emitted into a separate
27// section with its basic blocks sequenced in the given order. To get the
28// optimized performance, the clusters must form an optimal BB layout for the
29// function. We insert a symbol at the beginning of every cluster's section to
30// allow the linker to reorder the sections in any arbitrary sequence. A global
31// order of these sections would encapsulate the function layout.
32// For example, consider the following clusters for a function foo (consisting
33// of 6 basic blocks 0, 1, ..., 5).
34//
35// 0 2
36// 1 3 5
37//
38// * Basic blocks 0 and 2 are placed in one section with symbol `foo`
39// referencing the beginning of this section.
40// * Basic blocks 1, 3, 5 are placed in a separate section. A new symbol
41// `foo.__part.1` will reference the beginning of this section.
42// * Basic block 4 (note that it is not referenced in the list) is placed in
43// one section, and a new symbol `foo.cold` will point to it.
44//
45// There are a couple of challenges to be addressed:
46//
47// 1. The last basic block of every cluster should not have any implicit
48// fallthrough to its next basic block, as it can be reordered by the linker.
49// The compiler should make these fallthroughs explicit by adding
50// unconditional jumps..
51//
52// 2. All inter-cluster branch targets would now need to be resolved by the
53// linker as they cannot be calculated during compile time. This is done
54// using static relocations. Further, the compiler tries to use short branch
55// instructions on some ISAs for small branch offsets. This is not possible
56// for inter-cluster branches as the offset is not determined at compile
57// time, and therefore, long branch instructions have to be used for those.
58//
59// 3. Debug Information (DebugInfo) and Call Frame Information (CFI) emission
60// needs special handling with basic block sections. DebugInfo needs to be
61// emitted with more relocations as basic block sections can break a
62// function into potentially several disjoint pieces, and CFI needs to be
63// emitted per cluster. This also bloats the object file and binary sizes.
64//
65// Basic Block Address Map
66// ==================
67//
68// With -fbasic-block-address-map, we emit the offsets of BB addresses of
69// every function into the .llvm_bb_addr_map section. Along with the function
70// symbols, this allows for mapping of virtual addresses in PMU profiles back to
71// the corresponding basic blocks. This logic is implemented in AsmPrinter. This
72// pass only assigns the BBSectionType of every function to ``labels``.
73//
74// Machine Function Splitting
75// ==========================
76//
77// With -function-splitting=all, functions without a basic block sections
78// profile are split using PGO/AutoFDO profiles. Blocks deemed cold are placed
79// in a separate section prefixed with ".text.split." (see
80// -bbsections-cold-text-prefix), referenced by the symbol `foo.cold`. Grouping
81// cold blocks across functions decreases fragmentation and improves icache and
82// iTLB utilization. Such functions get the BBSectionType ``Preset``.
83//
84// For the original RFC of machine function splitting please see
85// https://groups.google.com/d/msg/llvm-dev/RUegaMg-iqc/wFAVxa6fCgAJ
86//
87//===----------------------------------------------------------------------===//
88
90#include "llvm/ADT/StringRef.h"
101#include "llvm/CodeGen/Passes.h"
103#include "llvm/IR/Function.h"
109#include <optional>
110
111using namespace llvm;
112
113// Placing the cold clusters in a separate section mitigates against poor
114// profiles and allows optimizations such as hugepage mapping to be applied at a
115// section granularity. Defaults to ".text.split." which is recognized by lld
116// via the `-z keep-text-section-prefix` flag.
118 "bbsections-cold-text-prefix",
119 cl::desc("The text prefix to use for cold basic block clusters"),
120 cl::init(".text.split."), cl::Hidden);
121
123 "bbsections-detect-source-drift",
124 cl::desc("This checks if there is a fdo instr. profile hash "
125 "mismatch for this function"),
126 cl::init(true), cl::Hidden);
127
128// FIXME: This cutoff value is CPU dependent and should be moved to
129// TargetTransformInfo once we consider enabling this on other platforms.
130// The value is expressed as a ProfileSummaryInfo integer percentile cutoff.
131// Defaults to 999950, i.e. all blocks colder than 99.995 percentile are split.
132// The default was empirically determined to be optimal when considering cutoff
133// values between 99%-ile to 100%-ile with respect to iTLB and icache metrics on
134// Intel CPUs.
136 PercentileCutoff("mfs-psi-cutoff",
137 cl::desc("Percentile profile summary cutoff used to "
138 "determine cold blocks. Unused if set to zero."),
139 cl::init(999950), cl::Hidden);
140
142 "mfs-count-threshold",
143 cl::desc(
144 "Minimum number of times a block must be executed to be retained."),
145 cl::init(1), cl::Hidden);
146
148 "mfs-split-ehcode",
149 cl::desc("Splits all EH code and it's descendants by default."),
150 cl::init(false), cl::Hidden);
151
152namespace {
153
154class BasicBlockSections : public MachineFunctionPass {
155public:
156 static char ID;
157
158 explicit BasicBlockSections(bool SplitWithPGO = false)
159 : MachineFunctionPass(ID), SplitWithPGO(SplitWithPGO) {
161 }
162
163 StringRef getPassName() const override {
164 return "Basic Block Sections Transformation";
165 }
166
167 void getAnalysisUsage(AnalysisUsage &AU) const override;
168
169 /// Identify basic blocks that need separate sections and prepare to emit them
170 /// accordingly.
171 bool runOnMachineFunction(MachineFunction &MF) override;
172
173private:
174 bool shouldSplitWithPGO(MachineFunction &MF);
175 void assignColdSectionWithPGO(MachineFunction &MF);
176
177 // Whether functions without a basic block sections profile are split using
178 // PGO/AutoFDO profiles (-function-splitting=all).
179 const bool SplitWithPGO;
180};
181
182} // end anonymous namespace
183
184char BasicBlockSections::ID = 0;
186 BasicBlockSections, "bbsections-prepare",
187 "Prepares for basic block sections, by splitting functions "
188 "into clusters of basic blocks.",
189 false, false)
193INITIALIZE_PASS_END(BasicBlockSections, "bbsections-prepare",
194 "Prepares for basic block sections, by splitting functions "
195 "into clusters of basic blocks.",
197
198// This function updates and optimizes the branching instructions of every basic
199// block in a given function to account for changes in the layout.
200static void
202 const SmallVector<MachineBasicBlock *> &PreLayoutFallThroughs) {
203 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
205 for (auto &MBB : MF) {
206 auto NextMBBI = std::next(MBB.getIterator());
207 auto *FTMBB = PreLayoutFallThroughs[MBB.getNumber()];
208 // If this block had a fallthrough before we need an explicit unconditional
209 // branch to that block if either
210 // 1- the block ends a section, which means its next block may be
211 // reorderd by the linker, or
212 // 2- the fallthrough block is not adjacent to the block in the new
213 // order.
214 if (FTMBB && (MBB.isEndSection() || &*NextMBBI != FTMBB))
215 TII->insertUnconditionalBranch(MBB, FTMBB, MBB.findBranchDebugLoc());
216
217 // We do not optimize branches for machine basic blocks ending sections, as
218 // their adjacent block might be reordered by the linker.
219 if (MBB.isEndSection())
220 continue;
221
222 // It might be possible to optimize branches by flipping the branch
223 // condition.
224 Cond.clear();
225 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; // For analyzeBranch.
226 if (TII->analyzeBranch(MBB, TBB, FBB, Cond))
227 continue;
228 MBB.updateTerminator(FTMBB);
229 }
230}
231
232// This function generates the machine basic block clusters of "hot" blocks.
233// Currently, only support one cluster creation.
234// TODO: Support multi-cluster creation.
238 SmallVector<BBClusterInfo> BBClusterInfos;
239 auto OptWeightInfo = BMI.getWeightInfo(MF.getName());
240 if (!OptWeightInfo)
241 return BBClusterInfos;
242 auto BlockWeights = OptWeightInfo->BlockWeights;
243 auto EdgeWeights = OptWeightInfo->EdgeWeights;
244
246 if (MF.size() <= 2) {
247 for (auto &MBB : MF) {
248 if (MBB.isEntryBlock() || BlockWeights[&MBB] > 0) {
249 HotMBBs.push_back(&MBB);
250 }
251 }
252 } else {
253 SmallVector<uint64_t, 0> BlockSizes(MF.size());
254 SmallVector<uint64_t, 0> BlockCounts(MF.size());
255 std::vector<const MachineBasicBlock *> OrigOrder;
256 OrigOrder.reserve(MF.size());
258
259 // Renumber blocks for running the layout algorithm.
260 MF.RenumberBlocks();
261
262 // Init the MBB size and count.
263 for (auto &MBB : MF) {
264 auto NonDbgInsts =
265 instructionsWithoutDebug(MBB.instr_begin(), MBB.instr_end());
266 int NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
267 BlockSizes[MBB.getNumber()] = 4 * NumInsts;
268 BlockCounts[MBB.getNumber()] = BlockWeights[&MBB];
269 OrigOrder.push_back(&MBB);
270 }
271
272 // Init the edge count.
273 for (auto &MBB : MF) {
274 for (auto *Succ : MBB.successors()) {
275 auto EdgeWeight = EdgeWeights[std::make_pair(&MBB, Succ)];
276 JumpCounts.push_back({static_cast<uint64_t>(MBB.getNumber()),
277 static_cast<uint64_t>(Succ->getNumber()),
278 EdgeWeight});
279 }
280 }
281
282 // Run the layout algorithm.
283 auto Result = computeExtTspLayout(BlockSizes, BlockCounts, JumpCounts);
284 for (uint64_t R : Result) {
285 auto Block = OrigOrder[R];
286 if (Block->isEntryBlock() || BlockWeights[Block] > 0)
287 HotMBBs.push_back(Block);
288 }
289 }
290
291 // Generate the "hot" basic block cluster.
292 if (!HotMBBs.empty()) {
293 unsigned CurrentPosition = 0;
294 for (auto &MBB : HotMBBs)
295 BBClusterInfos.push_back({*MBB->getBBID(), 0, CurrentPosition++});
296 }
297 return BBClusterInfos;
298}
299
300// This function sorts basic blocks according to the cluster's information.
301// All explicitly specified clusters of basic blocks will be ordered
302// accordingly. All non-specified BBs go into a separate "Cold" section.
303// Additionally, if exception handling landing pads end up in more than one
304// clusters, they are moved into a single "Exception" section. Eventually,
305// clusters are ordered in increasing order of their IDs, with the "Exception"
306// and "Cold" succeeding all other clusters. With -function-splitting=none, all
307// basic blocks stay in the default section instead.
308// FuncClusterInfo represents the cluster information for basic blocks. It
309// maps from BBID of basic blocks to their cluster information.
310static void
312 const DenseMap<UniqueBBID, BBClusterInfo> &FuncClusterInfo) {
313 assert(MF.hasBBSections() && "BB Sections is not set for function.");
314 // With function splitting disabled, the profile only decides the layout and
315 // the function is emitted as a single section.
318 return;
319 // This variable stores the section ID of the cluster containing eh_pads (if
320 // all eh_pads are one cluster). If more than one cluster contain eh_pads, we
321 // set it equal to ExceptionSectionID.
322 std::optional<MBBSectionID> EHPadsSectionID;
323
324 for (auto &MBB : MF) {
325 // With the 'all' option, every basic block is placed in a unique section.
326 // With the 'list' option, every basic block is placed in a section
327 // associated with its cluster.
329 // If unique sections are desired for all basic blocks of the function, we
330 // set every basic block's section ID equal to its original position in
331 // the layout (which is equal to its number). This ensures that basic
332 // blocks are ordered canonically.
333 MBB.setSectionID(MBB.getNumber());
334 } else {
335 auto I = FuncClusterInfo.find(*MBB.getBBID());
336 if (I != FuncClusterInfo.end()) {
337 MBB.setSectionID(I->second.ClusterID);
338 } else {
339 const TargetInstrInfo &TII =
340 *MBB.getParent()->getSubtarget().getInstrInfo();
341
342 if (TII.isMBBSafeToSplitToCold(MBB)) {
343 // BB goes into the special cold section if it is not specified in the
344 // cluster info map. If it is not safe to split, it is kept in the
345 // default section.
346 MBB.setSectionID(MBBSectionID::ColdSectionID);
347 }
348 }
349 }
350
351 if (MBB.isEHPad() && EHPadsSectionID != MBB.getSectionID() &&
352 EHPadsSectionID != MBBSectionID::ExceptionSectionID) {
353 // If we already have one cluster containing eh_pads, this must be updated
354 // to ExceptionSectionID. Otherwise, we set it equal to the current
355 // section ID.
356 EHPadsSectionID = EHPadsSectionID ? MBBSectionID::ExceptionSectionID
357 : MBB.getSectionID();
358 }
359 }
360
361 // If EHPads are in more than one section, this places all of them in the
362 // special exception section.
363 if (EHPadsSectionID == MBBSectionID::ExceptionSectionID)
364 for (auto &MBB : MF)
365 if (MBB.isEHPad())
366 MBB.setSectionID(*EHPadsSectionID);
367}
368
371 [[maybe_unused]] const MachineBasicBlock *EntryBlock = &MF.front();
372 SmallVector<MachineBasicBlock *> PreLayoutFallThroughs(MF.getNumBlockIDs());
373 for (auto &MBB : MF)
374 PreLayoutFallThroughs[MBB.getNumber()] =
375 MBB.getFallThrough(/*JumpToFallThrough=*/false);
376
377 MF.sort(MBBCmp);
378 assert(&MF.front() == EntryBlock &&
379 "Entry block should not be displaced by basic block sections");
380
381 // Set IsBeginSection and IsEndSection according to the assigned section IDs.
383
384 // After reordering basic blocks, we must update basic block branches to
385 // insert explicit fallthrough branches when required and optimize branches
386 // when possible.
387 updateBranches(MF, PreLayoutFallThroughs);
388}
389
390// If the exception section begins with a landing pad, that landing pad will
391// assume a zero offset (relative to @LPStart) in the LSDA. However, a value of
392// zero implies "no landing pad." This function inserts a NOP just before the EH
393// pad label to ensure a nonzero offset.
395 std::optional<MBBSectionID> CurrentSection;
396 auto IsFirstNonEmptyBBInSection = [&](const MachineBasicBlock &MBB) {
397 if (MBB.getFirstNonDebugInstr() == MBB.end() ||
398 MBB.getSectionID() == CurrentSection)
399 return false;
400 CurrentSection = MBB.getSectionID();
401 return true;
402 };
403
404 for (auto &MBB : MF) {
405 if (IsFirstNonEmptyBBInSection(MBB) && MBB.isEHPad()) {
407 while (!MI->isEHLabel())
408 ++MI;
410 }
411 }
412}
413
416 return false;
417
418 const char MetadataName[] = "instr_prof_hash_mismatch";
419 auto *Existing = MF.getFunction().getMetadata(LLVMContext::MD_annotation);
420 if (Existing) {
421 MDTuple *Tuple = cast<MDTuple>(Existing);
422 for (const auto &N : Tuple->operands())
423 if (N.equalsStr(MetadataName))
424 return true;
425 }
426
427 return false;
428}
429
430/// setDescendantEHBlocksCold - This splits all EH pads and blocks reachable
431/// only by EH pad as cold. This will help mark EH pads statically cold
432/// instead of relying on profile data.
435 computeEHOnlyBlocks(MF, EHBlocks);
436 for (auto Block : EHBlocks) {
437 Block->setSectionID(MBBSectionID::ColdSectionID);
438 }
439}
440
442 const MachineBlockFrequencyInfo *MBFI,
443 ProfileSummaryInfo *PSI) {
444 std::optional<uint64_t> Count = MBFI->getBlockProfileCount(&MBB);
445 // For instrumentation profiles and sample profiles, we use different ways
446 // to judge whether a block is cold and should be split.
448 // If using instrument profile, which is deemed "accurate", no count means
449 // cold.
450 if (!Count)
451 return true;
452 if (PercentileCutoff > 0)
454 // Fallthrough to end of function.
455 } else if (PSI->hasSampleProfile()) {
456 // For sample profile, no count means "do not judege coldness".
457 if (!Count)
458 return false;
459 }
460
461 return (*Count < ColdCountThreshold);
462}
463
464// Returns whether a function which does not have a basic block sections profile
465// should be split using its PGO/AutoFDO profile.
466bool BasicBlockSections::shouldSplitWithPGO(MachineFunction &MF) {
467 if (!SplitWithPGO || skipFunction(MF.getFunction()))
468 return false;
469
470 // We target functions with profile data. Static information in the form
471 // of exception handling code may be split to cold if user passes the
472 // mfs-split-ehcode flag.
474 return false;
475
476 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
477 if (!TII.isFunctionSafeToSplit(MF))
478 return false;
479
480 // Do not split functions which are in the basic block sections profile, even
481 // if their profile is not used due to source drift.
482 if (MF.getTarget().getBBSectionsType() == BasicBlockSection::List &&
483 getAnalysis<BasicBlockSectionsProfileReaderWrapperPass>()
484 .getBBSPR()
485 .isFunctionHot(MF.getName()))
486 return false;
487
488 return true;
489}
490
491// Splits a function using its PGO/AutoFDO profile: assigns the cold section to
492// cold blocks, and the default section to all the other blocks.
493void BasicBlockSections::assignColdSectionWithPGO(MachineFunction &MF) {
494 MF.setBBSectionsType(BasicBlockSection::Preset);
495
496 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
497 bool UseProfileData = MF.getFunction().hasProfileData();
498 MachineBlockFrequencyInfo *MBFI = nullptr;
499 ProfileSummaryInfo *PSI = nullptr;
500 if (UseProfileData) {
501 MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
502 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
503 // If we don't have a good profile (sample profile is not deemed
504 // as a "good profile") and the function is not hot, then early
505 // return. (Because we can only trust hot functions when profile
506 // quality is not good.)
507 if (PSI->hasSampleProfile() && !PSI->isFunctionHotInCallGraph(&MF, *MBFI)) {
508 // Split all EH code and it's descendant statically by default.
509 if (SplitAllEHCode)
511 return;
512 }
513 }
514
515 SmallVector<MachineBasicBlock *, 2> LandingPads;
516 for (auto &MBB : MF) {
517 if (MBB.isEntryBlock())
518 continue;
519
520 if (MBB.isEHPad())
521 LandingPads.push_back(&MBB);
522 else if (UseProfileData && isColdBlock(MBB, MBFI, PSI) &&
523 TII.isMBBSafeToSplitToCold(MBB) && !SplitAllEHCode)
525 }
526
527 // Split all EH code and it's descendant statically by default.
528 if (SplitAllEHCode)
530 // We only split out eh pads if all of them are cold.
531 else {
532 // Here we have UseProfileData == true.
533 bool HasHotLandingPads = false;
534 for (const MachineBasicBlock *LP : LandingPads) {
535 if (!isColdBlock(*LP, MBFI, PSI) || !TII.isMBBSafeToSplitToCold(*LP))
536 HasHotLandingPads = true;
537 }
538 if (!HasHotLandingPads) {
539 for (MachineBasicBlock *LP : LandingPads)
540 LP->setSectionID(MBBSectionID::ColdSectionID);
541 }
542 }
543}
544
545// Identify, arrange, and modify basic blocks which need separate sections
546// according to the specification provided by the -fbasic-block-sections flag,
547// or according to the PGO/AutoFDO profile with -function-splitting=all.
548bool BasicBlockSections::runOnMachineFunction(MachineFunction &MF) {
549 auto BBSectionsType = MF.getTarget().getBBSectionsType();
550
551 DenseMap<UniqueBBID, BBClusterInfo> FuncClusterInfo;
552 // Check for source drift. If the source has changed since the profiles
553 // were obtained, optimizing basic blocks might be sub-optimal.
554 // This only applies to BasicBlockSection::List as it creates
555 // clusters of basic blocks using basic block ids. Source drift can
556 // invalidate these groupings leading to sub-optimal code generation with
557 // regards to performance.
558 if (BBSectionsType == BasicBlockSection::List &&
561 if (auto *BMI = getAnalysisIfAvailable<BasicBlockMatchingAndInference>()) {
563 } else {
564 ClusterInfo = getAnalysis<BasicBlockSectionsProfileReaderWrapperPass>()
565 .getClusterInfoForFunction(MF.getName());
566 }
567 for (auto &BBClusterInfo : ClusterInfo) {
568 FuncClusterInfo.try_emplace(BBClusterInfo.BBID, BBClusterInfo);
569 }
570 }
571
572 // A function without a basic block sections profile is split using its
573 // PGO/AutoFDO profile, if enabled.
574 const bool UsePGO =
575 BBSectionsType == BasicBlockSection::None ||
576 (BBSectionsType == BasicBlockSection::List && FuncClusterInfo.empty());
577 if (UsePGO && !shouldSplitWithPGO(MF))
578 return false;
579
580 // Renumber blocks before assigning sections and sorting them. This is useful
581 // for accessing the original layout positions and finding the original
582 // fallthroughs. Blocks which are not in any cluster keep their original
583 // order, which retains decisions made by prior passes such as
584 // MachineBlockPlacement.
585 MF.RenumberBlocks();
586
587 if (UsePGO) {
588 assignColdSectionWithPGO(MF);
589 } else {
590 MF.setBBSectionsType(BBSectionsType);
591 assignSections(MF, FuncClusterInfo);
592 }
593
594 const MachineBasicBlock &EntryBB = MF.front();
595 auto EntryBBSectionID = EntryBB.getSectionID();
596
597 // Helper function for ordering BB sections as follows:
598 // * Entry section (section including the entry block).
599 // * Regular sections (in increasing order of their Number).
600 // ...
601 // * Exception section
602 // * Cold section
603 auto MBBSectionOrder = [EntryBBSectionID](const MBBSectionID &LHS,
604 const MBBSectionID &RHS) {
605 // We make sure that the section containing the entry block precedes all the
606 // other sections.
607 if (LHS == EntryBBSectionID || RHS == EntryBBSectionID)
608 return LHS == EntryBBSectionID;
609 return LHS.Type == RHS.Type ? LHS.Number < RHS.Number : LHS.Type < RHS.Type;
610 };
611
612 // We sort all basic blocks to make sure the basic blocks of every cluster are
613 // contiguous and ordered accordingly. Furthermore, clusters are ordered in
614 // increasing order of their section IDs, with the exception and the
615 // cold section placed at the end of the function.
616 // Also, we force the entry block of the function to be placed at the
617 // beginning of the function, regardless of the requested order.
618 auto Comparator = [&](const MachineBasicBlock &X,
619 const MachineBasicBlock &Y) {
620 auto XSectionID = X.getSectionID();
621 auto YSectionID = Y.getSectionID();
622 if (XSectionID != YSectionID)
623 return MBBSectionOrder(XSectionID, YSectionID);
624 // Make sure that the entry block is placed at the beginning.
625 if (&X == &EntryBB || &Y == &EntryBB)
626 return &X == &EntryBB;
627 // If the two basic blocks are in the same section, the order is decided by
628 // their cluster and their position within the cluster. A section holds more
629 // than one cluster only with -function-splitting=none. Basic blocks which
630 // are not in any cluster come after all the profiled basic blocks of the
631 // section, in their original order. Without a basic block sections profile,
632 // all basic blocks keep their original order (they might not have BBIDs).
633 if (XSectionID.Type == MBBSectionID::SectionType::Default &&
634 !FuncClusterInfo.empty()) {
635 auto XI = FuncClusterInfo.find(*X.getBBID());
636 auto YI = FuncClusterInfo.find(*Y.getBBID());
637 bool XInCluster = XI != FuncClusterInfo.end();
638 bool YInCluster = YI != FuncClusterInfo.end();
639 if (XInCluster != YInCluster)
640 return XInCluster;
641 if (XInCluster)
642 return std::tie(XI->second.ClusterID, XI->second.PositionInCluster) <
643 std::tie(YI->second.ClusterID, YI->second.PositionInCluster);
644 }
645 return X.getNumber() < Y.getNumber();
646 };
647
648 sortBasicBlocksAndUpdateBranches(MF, Comparator);
650 return true;
651}
652
653void BasicBlockSections::getAnalysisUsage(AnalysisUsage &AU) const {
654 AU.setPreservesAll();
655 AU.addRequired<BasicBlockSectionsProfileReaderWrapperPass>();
656 if (SplitWithPGO) {
657 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>();
658 AU.addRequired<ProfileSummaryInfoWrapperPass>();
659 }
660 AU.addUsedIfAvailable<BasicBlockMatchingAndInference>();
661 AU.addUsedIfAvailable<MachineDominatorTreeWrapperPass>();
662 AU.addUsedIfAvailable<MachinePostDominatorTreeWrapperPass>();
664}
665
667 return new BasicBlockSections(SplitWithPGO);
668}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
MachineBasicBlock & MBB
static bool isColdBlock(const MachineBasicBlock &MBB, const MachineBlockFrequencyInfo *MBFI, ProfileSummaryInfo *PSI)
static cl::opt< unsigned > ColdCountThreshold("mfs-count-threshold", cl::desc("Minimum number of times a block must be executed to be retained."), cl::init(1), cl::Hidden)
static void assignSections(MachineFunction &MF, const DenseMap< UniqueBBID, BBClusterInfo > &FuncClusterInfo)
static cl::opt< bool > BBSectionsDetectSourceDrift("bbsections-detect-source-drift", cl::desc("This checks if there is a fdo instr. profile hash " "mismatch for this function"), cl::init(true), cl::Hidden)
static void setDescendantEHBlocksCold(MachineFunction &MF)
setDescendantEHBlocksCold - This splits all EH pads and blocks reachable only by EH pad as cold.
bbsections Prepares for basic block by splitting functions into clusters of basic static false void updateBranches(MachineFunction &MF, const SmallVector< MachineBasicBlock * > &PreLayoutFallThroughs)
static cl::opt< unsigned > PercentileCutoff("mfs-psi-cutoff", cl::desc("Percentile profile summary cutoff used to " "determine cold blocks. Unused if set to zero."), cl::init(999950), cl::Hidden)
static cl::opt< bool > SplitAllEHCode("mfs-split-ehcode", cl::desc("Splits all EH code and it's descendants by default."), cl::init(false), cl::Hidden)
static SmallVector< BBClusterInfo > createBBClusterInfoForFunction(MachineFunction &MF, const BasicBlockMatchingAndInference &BMI)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
Declares methods and data structures for code layout algorithms.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
SmallVector< MachineOperand, 4 > Cond
#define I(x, y, z)
Definition MD5.cpp:57
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
std::optional< WeightInfo > getWeightInfo(StringRef FuncName) const
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
bool hasProfileData() const
Return true if the function is annotated with profile data.
Definition Function.h:313
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
Tuple of metadata.
Definition Metadata.h:1505
bool isEHPad() const
Returns true if the block is a landing pad.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
LLVM_ABI bool isEntryBlock() const
Returns true if this is the entry block of the function.
void setSectionID(MBBSectionID V)
Sets the section ID for this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const MachineBasicBlock *MBB) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void setBBSectionsType(BasicBlockSection V)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool hasBBSections() const
Returns true if this function has basic block sections enabled.
Function & getFunction()
Return the LLVM function that this machine code represents.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
const MachineBasicBlock & front() const
void assignBeginEndSections()
Assign IsBeginSection IsEndSection fields for basic blocks in this function.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
bool hasCSInstrumentationProfile() const
Returns true if module M has context sensitive instrumentation profile.
bool hasInstrumentationProfile() const
Returns true if module M has instrumentation profile.
bool hasSampleProfile() const
Returns true if module M has sample profile.
LLVM_ABI bool isColdCountNthPercentile(int PercentileCutoff, uint64_t C) const
Returns true if count C is considered cold with regard to a given cold percentile cutoff value.
bool isFunctionHotInCallGraph(const FuncT *F, BFIT &BFI) const
Returns true if F contains hot code.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
virtual void insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const
Insert a noop into the instruction stream at the specified point.
TargetOptions Options
llvm::BasicBlockSection getBBSectionsType() const
If basic blocks should be emitted into their own section, corresponding to -fbasic-block-sections.
FunctionSplittingMode FunctionSplitting
Which functions are eligible for late function splitting.
virtual const TargetInstrInfo * getInstrInfo() const
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI MachineFunctionPass * createBasicBlockSectionsPass(bool SplitWithPGO=false)
createBasicBlockSections Pass - This pass assigns sections to machine basic blocks and is enabled wit...
LLVM_ABI void initializeBasicBlockSectionsPass(PassRegistry &)
static void computeEHOnlyBlocks(FunctionT &F, DenseSet< BlockT * > &EHBlocks)
Compute a list of blocks that are only reachable via EH paths.
Definition EHUtils.h:18
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
LLVM_ABI bool hasInstrProfHashMismatch(MachineFunction &MF)
This checks if the source of this function has drifted since this binary was profiled previously.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
SmallPtrSet< SUnit *, 8 > ClusterInfo
Keep record of which SUnit are in the same cluster group.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI void avoidZeroOffsetLandingPad(MachineFunction &MF)
LLVM_ABI cl::opt< std::string > BBSectionsColdTextPrefix
function_ref< bool(const MachineBasicBlock &, const MachineBasicBlock &)> MachineBasicBlockComparator
LLVM_ABI void sortBasicBlocksAndUpdateBranches(MachineFunction &MF, MachineBasicBlockComparator MBBCmp)
#define N
LLVM_ABI static const MBBSectionID ExceptionSectionID
LLVM_ABI static const MBBSectionID ColdSectionID