81#define DEBUG_TYPE "block-placement"
83STATISTIC(NumCondBranches,
"Number of conditional branches");
84STATISTIC(NumUncondBranches,
"Number of unconditional branches");
86 "Potential frequency of taking conditional branches");
88 "Potential frequency of taking unconditional branches");
92 cl::desc(
"Force the alignment of all blocks in the function in log2 format "
93 "(e.g 4 means align on 16B boundaries)."),
97 "align-all-nofallthru-blocks",
98 cl::desc(
"Force the alignment of all blocks that have no fall-through "
99 "predecessors (i.e. don't add nops that are executed). In log2 "
100 "format (e.g 4 means align on 16B boundaries)."),
104 "max-bytes-for-alignment",
105 cl::desc(
"Forces the maximum bytes allowed to be emitted when padding for "
110 "block-placement-predecessor-limit",
111 cl::desc(
"For blocks with more predecessors, certain layout optimizations"
112 "will be disabled to prevent quadratic compile time."),
117 "block-placement-exit-block-bias",
118 cl::desc(
"Block frequency percentage a loop exit block needs "
119 "over the original exit to be considered the new exit."),
126 "loop-to-cold-block-ratio",
127 cl::desc(
"Outline loop blocks from loop chain if (frequency of loop) / "
128 "(frequency of block) is greater than this ratio"),
133 cl::desc(
"Force outlining cold blocks from loops."),
138 cl::desc(
"Model the cost of loop rotation more "
139 "precisely by using profile data."),
144 cl::desc(
"Force the use of precise cost "
145 "loop rotation strategy."),
150 cl::desc(
"Cost that models the probabilistic risk of an instruction "
151 "misfetch due to a jump comparing to falling through, whose cost "
156 cl::desc(
"Cost of jump instructions."),
160 cl::desc(
"Perform tail duplication during placement. "
161 "Creates more fallthrough opportunities in "
162 "outline branches."),
167 cl::desc(
"Perform branch folding during placement. "
168 "Reduces code size."),
173 "tail-dup-placement-threshold",
174 cl::desc(
"Instruction cutoff for tail duplication during layout. "
175 "Tail merging during layout is forced to have a threshold "
176 "that won't conflict."),
181 "tail-dup-placement-aggressive-threshold",
182 cl::desc(
"Instruction cutoff for aggressive tail duplication during "
183 "layout. Used at -O3. Tail merging during layout is forced to "
184 "have a threshold that won't conflict."),
189 "tail-dup-placement-penalty",
191 "Cost penalty for blocks that can avoid breaking CFG by copying. "
192 "Copying can increase fallthrough, but it also increases icache "
193 "pressure. This parameter controls the penalty to account for that. "
194 "Percent as integer."),
199 "tail-dup-profile-percent-threshold",
200 cl::desc(
"If profile count information is used in tail duplication cost "
201 "model, the gained fall through number from tail duplication "
202 "should be at least this percent of hot count."),
207 "triangle-chain-count",
208 cl::desc(
"Number of triangle-shaped-CFG's that need to be in a row for the "
209 "triangle tail duplication heuristic to kick in. 0 to disable."),
218 "renumber-blocks-before-view",
220 "If true, basic blocks are re-numbered before MBP layout is printed "
221 "into a dot graph. Only used when a function is being printed."),
225 "ext-tsp-block-placement-max-blocks",
226 cl::desc(
"Maximum number of basic blocks in a function to run ext-TSP "
233 cl::desc(
"Use ext-tsp for size-aware block placement."));
279 BlockToChainMapType &BlockToChain;
288 : Blocks(1, BB), BlockToChain(BlockToChain) {
289 assert(BB &&
"Cannot create a chain with a null basic block");
290 BlockToChain[BB] =
this;
306 for (
iterator i = begin(); i != end(); ++i) {
322 assert(BB &&
"Can't merge a null block.");
323 assert(!Blocks.
empty() &&
"Can't merge into an empty chain.");
327 assert(!BlockToChain[BB] &&
328 "Passed chain is null, but BB has entry in BlockToChain.");
330 BlockToChain[BB] =
this;
334 assert(BB == *Chain->begin() &&
"Passed BB is not head of Chain.");
335 assert(Chain->begin() != Chain->end());
341 assert(BlockToChain[ChainBB] == Chain &&
"Incoming blocks not in chain.");
342 BlockToChain[ChainBB] =
this;
363 unsigned UnscheduledPredecessors = 0;
366class MachineBlockPlacement {
368 using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
371 struct BlockAndTailDupResult {
372 MachineBasicBlock *BB =
nullptr;
377 struct WeightedEdge {
378 BlockFrequency Weight;
379 MachineBasicBlock *Src =
nullptr;
380 MachineBasicBlock *Dest =
nullptr;
384 struct WorkListEntry {
387 MachineBasicBlock *BB;
396 unsigned NextWorkListSeq = 0;
399 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
405 const MachineBranchProbabilityInfo *MBPI =
nullptr;
408 std::unique_ptr<MBFIWrapper> MBFI;
411 MachineLoopInfo *MLI =
nullptr;
416 MachineBasicBlock *PreferredLoopExit =
nullptr;
419 const TargetInstrInfo *TII =
nullptr;
422 const TargetLoweringBase *TLI =
nullptr;
425 MachinePostDominatorTree *MPDT =
nullptr;
427 ProfileSummaryInfo *PSI =
nullptr;
440 TailDuplicator TailDup;
443 BlockFrequency DupThreshold;
445 unsigned TailDupSize;
449 bool UseProfileCount =
false;
458 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
466 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
473 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
478 BlockFrequency getBlockCountOrFrequency(
const MachineBasicBlock *BB) {
479 if (UseProfileCount) {
480 auto Count = MBFI->getBlockProfileCount(BB);
482 return BlockFrequency(*
Count);
484 return BlockFrequency(0);
486 return MBFI->getBlockFreq(BB);
490 BlockFrequency scaleThreshold(MachineBasicBlock *BB);
491 void initTailDupThreshold();
495 void markChainSuccessors(
const BlockChain &Chain,
496 const MachineBasicBlock *LoopHeaderBB,
497 const BlockFilterSet *BlockFilter =
nullptr);
501 void markBlockSuccessors(
const BlockChain &Chain,
const MachineBasicBlock *BB,
502 const MachineBasicBlock *LoopHeaderBB,
503 const BlockFilterSet *BlockFilter =
nullptr);
506 collectViableSuccessors(
const MachineBasicBlock *BB,
const BlockChain &Chain,
507 const BlockFilterSet *BlockFilter,
508 SmallVector<MachineBasicBlock *, 4> &Successors);
509 bool isBestSuccessor(MachineBasicBlock *BB, MachineBasicBlock *
Pred,
510 BlockFilterSet *BlockFilter);
511 void findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock *> &Candidates,
512 MachineBasicBlock *BB,
513 BlockFilterSet *BlockFilter);
514 bool repeatedlyTailDuplicateBlock(
515 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
516 const MachineBasicBlock *LoopHeaderBB, BlockChain &Chain,
517 BlockFilterSet *BlockFilter,
521 maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred,
522 BlockChain &Chain, BlockFilterSet *BlockFilter,
525 bool &DuplicatedToLPred);
526 bool hasBetterLayoutPredecessor(
const MachineBasicBlock *BB,
527 const MachineBasicBlock *Succ,
528 const BlockChain &SuccChain,
529 BranchProbability SuccProb,
530 BranchProbability RealSuccProb,
531 const BlockChain &Chain,
532 const BlockFilterSet *BlockFilter);
533 BlockAndTailDupResult selectBestSuccessor(
const MachineBasicBlock *BB,
534 const BlockChain &Chain,
535 const BlockFilterSet *BlockFilter);
536 MachineBasicBlock *selectBestCandidateBlock(
const BlockChain &Chain,
538 static bool isWorseCandidate(
bool IsEHPad,
const WorkListEntry &
A,
539 const WorkListEntry &
B);
540 void addToWorkList(MachineBasicBlock *BB);
542 getFirstUnplacedBlock(
const BlockChain &PlacedChain,
545 getFirstUnplacedBlock(
const BlockChain &PlacedChain,
547 const BlockFilterSet *BlockFilter);
554 void fillWorkLists(
const MachineBasicBlock *
MBB,
555 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
556 const BlockFilterSet *BlockFilter);
558 void buildChain(
const MachineBasicBlock *BB, BlockChain &Chain,
559 BlockFilterSet *BlockFilter =
nullptr);
560 bool canMoveBottomBlockToTop(
const MachineBasicBlock *BottomBlock,
561 const MachineBasicBlock *OldTop);
562 bool hasViableTopFallthrough(
const MachineBasicBlock *Top,
563 const BlockFilterSet &LoopBlockSet);
564 BlockFrequency TopFallThroughFreq(
const MachineBasicBlock *Top,
565 const BlockFilterSet &LoopBlockSet);
566 BlockFrequency FallThroughGains(
const MachineBasicBlock *NewTop,
567 const MachineBasicBlock *OldTop,
568 const MachineBasicBlock *ExitBB,
569 const BlockFilterSet &LoopBlockSet);
570 MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop,
571 const MachineLoop &L,
572 const BlockFilterSet &LoopBlockSet);
573 MachineBasicBlock *findBestLoopTop(
const MachineLoop &L,
574 const BlockFilterSet &LoopBlockSet);
575 MachineBasicBlock *findBestLoopExit(
const MachineLoop &L,
576 const BlockFilterSet &LoopBlockSet,
577 BlockFrequency &ExitFreq);
578 BlockFilterSet collectLoopBlockSet(
const MachineLoop &L);
579 void buildLoopChains(
const MachineLoop &L);
580 void rotateLoop(BlockChain &LoopChain,
const MachineBasicBlock *ExitingBB,
581 BlockFrequency ExitFreq,
const BlockFilterSet &LoopBlockSet);
582 void rotateLoopWithProfile(BlockChain &LoopChain,
const MachineLoop &L,
583 const BlockFilterSet &LoopBlockSet);
584 void buildCFGChains();
585 void optimizeBranches();
589 bool shouldTailDuplicate(MachineBasicBlock *BB);
592 bool isProfitableToTailDup(
const MachineBasicBlock *BB,
593 const MachineBasicBlock *Succ,
594 BranchProbability QProb,
const BlockChain &Chain,
595 const BlockFilterSet *BlockFilter);
598 bool isTrellis(
const MachineBasicBlock *BB,
599 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
600 const BlockChain &Chain,
const BlockFilterSet *BlockFilter);
603 BlockAndTailDupResult getBestTrellisSuccessor(
604 const MachineBasicBlock *BB,
605 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
606 BranchProbability AdjustedSumProb,
const BlockChain &Chain,
607 const BlockFilterSet *BlockFilter);
610 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
611 const MachineBasicBlock *BB,
616 bool canTailDuplicateUnplacedPreds(
const MachineBasicBlock *BB,
617 MachineBasicBlock *Succ,
618 const BlockChain &Chain,
619 const BlockFilterSet *BlockFilter);
623 void precomputeTriangleChains();
626 void applyExtTsp(
bool OptForSize);
629 void assignBlockOrder(
const std::vector<const MachineBasicBlock *> &NewOrder);
632 void createCFGChainExtTsp();
635 MachineBlockPlacement(
const MachineBranchProbabilityInfo *MBPI,
636 MachineLoopInfo *MLI, ProfileSummaryInfo *PSI,
637 std::unique_ptr<MBFIWrapper> MBFI,
638 MachinePostDominatorTree *MPDT,
bool AllowTailMerge)
639 : MBPI(MBPI), MBFI(std::
move(MBFI)), MLI(MLI), MPDT(MPDT), PSI(PSI),
640 AllowTailMerge(AllowTailMerge) {};
653 MachineBlockPlacementLegacy() : MachineFunctionPass(ID) {}
660 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
661 auto MBFI = std::make_unique<MBFIWrapper>(
662 getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI());
663 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
664 auto *MPDT = MachineBlockPlacement::allowTailDupPlacement(MF)
665 ? &getAnalysis<MachinePostDominatorTreeWrapperPass>()
668 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
669 auto *PassConfig = &getAnalysis<TargetPassConfig>();
670 bool AllowTailMerge = PassConfig->getEnableTailMerge();
671 return MachineBlockPlacement(MBPI, MLI, PSI, std::move(MBFI), MPDT,
676 void getAnalysisUsage(AnalysisUsage &AU)
const override {
677 AU.
addRequired<MachineBranchProbabilityInfoWrapperPass>();
678 AU.
addRequired<MachineBlockFrequencyInfoWrapperPass>();
680 AU.
addRequired<MachinePostDominatorTreeWrapperPass>();
691char MachineBlockPlacementLegacy::ID = 0;
696 "Branch Probability Basic Block Placement",
false,
false)
713 OS <<
" ('" << BB->
getName() <<
"')";
724void MachineBlockPlacement::markChainSuccessors(
726 const BlockFilterSet *BlockFilter) {
729 for (MachineBasicBlock *
MBB : Chain) {
730 markBlockSuccessors(Chain,
MBB, LoopHeaderBB, BlockFilter);
740void MachineBlockPlacement::markBlockSuccessors(
741 const BlockChain &Chain,
const MachineBasicBlock *
MBB,
742 const MachineBasicBlock *LoopHeaderBB,
const BlockFilterSet *BlockFilter) {
748 if (BlockFilter && !BlockFilter->count(Succ))
750 BlockChain &SuccChain = *BlockToChain[Succ];
752 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
757 if (SuccChain.UnscheduledPredecessors == 0 ||
758 --SuccChain.UnscheduledPredecessors > 0)
761 addToWorkList(*SuccChain.begin());
769BranchProbability MachineBlockPlacement::collectViableSuccessors(
770 const MachineBasicBlock *BB,
const BlockChain &Chain,
771 const BlockFilterSet *BlockFilter,
772 SmallVector<MachineBasicBlock *, 4> &Successors) {
790 for (MachineBasicBlock *Succ : BB->
successors()) {
791 bool SkipSucc =
false;
792 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
795 BlockChain *SuccChain = BlockToChain[Succ];
796 if (SuccChain == &Chain) {
798 }
else if (Succ != *SuccChain->begin()) {
800 <<
" -> Mid chain!\n");
810 return AdjustedSumProb;
815static BranchProbability
821 if (SuccProbN >= SuccProbD)
836 if (Successors.
count(&BB))
839 if (!Successors.
count(Succ))
847bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
868 return (Gain / ThresholdProb) >= EntryFreq;
876bool MachineBlockPlacement::isProfitableToTailDup(
877 const MachineBasicBlock *BB,
const MachineBasicBlock *Succ,
878 BranchProbability QProb,
const BlockChain &Chain,
879 const BlockFilterSet *BlockFilter) {
903 MachineBasicBlock *PDom =
nullptr;
904 SmallVector<MachineBasicBlock *, 4> SuccSuccs;
906 auto AdjustedSuccSumProb =
907 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
909 auto BBFreq = MBFI->getBlockFreq(BB);
910 auto SuccFreq = MBFI->getBlockFreq(Succ);
911 BlockFrequency
P =
BBFreq * PProb;
912 BlockFrequency Qout =
BBFreq * QProb;
913 BlockFrequency EntryFreq = MBFI->getEntryFreq();
916 if (SuccSuccs.
size() == 0)
921 for (MachineBasicBlock *SuccSucc : SuccSuccs) {
923 if (Prob > BestSuccSucc)
933 auto SuccBestPred = BlockFrequency(0);
934 for (MachineBasicBlock *SuccPred : Succ->
predecessors()) {
935 if (SuccPred == Succ || SuccPred == BB ||
936 BlockToChain[SuccPred] == &Chain ||
937 (BlockFilter && !BlockFilter->count(SuccPred)))
941 if (Freq > SuccBestPred)
945 BlockFrequency Qin = SuccBestPred;
966 BranchProbability UProb = BestSuccSucc;
967 BranchProbability VProb = AdjustedSuccSumProb - UProb;
968 BlockFrequency
F = SuccFreq - Qin;
969 BlockFrequency
V = SuccFreq * VProb;
970 BlockFrequency QinU = std::min(Qin,
F) * UProb;
971 BlockFrequency BaseCost =
P +
V;
972 BlockFrequency DupCost = Qout + QinU + std::max(Qin,
F) * VProb;
976 BranchProbability VProb = AdjustedSuccSumProb - UProb;
977 BlockFrequency
U = SuccFreq * UProb;
978 BlockFrequency
V = SuccFreq * VProb;
979 BlockFrequency
F = SuccFreq - Qin;
1009 if (UProb > AdjustedSuccSumProb / 2 &&
1010 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
1011 Chain, BlockFilter))
1014 (
P +
V), (Qout + std::max(Qin,
F) * VProb + std::min(Qin,
F) * UProb),
1018 (Qout + std::min(Qin,
F) * AdjustedSuccSumProb +
1019 std::max(Qin,
F) * UProb),
1030bool MachineBlockPlacement::isTrellis(
1031 const MachineBasicBlock *BB,
1032 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
1033 const BlockChain &Chain,
const BlockFilterSet *BlockFilter) {
1042 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
1044 for (MachineBasicBlock *Succ : ViableSuccs) {
1053 if (Successors.count(SuccPred)) {
1055 for (MachineBasicBlock *CheckSucc : SuccPred->successors())
1056 if (!Successors.count(CheckSucc))
1060 const BlockChain *PredChain = BlockToChain[SuccPred];
1061 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
1062 PredChain == &Chain || PredChain == BlockToChain[Succ])
1066 if (!SeenPreds.
insert(SuccPred).second)
1084std::pair<MachineBlockPlacement::WeightedEdge,
1085 MachineBlockPlacement::WeightedEdge>
1086MachineBlockPlacement::getBestNonConflictingEdges(
1087 const MachineBasicBlock *BB,
1097 auto Cmp = [](WeightedEdge
A, WeightedEdge
B) {
return A.Weight >
B.Weight; };
1101 auto BestA = Edges[0].begin();
1102 auto BestB = Edges[1].begin();
1105 if (BestA->Src == BestB->Src) {
1107 auto SecondBestA = std::next(BestA);
1108 auto SecondBestB = std::next(BestB);
1109 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
1110 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
1111 if (BestAScore < BestBScore)
1112 BestA = SecondBestA;
1114 BestB = SecondBestB;
1117 if (BestB->Src == BB)
1119 return std::make_pair(*BestA, *BestB);
1129MachineBlockPlacement::BlockAndTailDupResult
1130MachineBlockPlacement::getBestTrellisSuccessor(
1131 const MachineBasicBlock *BB,
1132 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
1133 BranchProbability AdjustedSumProb,
const BlockChain &Chain,
1134 const BlockFilterSet *BlockFilter) {
1136 BlockAndTailDupResult
Result = {
nullptr,
false};
1143 if (Successors.
size() != 2 || ViableSuccs.
size() != 2)
1149 for (
auto *Succ : ViableSuccs) {
1150 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
1152 if (SuccPred != BB) {
1153 if (BlockFilter && !BlockFilter->count(SuccPred))
1155 const BlockChain *SuccPredChain = BlockToChain[SuccPred];
1156 if (SuccPredChain == &Chain || SuccPredChain == BlockToChain[Succ])
1159 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
1161 Edges[SuccIndex].
push_back({EdgeFreq, SuccPred, Succ});
1167 WeightedEdge BestA, BestB;
1168 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
1170 if (BestA.Src != BB) {
1174 LLVM_DEBUG(
dbgs() <<
"Trellis, but not one of the chosen edges.\n");
1181 if (BestA.Dest == BestB.Src) {
1184 MachineBasicBlock *Succ1 = BestA.Dest;
1185 MachineBasicBlock *Succ2 = BestB.Dest;
1187 if (allowTailDupPlacement(*
F) && shouldTailDuplicate(Succ2) &&
1188 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
1190 Chain, BlockFilter)) {
1194 <<
", probability: " << Succ2Prob
1195 <<
" (Tail Duplicate)\n");
1197 Result.ShouldTailDup =
true;
1203 ComputedEdges[BestB.Src] = {BestB.Dest,
false};
1205 auto TrellisSucc = BestA.Dest;
1209 <<
", probability: " << SuccProb <<
" (Trellis)\n");
1217bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
1218 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1219 const BlockChain &Chain,
const BlockFilterSet *BlockFilter) {
1220 if (!shouldTailDuplicate(Succ))
1224 bool Duplicate =
true;
1226 unsigned int NumDup = 0;
1235 if (
Pred == BB || (BlockFilter && !BlockFilter->count(
Pred)) ||
1286 if (
F->getFunction().hasProfileData())
1317 if ((NumDup > Succ->
succ_size()) || !Duplicate)
1340void MachineBlockPlacement::precomputeTriangleChains() {
1341 struct TriangleChain {
1342 std::vector<MachineBasicBlock *> Edges;
1344 TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
1345 : Edges({src, dst}) {}
1347 void append(MachineBasicBlock *dst) {
1348 assert(getKey()->isSuccessor(dst) &&
1349 "Attempting to append a block that is not a successor.");
1350 Edges.push_back(dst);
1353 unsigned count()
const {
return Edges.size() - 1; }
1355 MachineBasicBlock *getKey()
const {
return Edges.back(); }
1364 DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
1365 for (MachineBasicBlock &BB : *
F) {
1369 MachineBasicBlock *PDom =
nullptr;
1370 for (MachineBasicBlock *Succ : BB.
successors()) {
1378 if (PDom ==
nullptr)
1385 if (!shouldTailDuplicate(PDom))
1387 bool CanTailDuplicate =
true;
1394 CanTailDuplicate =
false;
1400 if (!CanTailDuplicate)
1407 auto Found = TriangleChainMap.
find(&BB);
1410 if (Found != TriangleChainMap.
end()) {
1411 TriangleChain Chain = std::move(Found->second);
1412 TriangleChainMap.
erase(Found);
1414 TriangleChainMap.
insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1416 auto InsertResult = TriangleChainMap.
try_emplace(PDom, &BB, PDom);
1417 assert(InsertResult.second &&
"Block seen twice.");
1425 for (
auto &ChainPair : TriangleChainMap) {
1426 TriangleChain &Chain = ChainPair.second;
1432 MachineBasicBlock *dst = Chain.Edges.back();
1433 Chain.Edges.pop_back();
1434 for (MachineBasicBlock *src :
reverse(Chain.Edges)) {
1437 <<
" as pre-computed based on triangles.\n");
1439 auto InsertResult = ComputedEdges.
insert({src, {dst,
true}});
1440 assert(InsertResult.second &&
"Block seen twice.");
1450static BranchProbability
1486bool MachineBlockPlacement::hasBetterLayoutPredecessor(
1487 const MachineBasicBlock *BB,
const MachineBasicBlock *Succ,
1488 const BlockChain &SuccChain, BranchProbability SuccProb,
1489 BranchProbability RealSuccProb,
const BlockChain &Chain,
1490 const BlockFilterSet *BlockFilter) {
1493 if (SuccChain.UnscheduledPredecessors == 0)
1618 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1619 bool BadCFGConflict =
false;
1622 BlockChain *PredChain = BlockToChain[
Pred];
1623 if (
Pred == Succ || PredChain == &SuccChain ||
1624 (BlockFilter && !BlockFilter->count(
Pred)) || PredChain == &Chain ||
1625 Pred != *std::prev(PredChain->end()) ||
1644 BlockFrequency PredEdgeFreq =
1646 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.
getCompl()) {
1647 BadCFGConflict =
true;
1652 if (BadCFGConflict) {
1654 << SuccProb <<
" (prob) (non-cold CFG conflict)\n");
1671MachineBlockPlacement::BlockAndTailDupResult
1672MachineBlockPlacement::selectBestSuccessor(
const MachineBasicBlock *BB,
1673 const BlockChain &Chain,
1674 const BlockFilterSet *BlockFilter) {
1677 BlockAndTailDupResult BestSucc = {
nullptr,
false};
1680 SmallVector<MachineBasicBlock *, 4> Successors;
1681 auto AdjustedSumProb =
1682 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1689 auto FoundEdge = ComputedEdges.
find(BB);
1690 if (FoundEdge != ComputedEdges.
end()) {
1691 BlockAndTailDupResult
Result = FoundEdge->second;
1692 ComputedEdges.
erase(FoundEdge);
1693 BlockChain *SuccChain = BlockToChain[
Result.BB];
1695 (!BlockFilter || BlockFilter->count(
Result.BB)) &&
1696 SuccChain != &Chain &&
Result.BB == *SuccChain->begin())
1702 if (isTrellis(BB, Successors, Chain, BlockFilter))
1703 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1711 for (MachineBasicBlock *Succ : Successors) {
1713 BranchProbability SuccProb =
1716 BlockChain &SuccChain = *BlockToChain[Succ];
1719 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
1720 Chain, BlockFilter)) {
1722 if (allowTailDupPlacement(*
F) && shouldTailDuplicate(Succ))
1729 <<
", probability: " << SuccProb
1730 << (SuccChain.UnscheduledPredecessors != 0 ?
" (CFG break)" :
"")
1733 if (BestSucc.BB && BestProb >= SuccProb) {
1740 BestProb = SuccProb;
1748 [](std::tuple<BranchProbability, MachineBasicBlock *> L,
1749 std::tuple<BranchProbability, MachineBasicBlock *> R) {
1750 return std::get<0>(L) > std::get<0>(R);
1752 for (
auto &Tup : DupCandidates) {
1753 BranchProbability DupProb;
1754 MachineBasicBlock *Succ;
1755 std::tie(DupProb, Succ) = Tup;
1756 if (DupProb < BestProb)
1758 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter) &&
1759 (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
1761 <<
", probability: " << DupProb
1762 <<
" (Tail Duplicate)\n");
1764 BestSucc.ShouldTailDup =
true;
1777bool MachineBlockPlacement::isWorseCandidate(
bool IsEHPad,
1778 const WorkListEntry &
A,
1779 const WorkListEntry &
B) {
1780 if (
A.Freq !=
B.Freq) {
1799 return IsEHPad ?
A.Freq >
B.Freq :
A.Freq <
B.Freq;
1802 return IsEHPad ?
A.Seq <
B.Seq :
A.Seq >
B.Seq;
1806void MachineBlockPlacement::addToWorkList(MachineBasicBlock *BB) {
1808 SmallVectorImpl<WorkListEntry> &WorkList =
1809 IsEHPad ? EHPadWorkList : BlockWorkList;
1810 WorkList.
push_back({MBFI->getBlockFreq(BB), NextWorkListSeq++, BB});
1811 std::push_heap(WorkList.
begin(), WorkList.
end(),
1812 [IsEHPad](
const WorkListEntry &
A,
const WorkListEntry &
B) {
1813 return isWorseCandidate(IsEHPad, A, B);
1828MachineBlockPlacement::selectBestCandidateBlock(
const BlockChain &Chain,
1830 SmallVectorImpl<WorkListEntry> &WorkList =
1831 IsEHPad ? EHPadWorkList : BlockWorkList;
1832 while (!WorkList.
empty()) {
1833 const BlockChain *SuccChain = BlockToChain.
lookup(WorkList.
front().BB);
1834 bool IsStale = !SuccChain || SuccChain == &Chain;
1837 std::pop_heap(WorkList.
begin(), WorkList.
end(),
1838 [IsEHPad](
const WorkListEntry &
A,
const WorkListEntry &
B) {
1839 return isWorseCandidate(IsEHPad, A, B);
1844 if (WorkList.
empty())
1848 MachineBasicBlock *BestBlock = WorkList.
front().BB;
1850 "EHPad mismatch between block and work list.");
1851 assert(BlockToChain[BestBlock]->UnscheduledPredecessors == 0 &&
1852 "Found CFG-violating block");
1854#ifdef EXPENSIVE_CHECKS
1855 for (
const WorkListEntry &
E : WorkList) {
1856 const BlockChain *
C = BlockToChain.
lookup(
E.BB);
1857 bool IsStale = !
C ||
C == &Chain;
1860 assert(
E.BB->isEHPad() == IsEHPad &&
1861 "EHPad mismatch between block and work list.");
1862 assert(
C->UnscheduledPredecessors == 0 &&
"Found CFG-violating block");
1867 for (
const WorkListEntry &
E : WorkList) {
1868 const BlockChain *
C = BlockToChain.
lookup(
E.BB);
1869 bool IsStale = !
C ||
C == &Chain;
1887MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1888 const BlockChain &PlacedChain,
1893 if (BlockChain *Chain = BlockToChain[&*
I]; Chain != &PlacedChain) {
1894 PrevUnplacedBlockIt =
I;
1898 return *Chain->begin();
1914MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1915 const BlockChain &PlacedChain,
1916 BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
1917 const BlockFilterSet *BlockFilter) {
1919 for (; PrevUnplacedBlockInFilterIt != BlockFilter->end();
1920 ++PrevUnplacedBlockInFilterIt) {
1921 BlockChain *
C = BlockToChain[*PrevUnplacedBlockInFilterIt];
1922 if (
C != &PlacedChain) {
1929void MachineBlockPlacement::fillWorkLists(
1930 const MachineBasicBlock *
MBB, SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
1931 const BlockFilterSet *BlockFilter =
nullptr) {
1932 BlockChain &Chain = *BlockToChain[
MBB];
1933 if (!UpdatedPreds.
insert(&Chain).second)
1937 Chain.UnscheduledPredecessors == 0 &&
1938 "Attempting to place block with unscheduled predecessors in worklist.");
1939 for (MachineBasicBlock *ChainBB : Chain) {
1940 assert(BlockToChain[ChainBB] == &Chain &&
1941 "Block in chain doesn't match BlockToChain map.");
1942 for (MachineBasicBlock *
Pred : ChainBB->predecessors()) {
1943 if (BlockFilter && !BlockFilter->count(
Pred))
1945 if (BlockToChain[
Pred] == &Chain)
1947 ++Chain.UnscheduledPredecessors;
1951 if (Chain.UnscheduledPredecessors != 0)
1954 addToWorkList(*Chain.begin());
1957void MachineBlockPlacement::buildChain(
const MachineBasicBlock *HeadBB,
1959 BlockFilterSet *BlockFilter) {
1960 assert(HeadBB &&
"BB must not be null.\n");
1961 assert(BlockToChain[HeadBB] == &Chain &&
"BlockToChainMap mis-match.\n");
1963 BlockFilterSet::iterator PrevUnplacedBlockInFilterIt;
1965 PrevUnplacedBlockInFilterIt = BlockFilter->begin();
1967 const MachineBasicBlock *LoopHeaderBB = HeadBB;
1968 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
1969 MachineBasicBlock *BB = *std::prev(Chain.end());
1971 assert(BB &&
"null block found at end of chain in loop.");
1972 assert(BlockToChain[BB] == &Chain &&
"BlockToChainMap mis-match in loop.");
1973 assert(*std::prev(Chain.end()) == BB &&
"BB Not found at end of chain.");
1977 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1978 MachineBasicBlock *BestSucc =
Result.BB;
1979 bool ShouldTailDup =
Result.ShouldTailDup;
1980 if (allowTailDupPlacement(*
F))
1981 ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(
1982 BB, BestSucc, Chain, BlockFilter));
1988 BestSucc = selectBestCandidateBlock(Chain,
false);
1990 BestSucc = selectBestCandidateBlock(Chain,
true);
1994 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockInFilterIt,
1997 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt);
2001 LLVM_DEBUG(
dbgs() <<
"Unnatural loop CFG detected, forcibly merging the "
2002 "layout successor until the CFG reduces\n");
2007 if (allowTailDupPlacement(*
F) && BestSucc && ShouldTailDup) {
2008 repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
2009 BlockFilter, PrevUnplacedBlockIt,
2010 PrevUnplacedBlockInFilterIt);
2018 BlockChain &SuccChain = *BlockToChain[BestSucc];
2021 SuccChain.UnscheduledPredecessors = 0;
2024 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
2025 Chain.merge(BestSucc, &SuccChain);
2026 BB = *std::prev(Chain.end());
2047bool MachineBlockPlacement::canMoveBottomBlockToTop(
2048 const MachineBasicBlock *BottomBlock,
const MachineBasicBlock *OldTop) {
2052 if (
Pred->succ_size() != 2)
2055 MachineBasicBlock *OtherBB = *
Pred->succ_begin();
2056 if (OtherBB == BottomBlock)
2057 OtherBB = *
Pred->succ_rbegin();
2058 if (OtherBB == OldTop)
2066MachineBlockPlacement::TopFallThroughFreq(
const MachineBasicBlock *Top,
2067 const BlockFilterSet &LoopBlockSet) {
2068 BlockFrequency MaxFreq = BlockFrequency(0);
2070 BlockChain *PredChain = BlockToChain[
Pred];
2071 if (!LoopBlockSet.count(
Pred) &&
2072 (!PredChain ||
Pred == *std::prev(PredChain->end()))) {
2077 for (MachineBasicBlock *Succ :
Pred->successors()) {
2079 BlockChain *SuccChain = BlockToChain[Succ];
2082 if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) &&
2083 (!SuccChain || Succ == *SuccChain->begin())) {
2089 BlockFrequency EdgeFreq =
2091 if (EdgeFreq > MaxFreq)
2120BlockFrequency MachineBlockPlacement::FallThroughGains(
2121 const MachineBasicBlock *NewTop,
const MachineBasicBlock *OldTop,
2122 const MachineBasicBlock *ExitBB,
const BlockFilterSet &LoopBlockSet) {
2123 BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet);
2124 BlockFrequency FallThrough2Exit = BlockFrequency(0);
2128 BlockFrequency BackEdgeFreq =
2132 MachineBasicBlock *BestPred =
nullptr;
2133 BlockFrequency FallThroughFromPred = BlockFrequency(0);
2135 if (!LoopBlockSet.count(
Pred))
2137 BlockChain *PredChain = BlockToChain[
Pred];
2138 if (!PredChain ||
Pred == *std::prev(PredChain->end())) {
2139 BlockFrequency EdgeFreq =
2141 if (EdgeFreq > FallThroughFromPred) {
2142 FallThroughFromPred = EdgeFreq;
2150 BlockFrequency NewFreq = BlockFrequency(0);
2152 for (MachineBasicBlock *Succ : BestPred->
successors()) {
2153 if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ))
2157 BlockChain *SuccChain = BlockToChain[Succ];
2158 if ((SuccChain && (Succ != *SuccChain->begin())) ||
2159 (SuccChain == BlockToChain[BestPred]))
2161 BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) *
2163 if (EdgeFreq > NewFreq)
2166 BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) *
2168 if (NewFreq > OrigEdgeFreq) {
2172 NewFreq = BlockFrequency(0);
2173 FallThroughFromPred = BlockFrequency(0);
2177 BlockFrequency
Result = BlockFrequency(0);
2178 BlockFrequency Gains = BackEdgeFreq + NewFreq;
2179 BlockFrequency Lost =
2180 FallThrough2Top + FallThrough2Exit + FallThroughFromPred;
2208MachineBasicBlock *MachineBlockPlacement::findBestLoopTopHelper(
2209 MachineBasicBlock *OldTop,
const MachineLoop &L,
2210 const BlockFilterSet &LoopBlockSet) {
2214 BlockChain &HeaderChain = *BlockToChain[OldTop];
2215 if (!LoopBlockSet.count(*HeaderChain.begin()))
2217 if (OldTop != *HeaderChain.begin())
2223 BlockFrequency BestGains = BlockFrequency(0);
2224 MachineBasicBlock *BestPred =
nullptr;
2226 if (!LoopBlockSet.count(
Pred))
2228 if (
Pred ==
L.getHeader())
2231 <<
Pred->succ_size() <<
" successors, "
2233 if (
Pred->succ_size() > 2)
2236 MachineBasicBlock *OtherBB =
nullptr;
2237 if (
Pred->succ_size() == 2) {
2238 OtherBB = *
Pred->succ_begin();
2239 if (OtherBB == OldTop)
2240 OtherBB = *
Pred->succ_rbegin();
2243 if (!canMoveBottomBlockToTop(
Pred, OldTop))
2246 BlockFrequency Gains =
2247 FallThroughGains(
Pred, OldTop, OtherBB, LoopBlockSet);
2248 if ((Gains > BlockFrequency(0)) &&
2249 (Gains > BestGains ||
2250 ((Gains == BestGains) &&
Pred->isLayoutSuccessor(OldTop)))) {
2264 (*BestPred->
pred_begin())->succ_size() == 1 &&
2277MachineBlockPlacement::findBestLoopTop(
const MachineLoop &L,
2278 const BlockFilterSet &LoopBlockSet) {
2287 return L.getHeader();
2289 MachineBasicBlock *OldTop =
nullptr;
2290 MachineBasicBlock *NewTop =
L.getHeader();
2291 while (NewTop != OldTop) {
2293 NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet);
2294 if (NewTop != OldTop)
2295 ComputedEdges[NewTop] = {OldTop,
false};
2306MachineBlockPlacement::findBestLoopExit(
const MachineLoop &L,
2307 const BlockFilterSet &LoopBlockSet,
2308 BlockFrequency &ExitFreq) {
2317 BlockChain &HeaderChain = *BlockToChain[
L.getHeader()];
2318 if (!LoopBlockSet.count(*HeaderChain.begin()))
2321 BlockFrequency BestExitEdgeFreq;
2322 unsigned BestExitLoopDepth = 0;
2323 MachineBasicBlock *ExitingBB =
nullptr;
2327 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
2331 for (MachineBasicBlock *
MBB :
L.getBlocks()) {
2332 BlockChain &Chain = *BlockToChain[
MBB];
2335 if (
MBB != *std::prev(Chain.end()))
2342 MachineBasicBlock *OldExitingBB = ExitingBB;
2343 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
2344 bool HasLoopingSucc =
false;
2350 BlockChain &SuccChain = *BlockToChain[Succ];
2352 if (&Chain == &SuccChain) {
2359 if (LoopBlockSet.count(Succ)) {
2362 HasLoopingSucc =
true;
2366 unsigned SuccLoopDepth = 0;
2367 if (MachineLoop *ExitLoop = MLI->
getLoopFor(Succ)) {
2368 SuccLoopDepth = ExitLoop->getLoopDepth();
2369 if (ExitLoop->contains(&L))
2373 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(
MBB) * SuccProb;
2376 <<
getBlockName(Succ) <<
" [L:" << SuccLoopDepth <<
"] ("
2383 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
2384 ExitEdgeFreq > BestExitEdgeFreq ||
2386 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
2387 BestExitEdgeFreq = ExitEdgeFreq;
2392 if (!HasLoopingSucc) {
2394 ExitingBB = OldExitingBB;
2395 BestExitEdgeFreq = OldBestExitEdgeFreq;
2402 dbgs() <<
" No other candidate exit blocks, using loop header\n");
2405 if (
L.getNumBlocks() == 1) {
2406 LLVM_DEBUG(
dbgs() <<
" Loop has 1 block, using loop header as exit\n");
2413 if (!BlocksExitingToOuterLoop.
empty() &&
2414 !BlocksExitingToOuterLoop.
count(ExitingBB))
2419 ExitFreq = BestExitEdgeFreq;
2427bool MachineBlockPlacement::hasViableTopFallthrough(
2428 const MachineBasicBlock *Top,
const BlockFilterSet &LoopBlockSet) {
2430 BlockChain *PredChain = BlockToChain[
Pred];
2431 if (!LoopBlockSet.count(
Pred) &&
2432 (!PredChain ||
Pred == *std::prev(PredChain->end()))) {
2437 for (MachineBasicBlock *Succ :
Pred->successors()) {
2439 BlockChain *SuccChain = BlockToChain[Succ];
2442 if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
2460void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
2461 const MachineBasicBlock *ExitingBB,
2462 BlockFrequency ExitFreq,
2463 const BlockFilterSet &LoopBlockSet) {
2467 MachineBasicBlock *Top = *LoopChain.begin();
2468 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
2471 if (Bottom == ExitingBB)
2478 bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
2483 if (ViableTopFallthrough) {
2484 for (MachineBasicBlock *Succ : Bottom->
successors()) {
2485 BlockChain *SuccChain = BlockToChain[Succ];
2486 if (!LoopBlockSet.count(Succ) &&
2487 (!SuccChain || Succ == *SuccChain->begin()))
2493 BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet);
2494 if (FallThrough2Top >= ExitFreq)
2498 BlockChain::iterator ExitIt =
llvm::find(LoopChain, ExitingBB);
2499 if (ExitIt == LoopChain.end())
2521 if (ViableTopFallthrough) {
2522 assert(std::next(ExitIt) != LoopChain.end() &&
2523 "Exit should not be last BB");
2524 MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
2532 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
2548void MachineBlockPlacement::rotateLoopWithProfile(
2549 BlockChain &LoopChain,
const MachineLoop &L,
2550 const BlockFilterSet &LoopBlockSet) {
2551 auto RotationPos = LoopChain.end();
2552 MachineBasicBlock *ChainHeaderBB = *LoopChain.begin();
2562 auto ScaleBlockFrequency = [](BlockFrequency Freq,
2563 unsigned Scale) -> BlockFrequency {
2565 return BlockFrequency(0);
2568 return Freq / BranchProbability(1, Scale);
2574 BlockFrequency HeaderFallThroughCost(0);
2576 BlockChain *PredChain = BlockToChain[
Pred];
2577 if (!LoopBlockSet.count(
Pred) &&
2578 (!PredChain ||
Pred == *std::prev(PredChain->end()))) {
2579 auto EdgeFreq = MBFI->getBlockFreq(
Pred) *
2581 auto FallThruCost = ScaleBlockFrequency(EdgeFreq,
MisfetchCost);
2584 if (
Pred->succ_size() == 1)
2585 FallThruCost += ScaleBlockFrequency(EdgeFreq,
JumpInstCost);
2586 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
2595 for (
auto *BB : LoopChain) {
2598 BlockChain *SuccChain = BlockToChain[Succ];
2599 if (!LoopBlockSet.count(Succ) &&
2600 (!SuccChain || Succ == *SuccChain->begin())) {
2602 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
2606 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
2614 for (
auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2615 EndIter = LoopChain.end();
2616 Iter != EndIter; Iter++, TailIter++) {
2619 if (TailIter == LoopChain.end())
2620 TailIter = LoopChain.begin();
2622 auto TailBB = *TailIter;
2625 BlockFrequency
Cost = BlockFrequency(0);
2630 if (Iter != LoopChain.begin())
2631 Cost += HeaderFallThroughCost;
2635 for (
auto &ExitWithFreq : ExitsWithFreq)
2636 if (TailBB != ExitWithFreq.first)
2637 Cost += ExitWithFreq.second;
2653 if (TailBB->isSuccessor(*Iter)) {
2654 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2655 if (TailBB->succ_size() == 1)
2657 else if (TailBB->succ_size() == 2) {
2659 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2660 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2661 ? TailBBFreq * TailToHeadProb.
getCompl()
2672 if (
Cost < SmallestRotationCost) {
2673 SmallestRotationCost =
Cost;
2678 if (RotationPos != LoopChain.end()) {
2680 <<
" to the top\n");
2681 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2689MachineBlockPlacement::BlockFilterSet
2690MachineBlockPlacement::collectLoopBlockSet(
const MachineLoop &L) {
2694 bool operator()(
const MachineBasicBlock *
X,
2695 const MachineBasicBlock *
Y)
const {
2696 return X->getNumber() <
Y->getNumber();
2699 std::set<const MachineBasicBlock *, MBBCompare> LoopBlockSet;
2711 BlockFrequency LoopFreq(0);
2712 for (
auto *LoopPred :
L.getHeader()->predecessors())
2713 if (!
L.contains(LoopPred))
2714 LoopFreq += MBFI->getBlockFreq(LoopPred) *
2717 for (MachineBasicBlock *LoopBB :
L.getBlocks()) {
2718 if (LoopBlockSet.count(LoopBB))
2723 BlockChain *Chain = BlockToChain[LoopBB];
2724 for (MachineBasicBlock *ChainBB : *Chain)
2725 LoopBlockSet.insert(ChainBB);
2728 LoopBlockSet.insert(
L.block_begin(),
L.block_end());
2733 BlockFilterSet Ret(LoopBlockSet.begin(), LoopBlockSet.end());
2743void MachineBlockPlacement::buildLoopChains(
const MachineLoop &L) {
2746 for (
const MachineLoop *InnerLoop : L)
2747 buildLoopChains(*InnerLoop);
2750 "BlockWorkList not empty when starting to build loop chains.");
2752 "EHPadWorkList not empty when starting to build loop chains.");
2753 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
2758 bool RotateLoopWithProfile =
2766 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
2774 PreferredLoopExit =
nullptr;
2775 BlockFrequency ExitFreq;
2776 if (!RotateLoopWithProfile && LoopTop ==
L.getHeader())
2777 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq);
2779 BlockChain &LoopChain = *BlockToChain[LoopTop];
2784 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2785 assert(LoopChain.UnscheduledPredecessors == 0 &&
2786 "LoopChain should not have unscheduled predecessors.");
2787 UpdatedPreds.
insert(&LoopChain);
2789 for (
const MachineBasicBlock *LoopBB : LoopBlockSet)
2790 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
2792 buildChain(LoopTop, LoopChain, &LoopBlockSet);
2794 if (RotateLoopWithProfile)
2795 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2797 rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet);
2801 bool BadLoop =
false;
2802 if (LoopChain.UnscheduledPredecessors) {
2804 dbgs() <<
"Loop chain contains a block without its preds placed!\n"
2805 <<
" Loop header: " <<
getBlockName(*
L.block_begin()) <<
"\n"
2806 <<
" Chain header: " <<
getBlockName(*LoopChain.begin()) <<
"\n";
2808 for (MachineBasicBlock *ChainBB : LoopChain) {
2810 if (!LoopBlockSet.remove(ChainBB)) {
2814 dbgs() <<
"Loop chain contains a block not contained by the loop!\n"
2815 <<
" Loop header: " <<
getBlockName(*
L.block_begin()) <<
"\n"
2816 <<
" Chain header: " <<
getBlockName(*LoopChain.begin()) <<
"\n"
2821 if (!LoopBlockSet.empty()) {
2823 for (
const MachineBasicBlock *LoopBB : LoopBlockSet)
2824 dbgs() <<
"Loop contains blocks never placed into a chain!\n"
2825 <<
" Loop header: " <<
getBlockName(*
L.block_begin()) <<
"\n"
2826 <<
" Chain header: " <<
getBlockName(*LoopChain.begin()) <<
"\n"
2829 assert(!BadLoop &&
"Detected problems with the placement of this loop.");
2832 BlockWorkList.
clear();
2833 EHPadWorkList.
clear();
2836void MachineBlockPlacement::buildCFGChains() {
2839 SmallVector<MachineOperand, 4>
Cond;
2842 MachineBasicBlock *BB = &*FI;
2844 new (ChainAllocator.
Allocate()) BlockChain(BlockToChain, BB);
2849 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
2854 MachineBasicBlock *NextBB = &*NextFI;
2857 assert(NextFI != FE &&
"Can't fallthrough past the last block.");
2858 LLVM_DEBUG(
dbgs() <<
"Pre-merging due to unanalyzable fallthrough: "
2861 Chain->merge(NextBB,
nullptr);
2863 BlocksWithUnanalyzableExits.
insert(&*BB);
2871 PreferredLoopExit =
nullptr;
2872 for (MachineLoop *L : *MLI)
2873 buildLoopChains(*L);
2876 "BlockWorkList should be empty before building final chain.");
2878 "EHPadWorkList should be empty before building final chain.");
2880 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2881 for (MachineBasicBlock &
MBB : *
F)
2882 fillWorkLists(&
MBB, UpdatedPreds);
2884 BlockChain &FunctionChain = *BlockToChain[&
F->front()];
2885 buildChain(&
F->front(), FunctionChain);
2888 using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
2892 bool BadFunc =
false;
2893 FunctionBlockSetType FunctionBlockSet;
2894 for (MachineBasicBlock &
MBB : *
F)
2895 FunctionBlockSet.insert(&
MBB);
2897 for (MachineBasicBlock *ChainBB : FunctionChain)
2898 if (!FunctionBlockSet.erase(ChainBB)) {
2900 dbgs() <<
"Function chain contains a block not in the function!\n"
2904 if (!FunctionBlockSet.empty()) {
2906 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
2907 dbgs() <<
"Function contains blocks never placed into a chain!\n"
2908 <<
" Bad block: " <<
getBlockName(RemainingBB) <<
"\n";
2910 assert(!BadFunc &&
"Detected problems with the block placement.");
2915 SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors(
2916 F->getNumBlockIDs());
2918 MachineBasicBlock *LastMBB =
nullptr;
2919 for (
auto &
MBB : *
F) {
2920 if (LastMBB !=
nullptr)
2924 OriginalLayoutSuccessors[
F->back().getNumber()] =
nullptr;
2930 for (MachineBasicBlock *ChainBB : FunctionChain) {
2931 LLVM_DEBUG(
dbgs() << (ChainBB == *FunctionChain.begin() ?
"Placing chain "
2935 F->splice(InsertPos, ChainBB);
2940 if (ChainBB == *FunctionChain.begin())
2948 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
2951 if (!BlocksWithUnanalyzableExits.
count(PrevBB)) {
2957 "Unexpected block with un-analyzable fallthrough!");
2959 TBB = FBB =
nullptr;
2991 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
2993 MachineBasicBlock *PrevBB = &
F->
back();
2997 BlockWorkList.
clear();
2998 EHPadWorkList.
clear();
3001void MachineBlockPlacement::optimizeBranches() {
3002 BlockChain &FunctionChain = *BlockToChain[&
F->front()];
3003 SmallVector<MachineOperand, 4>
Cond;
3011 for (MachineBasicBlock *ChainBB : FunctionChain) {
3013 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
3034 auto Dl = ChainBB->findBranchDebugLoc();
3040void MachineBlockPlacement::alignBlocks() {
3047 if (
F->getFunction().hasMinSize() ||
3052 BlockChain &FunctionChain = *BlockToChain[&
F->front()];
3054 if (FunctionChain.begin() == FunctionChain.end())
3057 const BranchProbability ColdProb(1, 5);
3058 BlockFrequency EntryFreq = MBFI->getBlockFreq(&
F->front());
3059 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
3060 for (MachineBasicBlock *ChainBB : FunctionChain) {
3061 if (ChainBB == *FunctionChain.begin())
3068 MachineLoop *
L = MLI->getLoopFor(ChainBB);
3075 unsigned MDAlign = 1;
3076 MDNode *LoopID =
L->getLoopID();
3085 if (S->
getString() ==
"llvm.loop.align") {
3093 const Align LoopAlign = std::max(TLIAlign,
Align(MDAlign));
3099 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
3100 if (Freq < WeightedEntryFreq)
3105 MachineBasicBlock *LoopHeader =
L->getHeader();
3106 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
3107 if (Freq < (LoopHeaderFreq * ColdProb))
3117 MachineBasicBlock *LayoutPred =
3120 auto DetermineMaxAlignmentPadding = [&]() {
3127 ChainBB->setMaxBytesForAlignment(MaxBytes);
3133 ChainBB->setAlignment(LoopAlign);
3134 DetermineMaxAlignmentPadding();
3142 BranchProbability LayoutProb =
3144 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
3145 if (LayoutEdgeFreq <= (Freq * ColdProb)) {
3146 ChainBB->setAlignment(LoopAlign);
3147 DetermineMaxAlignmentPadding();
3151 const bool HasMaxBytesOverride =
3156 for (MachineBasicBlock &
MBB : *
F) {
3157 if (HasMaxBytesOverride)
3166 for (
auto MBI = std::next(
F->begin()), MBE =
F->end(); MBI != MBE; ++MBI) {
3167 auto LayoutPred = std::prev(MBI);
3169 if (HasMaxBytesOverride)
3194bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
3195 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
3196 const MachineBasicBlock *LoopHeaderBB, BlockChain &Chain,
3198 BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt) {
3199 bool Removed, DuplicatedToLPred;
3200 bool DuplicatedToOriginalLPred;
3201 Removed = maybeTailDuplicateBlock(
3202 BB, LPred, Chain, BlockFilter, PrevUnplacedBlockIt,
3203 PrevUnplacedBlockInFilterIt, DuplicatedToLPred);
3206 DuplicatedToOriginalLPred = DuplicatedToLPred;
3211 while (DuplicatedToLPred && Removed) {
3212 MachineBasicBlock *DupBB, *DupPred;
3218 BlockChain::iterator ChainEnd = Chain.end();
3219 DupBB = *(--ChainEnd);
3221 if (ChainEnd == Chain.begin())
3223 DupPred = *std::prev(ChainEnd);
3224 Removed = maybeTailDuplicateBlock(
3225 DupBB, DupPred, Chain, BlockFilter, PrevUnplacedBlockIt,
3226 PrevUnplacedBlockInFilterIt, DuplicatedToLPred);
3233 LPred = *std::prev(Chain.end());
3234 if (DuplicatedToOriginalLPred)
3235 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
3252bool MachineBlockPlacement::maybeTailDuplicateBlock(
3253 MachineBasicBlock *BB, MachineBasicBlock *LPred, BlockChain &Chain,
3255 BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
3256 bool &DuplicatedToLPred) {
3257 DuplicatedToLPred =
false;
3258 if (!shouldTailDuplicate(BB))
3266 bool Removed =
false;
3267 auto RemovalCallback = [&](MachineBasicBlock *RemBB) {
3272 if (
auto It = BlockToChain.
find(RemBB); It != BlockToChain.
end()) {
3273 It->second->remove(RemBB);
3274 BlockToChain.
erase(It);
3278 if (&(*PrevUnplacedBlockIt) == RemBB) {
3279 PrevUnplacedBlockIt++;
3290 if (It != BlockFilter->end()) {
3291 if (It < PrevUnplacedBlockInFilterIt) {
3292 const MachineBasicBlock *PrevBB = *PrevUnplacedBlockInFilterIt;
3295 auto Distance = PrevUnplacedBlockInFilterIt - It - 1;
3296 PrevUnplacedBlockInFilterIt = BlockFilter->
erase(It) + Distance;
3297 assert(*PrevUnplacedBlockInFilterIt == PrevBB);
3299 }
else if (It == PrevUnplacedBlockInFilterIt)
3302 PrevUnplacedBlockInFilterIt = BlockFilter->erase(It);
3304 BlockFilter->erase(It);
3309 MLI->removeBlock(RemBB);
3310 if (RemBB == PreferredLoopExit)
3311 PreferredLoopExit =
nullptr;
3316 auto RemovalCallbackRef =
3317 function_ref<void(MachineBasicBlock *)>(RemovalCallback);
3322 SmallVectorImpl<MachineBasicBlock *> *CandidatePtr =
nullptr;
3323 if (
F->getFunction().hasProfileData()) {
3325 findDuplicateCandidates(CandidatePreds, BB, BlockFilter);
3326 if (CandidatePreds.
size() == 0)
3329 CandidatePtr = &CandidatePreds;
3332 &RemovalCallbackRef, CandidatePtr);
3335 DuplicatedToLPred =
false;
3336 for (MachineBasicBlock *
Pred : DuplicatedPreds) {
3338 BlockChain *PredChain = BlockToChain[
Pred];
3340 DuplicatedToLPred =
true;
3341 if (
Pred == LPred || (BlockFilter && !BlockFilter->count(
Pred)) ||
3342 PredChain == &Chain)
3344 for (MachineBasicBlock *NewSucc :
Pred->successors()) {
3345 if (BlockFilter && !BlockFilter->count(NewSucc))
3347 BlockChain *NewChain = BlockToChain[NewSucc];
3348 if (NewChain != &Chain && NewChain != PredChain)
3349 NewChain->UnscheduledPredecessors++;
3359 if (!
MI.isPHI() && !
MI.isMetaInstruction())
3368BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) {
3373bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB,
3374 MachineBasicBlock *
Pred,
3375 BlockFilterSet *BlockFilter) {
3378 if (BlockFilter && !BlockFilter->count(
Pred))
3380 BlockChain *PredChain = BlockToChain[
Pred];
3381 if (PredChain && (
Pred != *std::prev(PredChain->end())))
3386 for (MachineBasicBlock *Succ :
Pred->successors())
3388 if (BlockFilter && !BlockFilter->count(Succ))
3390 BlockChain *SuccChain = BlockToChain[Succ];
3391 if (SuccChain && (Succ != *SuccChain->begin()))
3394 if (SuccProb > BestProb)
3395 BestProb = SuccProb;
3399 if (BBProb <= BestProb)
3404 BlockFrequency PredFreq = getBlockCountOrFrequency(
Pred);
3405 BlockFrequency Gain = PredFreq * (BBProb - BestProb);
3406 return Gain > scaleThreshold(BB);
3411void MachineBlockPlacement::findDuplicateCandidates(
3412 SmallVectorImpl<MachineBasicBlock *> &Candidates, MachineBasicBlock *BB,
3413 BlockFilterSet *BlockFilter) {
3414 MachineBasicBlock *Fallthrough =
nullptr;
3416 BlockFrequency BBDupThreshold(scaleThreshold(BB));
3421 auto CmpSucc = [&](MachineBasicBlock *
A, MachineBasicBlock *
B) {
3424 auto CmpPred = [&](MachineBasicBlock *
A, MachineBasicBlock *
B) {
3425 return MBFI->getBlockFreq(
A) > MBFI->getBlockFreq(
B);
3430 auto SuccIt = Succs.begin();
3431 if (SuccIt != Succs.end()) {
3476 for (MachineBasicBlock *
Pred : Preds) {
3477 BlockFrequency PredFreq = getBlockCountOrFrequency(
Pred);
3482 if (!Fallthrough && isBestSuccessor(BB,
Pred, BlockFilter)) {
3484 if (SuccIt != Succs.end())
3490 BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb;
3491 BlockFrequency DupCost;
3492 if (SuccIt == Succs.end()) {
3494 if (Succs.size() > 0)
3495 DupCost += PredFreq;
3498 DupCost += PredFreq;
3502 assert(OrigCost >= DupCost);
3503 OrigCost -= DupCost;
3504 if (OrigCost > BBDupThreshold) {
3506 if (SuccIt != Succs.end())
3514 if ((Candidates.
size() < Preds.size()) && (Candidates.
size() > 0)) {
3515 Candidates[0] = Candidates.
back();
3521void MachineBlockPlacement::initTailDupThreshold() {
3522 DupThreshold = BlockFrequency(0);
3523 if (
F->getFunction().hasProfileData()) {
3527 UseProfileCount =
true;
3532 BlockFrequency MaxFreq = BlockFrequency(0);
3533 for (MachineBasicBlock &
MBB : *
F) {
3534 BlockFrequency Freq = MBFI->getBlockFreq(&
MBB);
3540 DupThreshold = BlockFrequency(MaxFreq * ThresholdProb);
3541 UseProfileCount =
false;
3553 if (OptLevel >= CodeGenOptLevel::Aggressive) {
3565 (OptLevel < CodeGenOptLevel::Aggressive ||
3567 TailDupSize =
TII->getTailDuplicateSize(OptLevel);
3574 auto MBFI = std::make_unique<MBFIWrapper>(
3577 auto *MPDT = MachineBlockPlacement::allowTailDupPlacement(MF)
3581 .getCachedResult<ProfileSummaryAnalysis>(
3586 MachineBlockPlacement MBP(MBPI, MLI, PSI, std::move(MBFI), MPDT,
3598 OS << MapClassName2PassName(
name());
3599 if (!AllowTailMerge)
3600 OS <<
"<no-tail-merge>";
3606 if (std::next(MF.
begin()) == MF.
end())
3610 OptLevel =
F->getTarget().getOptLevel();
3617 PreferredLoopExit =
nullptr;
3620 "BlockToChain map should be empty before starting placement.");
3622 "Computed Edge map should be empty before starting placement.");
3625 initTailDupThreshold();
3627 const bool OptForSize =
3632 bool UseExtTspForPerf =
false;
3633 bool UseExtTspForSize =
false;
3642 if (allowTailDupPlacement(*
F)) {
3645 const bool PreRegAlloc =
false;
3646 TailDup.
initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI,
3648 if (!UseExtTspForSize)
3649 precomputeTriangleChains();
3653 if (!UseExtTspForSize)
3663 if (EnableTailMerge) {
3664 const unsigned TailMergeSize = TailDupSize + 1;
3665 BranchFolder BF(
true,
false,
3666 *MBFI, *MBPI, PSI, TailMergeSize);
3673 if (!UseExtTspForSize) {
3675 BlockToChain.
clear();
3676 ComputedEdges.
clear();
3686 if (UseExtTspForPerf || UseExtTspForSize) {
3688 !(UseExtTspForPerf && UseExtTspForSize) &&
3689 "UseExtTspForPerf and UseExtTspForSize can not be set simultaneously");
3690 applyExtTsp(UseExtTspForSize);
3691 createCFGChainExtTsp();
3697 BlockToChain.
clear();
3698 ComputedEdges.
clear();
3702 StringRef ViewFuncName =
3705 (ViewFuncName.
empty() ||
F->getFunction().getName() == ViewFuncName)) {
3708 MBFI->view(
"MBP." + MF.
getName(),
false);
3716void MachineBlockPlacement::applyExtTsp(
bool OptForSize) {
3718 DenseMap<const MachineBasicBlock *, uint64_t> BlockIndex;
3720 std::vector<const MachineBasicBlock *> CurrentBlockOrder;
3721 CurrentBlockOrder.reserve(
F->size());
3722 size_t NumBlocks = 0;
3723 for (
const MachineBasicBlock &
MBB : *
F) {
3724 BlockIndex[&
MBB] = NumBlocks++;
3725 CurrentBlockOrder.push_back(&
MBB);
3728 SmallVector<uint64_t, 0> BlockCounts(
F->size());
3729 SmallVector<uint64_t, 0> BlockSizes(
F->size());
3731 SmallVector<MachineOperand, 4>
Cond;
3733 for (MachineBasicBlock &
MBB : *
F) {
3735 BlockFrequency BlockFreq = MBFI->getBlockFreq(&
MBB);
3736 BlockCounts[BlockIndex[&
MBB]] = OptForSize ? 1 : BlockFreq.
getFrequency();
3745 size_t NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
3746 BlockSizes[BlockIndex[&
MBB]] = 4 * NumInsts;
3751 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
3762 if (FBB && FBB != FTB)
3770 for (
const MachineBasicBlock *Succ : Succs)
3771 JumpCounts.
push_back({BlockIndex[&
MBB], BlockIndex[Succ], Freq});
3775 BlockFrequency JumpFreq = BlockFreq * EP;
3782 LLVM_DEBUG(
dbgs() <<
"Applying ext-tsp layout for |V| = " <<
F->size()
3783 <<
" with profile = " <<
F->getFunction().hasProfileData()
3784 <<
" (" <<
F->getName() <<
")" <<
"\n");
3791 std::vector<const MachineBasicBlock *> NewBlockOrder;
3792 NewBlockOrder.reserve(
F->size());
3794 NewBlockOrder.push_back(CurrentBlockOrder[Node]);
3796 const double OptScore =
calcExtTspScore(NewOrder, BlockSizes, JumpCounts);
3800 if (OptForSize && OrgScore > OptScore)
3801 assignBlockOrder(CurrentBlockOrder);
3803 assignBlockOrder(NewBlockOrder);
3806void MachineBlockPlacement::assignBlockOrder(
3807 const std::vector<const MachineBasicBlock *> &NewBlockOrder) {
3808 assert(
F->size() == NewBlockOrder.size() &&
"Incorrect size of block order");
3809 F->RenumberBlocks();
3811 bool HasChanges =
false;
3812 for (
size_t I = 0;
I < NewBlockOrder.size();
I++) {
3813 if (NewBlockOrder[
I] !=
F->getBlockNumbered(
I)) {
3822 SmallVector<MachineBasicBlock *, 4> PrevFallThroughs(
F->getNumBlockIDs());
3823 for (
auto &
MBB : *
F) {
3828 DenseMap<const MachineBasicBlock *, size_t> NewIndex;
3829 for (
const MachineBasicBlock *
MBB : NewBlockOrder) {
3830 NewIndex[
MBB] = NewIndex.
size();
3832 F->sort([&](MachineBasicBlock &L, MachineBasicBlock &R) {
3833 return NewIndex[&
L] < NewIndex[&
R];
3838 const TargetInstrInfo *
TII =
F->getSubtarget().getInstrInfo();
3839 SmallVector<MachineOperand, 4>
Cond;
3840 for (
auto &
MBB : *
F) {
3847 if (FTMBB && (NextMBB == EndIt || &*NextMBB != FTMBB)) {
3853 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
3860void MachineBlockPlacement::createCFGChainExtTsp() {
3861 BlockToChain.
clear();
3862 ComputedEdges.
clear();
3865 MachineBasicBlock *HeadBB = &
F->
front();
3866 BlockChain *FunctionChain =
3867 new (ChainAllocator.
Allocate()) BlockChain(BlockToChain, HeadBB);
3869 for (MachineBasicBlock &
MBB : *
F) {
3872 FunctionChain->merge(&
MBB,
nullptr);
3884class MachineBlockPlacementStats {
3886 const MachineBranchProbabilityInfo *MBPI;
3889 const MachineBlockFrequencyInfo *MBFI;
3892 MachineBlockPlacementStats(
const MachineBranchProbabilityInfo *MBPI,
3893 const MachineBlockFrequencyInfo *MBFI)
3894 : MBPI(MBPI), MBFI(MBFI) {}
3898class MachineBlockPlacementStatsLegacy :
public MachineFunctionPass {
3902 MachineBlockPlacementStatsLegacy() : MachineFunctionPass(
ID) {}
3906 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
3907 auto *MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
3908 return MachineBlockPlacementStats(MBPI, MBFI).run(
F);
3911 void getAnalysisUsage(AnalysisUsage &AU)
const override {
3912 AU.
addRequired<MachineBranchProbabilityInfoWrapperPass>();
3913 AU.
addRequired<MachineBlockFrequencyInfoWrapperPass>();
3921char MachineBlockPlacementStatsLegacy::ID = 0;
3926 "Basic Block Placement Stats",
false,
false)
3938 MachineBlockPlacementStats(&MBPI, &MBFI).
run(MF);
3944 if (std::next(
F.begin()) ==
F.end())
3953 (
MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
3955 (
MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
3958 if (
MBB.isLayoutSuccessor(Succ))
const TargetLowering & TLI
Ops append({Chain, DAG.getConstant(SVEStores[NumParts - 2], DL, MVT::i32)})
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Declares methods and data structures for code layout algorithms.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
static unsigned InstrCount
This file defines the DenseMap class.
SmallVector< MachineOperand, 4 > Cond
static LoopDeletionResult merge(LoopDeletionResult A, LoopDeletionResult B)
static BranchProbability getAdjustedProbability(BranchProbability OrigProb, BranchProbability AdjustedSumProb)
The helper function returns the branch probability that is adjusted or normalized over the new total ...
static cl::opt< bool > PreciseRotationCost("precise-rotation-cost", cl::desc("Model the cost of loop rotation more " "precisely by using profile data."), cl::init(false), cl::Hidden)
static cl::opt< unsigned > ExtTspBlockPlacementMaxBlocks("ext-tsp-block-placement-max-blocks", cl::desc("Maximum number of basic blocks in a function to run ext-TSP " "block placement."), cl::init(UINT_MAX), cl::Hidden)
static cl::opt< unsigned > AlignAllBlock("align-all-blocks", cl::desc("Force the alignment of all blocks in the function in log2 format " "(e.g 4 means align on 16B boundaries)."), cl::init(0), cl::Hidden)
static cl::opt< unsigned > PredecessorLimit("block-placement-predecessor-limit", cl::desc("For blocks with more predecessors, certain layout optimizations" "will be disabled to prevent quadratic compile time."), cl::init(1000), cl::Hidden)
static BranchProbability getLayoutSuccessorProbThreshold(const MachineBasicBlock *BB)
static cl::opt< bool > ForceLoopColdBlock("force-loop-cold-block", cl::desc("Force outlining cold blocks from loops."), cl::init(false), cl::Hidden)
static cl::opt< unsigned > ExitBlockBias("block-placement-exit-block-bias", cl::desc("Block frequency percentage a loop exit block needs " "over the original exit to be considered the new exit."), cl::init(0), cl::Hidden)
static cl::opt< unsigned > AlignAllNonFallThruBlocks("align-all-nofallthru-blocks", cl::desc("Force the alignment of all blocks that have no fall-through " "predecessors (i.e. don't add nops that are executed). In log2 " "format (e.g 4 means align on 16B boundaries)."), cl::init(0), cl::Hidden)
static cl::opt< unsigned > TailDupPlacementThreshold("tail-dup-placement-threshold", cl::desc("Instruction cutoff for tail duplication during layout. " "Tail merging during layout is forced to have a threshold " "that won't conflict."), cl::init(2), cl::Hidden)
static cl::opt< unsigned > JumpInstCost("jump-inst-cost", cl::desc("Cost of jump instructions."), cl::init(1), cl::Hidden)
static cl::opt< unsigned > TailDupPlacementPenalty("tail-dup-placement-penalty", cl::desc("Cost penalty for blocks that can avoid breaking CFG by copying. " "Copying can increase fallthrough, but it also increases icache " "pressure. This parameter controls the penalty to account for that. " "Percent as integer."), cl::init(2), cl::Hidden)
static bool greaterWithBias(BlockFrequency A, BlockFrequency B, BlockFrequency EntryFreq)
Compare 2 BlockFrequency's with a small penalty for A.
static cl::opt< unsigned > MisfetchCost("misfetch-cost", cl::desc("Cost that models the probabilistic risk of an instruction " "misfetch due to a jump comparing to falling through, whose cost " "is zero."), cl::init(1), cl::Hidden)
static cl::opt< unsigned > MaxBytesForAlignmentOverride("max-bytes-for-alignment", cl::desc("Forces the maximum bytes allowed to be emitted when padding for " "alignment"), cl::init(0), cl::Hidden)
static cl::opt< bool > BranchFoldPlacement("branch-fold-placement", cl::desc("Perform branch folding during placement. " "Reduces code size."), cl::init(true), cl::Hidden)
static cl::opt< unsigned > TailDupProfilePercentThreshold("tail-dup-profile-percent-threshold", cl::desc("If profile count information is used in tail duplication cost " "model, the gained fall through number from tail duplication " "should be at least this percent of hot count."), cl::init(50), cl::Hidden)
static cl::opt< unsigned > TriangleChainCount("triangle-chain-count", cl::desc("Number of triangle-shaped-CFG's that need to be in a row for the " "triangle tail duplication heuristic to kick in. 0 to disable."), cl::init(2), cl::Hidden)
Branch Probability Basic Block static false std::string getBlockName(const MachineBasicBlock *BB)
Helper to print the name of a MBB.
static cl::opt< bool > ApplyExtTspForSize("apply-ext-tsp-for-size", cl::init(false), cl::Hidden, cl::desc("Use ext-tsp for size-aware block placement."))
static bool hasSameSuccessors(MachineBasicBlock &BB, SmallPtrSetImpl< const MachineBasicBlock * > &Successors)
Check if BB has exactly the successors in Successors.
static cl::opt< bool > TailDupPlacement("tail-dup-placement", cl::desc("Perform tail duplication during placement. " "Creates more fallthrough opportunities in " "outline branches."), cl::init(true), cl::Hidden)
static uint64_t countMBBInstruction(MachineBasicBlock *MBB)
static cl::opt< unsigned > LoopToColdBlockRatio("loop-to-cold-block-ratio", cl::desc("Outline loop blocks from loop chain if (frequency of loop) / " "(frequency of block) is greater than this ratio"), cl::init(5), cl::Hidden)
static cl::opt< bool > RenumberBlocksBeforeView("renumber-blocks-before-view", cl::desc("If true, basic blocks are re-numbered before MBP layout is printed " "into a dot graph. Only used when a function is being printed."), cl::init(false), cl::Hidden)
static cl::opt< unsigned > TailDupPlacementAggressiveThreshold("tail-dup-placement-aggressive-threshold", cl::desc("Instruction cutoff for aggressive tail duplication during " "layout. Used at -O3. Tail merging during layout is forced to " "have a threshold that won't conflict."), cl::init(4), cl::Hidden)
static cl::opt< bool > ForcePreciseRotationCost("force-precise-rotation-cost", cl::desc("Force the use of precise cost " "loop rotation strategy."), cl::init(false), cl::Hidden)
static bool hasProfileData(const Function &F, const FunctionOutliningInfo &OI)
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const override
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
static BlockFrequency max()
Returns the maximum possible frequency, the saturation value.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
static constexpr BranchProbability getOne()
static constexpr BranchProbability getZero()
uint32_t getNumerator() const
BranchProbability getCompl() const
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
iterator find(const_arg_type_t< KeyT > Val)
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
bool erase(const KeyT &Val)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
bool hasProfileData() const
Return true if the function is annotated with profile data.
Module * getParent()
Get the module that this global value is contained inside of...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
LLVM_ABI StringRef getString() const
unsigned pred_size() const
bool isEHPad() const
Returns true if the block is a landing pad.
instr_iterator instr_begin()
LLVM_ABI MachineBasicBlock * getFallThrough(bool JumpToFallThrough=true)
Return the fallthrough block if the block can implicitly transfer control to the block after it by fa...
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
LLVM_ABI void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor)
Update the terminator instructions in block to account for changes to block layout which may have bee...
LLVM_ABI bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
succ_iterator succ_begin()
unsigned succ_size() const
void setAlignment(Align A)
Set alignment of the basic block.
LLVM_ABI bool isEntryBlock() const
Returns true if this is the entry block of the function.
pred_iterator pred_begin()
LLVM_ABI bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
instr_iterator instr_end()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
LLVM_ABI DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
iterator_range< succ_iterator > successors()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
iterator_range< pred_iterator > predecessors()
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName) const
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) 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.
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.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
Analysis pass that exposes the MachineLoopInfo for a machine function.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
LLVM_ABI uint64_t getOrCompHotCountThreshold() const
Returns HotCountThreshold if set.
typename vector_type::const_iterator iterator
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
reference emplace_back(ArgTypes &&... Args)
iterator erase(const_iterator CI)
typename SuperClass::const_iterator const_iterator
typename SuperClass::iterator iterator
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST T * Allocate(size_t num=1)
Allocate space for an array of objects without constructing them.
void DestroyAll()
Call the destructor of each allocated object and deallocate all but the current slab and reset the cu...
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
LLVM_ABI void initMF(MachineFunction &MF, bool PreRegAlloc, const MachineBranchProbabilityInfo *MBPI, MBFIWrapper *MBFI, ProfileSummaryInfo *PSI, bool LayoutMode, unsigned TailDupSize=0)
Prepare to run on a specific machine function.
LLVM_ABI bool tailDuplicateAndUpdate(bool IsSimple, MachineBasicBlock *MBB, MachineBasicBlock *ForcedLayoutPred, SmallVectorImpl< MachineBasicBlock * > *DuplicatedPreds=nullptr, function_ref< void(MachineBasicBlock *)> *RemovalCallback=nullptr, SmallVectorImpl< MachineBasicBlock * > *CandidatePtr=nullptr)
Tail duplicate a single basic block into its predecessors, and then clean up.
static LLVM_ABI bool isSimpleBB(MachineBasicBlock *TailBB)
True if this BB has only one unconditional jump.
LLVM_ABI bool canTailDuplicate(MachineBasicBlock *TailBB, MachineBasicBlock *PredBB)
Returns true if TailBB can successfully be duplicated into PredBB.
LLVM_ABI bool shouldTailDuplicate(bool IsSimple, MachineBasicBlock &TailBB)
Determine if it is profitable to duplicate this block.
virtual Align getPrefLoopAlignment(MachineLoop *ML=nullptr, const MachineBasicBlock *BlockToAlign=nullptr) const
Return the preferred loop alignment.
virtual unsigned getMaxPermittedBytesForAlignment(MachineBasicBlock *MBB) const
Return the maximum amount of bytes allowed to be emitted when padding for alignment.
virtual bool alignLoopsWithOptSize() const
Should loops be aligned even when the function is marked OptSize (but not MinSize).
bool requiresStructuredCFG() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
An efficient, type-erasing, non-owning reference to a callable.
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
initializer< Ty > init(const Ty &Val)
LLVM_ABI double calcExtTspScore(ArrayRef< uint64_t > Order, ArrayRef< uint64_t > NodeSizes, ArrayRef< EdgeCount > EdgeCounts)
Estimate the "quality" of a given node order in CFG.
LLVM_ABI std::vector< uint64_t > computeExtTspLayout(ArrayRef< uint64_t > NodeSizes, ArrayRef< uint64_t > NodeCounts, ArrayRef< EdgeCount > EdgeCounts)
Find a layout of nodes (basic blocks) of a given CFG optimizing jump locality and thus processor I-ca...
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
void stable_sort(R &&Range)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
cl::opt< GVDAGType > ViewBlockLayoutWithBFI("view-block-layout-with-bfi", cl::Hidden, cl::desc("Pop up a window to show a dag displaying MBP layout and associated " "block frequencies of the CFG."), cl::values(clEnumValN(GVDAGType::None, "none", "do not display graphs."), clEnumValN(GVDAGType::Fraction, "fraction", "display a graph using the " "fractional block frequency representation."), clEnumValN(GVDAGType::Integer, "integer", "display a graph using the raw " "integer fractional block frequency representation."), clEnumValN(GVDAGType::Count, "count", "display a graph using the real " "profile count if available.")))
cl::opt< bool > ApplyExtTspWithoutProfile
constexpr from_range_t from_range
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
cl::opt< unsigned > ProfileLikelyProb
auto reverse(ContainerTy &&C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI bool isFunctionInPrintList(StringRef FunctionName)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
CodeGenOptLevel
Code generation optimization level.
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,...
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
cl::opt< unsigned > StaticLikelyProb
LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI, BlockFrequency Freq)
Print the block frequency Freq relative to the current functions entry frequency.
LLVM_ABI char & MachineBlockPlacementID
MachineBlockPlacement - This pass places basic blocks based on branch probabilities.
cl::opt< bool > EnableExtTspBlockPlacement
LLVM_ABI StringRef getViewBlockFreqFuncName(const LLVMContext &C)
Return -view-bfi-func-name.
LLVM_ABI char & MachineBlockPlacementStatsID
MachineBlockPlacementStats - This pass collects statistics about the basic block placement using bran...
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static constexpr Align fromLog2(unsigned Log2Value)
Returns an alignment of 1 << Log2Value bytes.