80#define DEBUG_TYPE "block-placement"
82STATISTIC(NumCondBranches,
"Number of conditional branches");
83STATISTIC(NumUncondBranches,
"Number of unconditional branches");
85 "Potential frequency of taking conditional branches");
87 "Potential frequency of taking unconditional branches");
91 cl::desc(
"Force the alignment of all blocks in the function in log2 format "
92 "(e.g 4 means align on 16B boundaries)."),
96 "align-all-nofallthru-blocks",
97 cl::desc(
"Force the alignment of all blocks that have no fall-through "
98 "predecessors (i.e. don't add nops that are executed). In log2 "
99 "format (e.g 4 means align on 16B boundaries)."),
103 "max-bytes-for-alignment",
104 cl::desc(
"Forces the maximum bytes allowed to be emitted when padding for "
109 "block-placement-predecessor-limit",
110 cl::desc(
"For blocks with more predecessors, certain layout optimizations"
111 "will be disabled to prevent quadratic compile time."),
116 "block-placement-exit-block-bias",
117 cl::desc(
"Block frequency percentage a loop exit block needs "
118 "over the original exit to be considered the new exit."),
125 "loop-to-cold-block-ratio",
126 cl::desc(
"Outline loop blocks from loop chain if (frequency of loop) / "
127 "(frequency of block) is greater than this ratio"),
132 cl::desc(
"Force outlining cold blocks from loops."),
137 cl::desc(
"Model the cost of loop rotation more "
138 "precisely by using profile data."),
143 cl::desc(
"Force the use of precise cost "
144 "loop rotation strategy."),
149 cl::desc(
"Cost that models the probabilistic risk of an instruction "
150 "misfetch due to a jump comparing to falling through, whose cost "
155 cl::desc(
"Cost of jump instructions."),
159 cl::desc(
"Perform tail duplication during placement. "
160 "Creates more fallthrough opportunities in "
161 "outline branches."),
166 cl::desc(
"Perform branch folding during placement. "
167 "Reduces code size."),
172 "tail-dup-placement-threshold",
173 cl::desc(
"Instruction cutoff for tail duplication during layout. "
174 "Tail merging during layout is forced to have a threshold "
175 "that won't conflict."),
180 "tail-dup-placement-aggressive-threshold",
181 cl::desc(
"Instruction cutoff for aggressive tail duplication during "
182 "layout. Used at -O3. Tail merging during layout is forced to "
183 "have a threshold that won't conflict."),
188 "tail-dup-placement-penalty",
190 "Cost penalty for blocks that can avoid breaking CFG by copying. "
191 "Copying can increase fallthrough, but it also increases icache "
192 "pressure. This parameter controls the penalty to account for that. "
193 "Percent as integer."),
198 "tail-dup-profile-percent-threshold",
199 cl::desc(
"If profile count information is used in tail duplication cost "
200 "model, the gained fall through number from tail duplication "
201 "should be at least this percent of hot count."),
206 "triangle-chain-count",
207 cl::desc(
"Number of triangle-shaped-CFG's that need to be in a row for the "
208 "triangle tail duplication heuristic to kick in. 0 to disable."),
217 "renumber-blocks-before-view",
219 "If true, basic blocks are re-numbered before MBP layout is printed "
220 "into a dot graph. Only used when a function is being printed."),
224 "ext-tsp-block-placement-max-blocks",
225 cl::desc(
"Maximum number of basic blocks in a function to run ext-TSP "
232 cl::desc(
"Use ext-tsp for size-aware block placement."));
281 BlockToChainMapType &BlockToChain;
290 : Blocks(1, BB), BlockToChain(BlockToChain) {
291 assert(BB &&
"Cannot create a chain with a null basic block");
292 BlockToChain[BB] =
this;
308 for (
iterator i = begin(); i != end(); ++i) {
324 assert(BB &&
"Can't merge a null block.");
325 assert(!Blocks.
empty() &&
"Can't merge into an empty chain.");
329 assert(!BlockToChain[BB] &&
330 "Passed chain is null, but BB has entry in BlockToChain.");
332 BlockToChain[BB] =
this;
336 assert(BB == *Chain->begin() &&
"Passed BB is not head of Chain.");
337 assert(Chain->begin() != Chain->end());
343 assert(BlockToChain[ChainBB] == Chain &&
"Incoming blocks not in chain.");
344 BlockToChain[ChainBB] =
this;
365 unsigned UnscheduledPredecessors = 0;
368class MachineBlockPlacement {
370 using BlockFilterSet = SmallSetVector<const MachineBasicBlock *, 16>;
373 struct BlockAndTailDupResult {
374 MachineBasicBlock *BB =
nullptr;
379 struct WeightedEdge {
380 BlockFrequency Weight;
381 MachineBasicBlock *Src =
nullptr;
382 MachineBasicBlock *Dest =
nullptr;
390 DenseMap<const MachineBasicBlock *, BlockAndTailDupResult> ComputedEdges;
393 MachineFunction *F =
nullptr;
396 const MachineBranchProbabilityInfo *MBPI =
nullptr;
399 std::unique_ptr<MBFIWrapper> MBFI;
402 MachineLoopInfo *MLI =
nullptr;
407 MachineBasicBlock *PreferredLoopExit =
nullptr;
410 const TargetInstrInfo *TII =
nullptr;
413 const TargetLoweringBase *TLI =
nullptr;
416 MachinePostDominatorTree *MPDT =
nullptr;
418 ProfileSummaryInfo *PSI =
nullptr;
431 TailDuplicator TailDup;
434 BlockFrequency DupThreshold;
436 unsigned TailDupSize;
440 bool UseProfileCount =
false;
449 SpecificBumpPtrAllocator<BlockChain> ChainAllocator;
457 DenseMap<const MachineBasicBlock *, BlockChain *> BlockToChain;
464 SmallPtrSet<MachineBasicBlock *, 4> BlocksWithUnanalyzableExits;
469 BlockFrequency getBlockCountOrFrequency(
const MachineBasicBlock *BB) {
470 if (UseProfileCount) {
471 auto Count = MBFI->getBlockProfileCount(BB);
473 return BlockFrequency(*
Count);
475 return BlockFrequency(0);
477 return MBFI->getBlockFreq(BB);
481 BlockFrequency scaleThreshold(MachineBasicBlock *BB);
482 void initTailDupThreshold();
486 void markChainSuccessors(
const BlockChain &Chain,
487 const MachineBasicBlock *LoopHeaderBB,
488 const BlockFilterSet *BlockFilter =
nullptr);
492 void markBlockSuccessors(
const BlockChain &Chain,
const MachineBasicBlock *BB,
493 const MachineBasicBlock *LoopHeaderBB,
494 const BlockFilterSet *BlockFilter =
nullptr);
497 collectViableSuccessors(
const MachineBasicBlock *BB,
const BlockChain &Chain,
498 const BlockFilterSet *BlockFilter,
499 SmallVector<MachineBasicBlock *, 4> &Successors);
500 bool isBestSuccessor(MachineBasicBlock *BB, MachineBasicBlock *Pred,
501 BlockFilterSet *BlockFilter);
502 void findDuplicateCandidates(SmallVectorImpl<MachineBasicBlock *> &Candidates,
503 MachineBasicBlock *BB,
504 BlockFilterSet *BlockFilter);
505 bool repeatedlyTailDuplicateBlock(
506 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
507 const MachineBasicBlock *LoopHeaderBB, BlockChain &Chain,
508 BlockFilterSet *BlockFilter,
512 maybeTailDuplicateBlock(MachineBasicBlock *BB, MachineBasicBlock *LPred,
513 BlockChain &Chain, BlockFilterSet *BlockFilter,
516 bool &DuplicatedToLPred);
517 bool hasBetterLayoutPredecessor(
const MachineBasicBlock *BB,
518 const MachineBasicBlock *Succ,
519 const BlockChain &SuccChain,
520 BranchProbability SuccProb,
521 BranchProbability RealSuccProb,
522 const BlockChain &Chain,
523 const BlockFilterSet *BlockFilter);
524 BlockAndTailDupResult selectBestSuccessor(
const MachineBasicBlock *BB,
525 const BlockChain &Chain,
526 const BlockFilterSet *BlockFilter);
528 selectBestCandidateBlock(
const BlockChain &Chain,
529 SmallVectorImpl<MachineBasicBlock *> &WorkList);
531 getFirstUnplacedBlock(
const BlockChain &PlacedChain,
534 getFirstUnplacedBlock(
const BlockChain &PlacedChain,
536 const BlockFilterSet *BlockFilter);
543 void fillWorkLists(
const MachineBasicBlock *
MBB,
544 SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
545 const BlockFilterSet *BlockFilter);
547 void buildChain(
const MachineBasicBlock *BB, BlockChain &Chain,
548 BlockFilterSet *BlockFilter =
nullptr);
549 bool canMoveBottomBlockToTop(
const MachineBasicBlock *BottomBlock,
550 const MachineBasicBlock *OldTop);
551 bool hasViableTopFallthrough(
const MachineBasicBlock *Top,
552 const BlockFilterSet &LoopBlockSet);
553 BlockFrequency TopFallThroughFreq(
const MachineBasicBlock *Top,
554 const BlockFilterSet &LoopBlockSet);
555 BlockFrequency FallThroughGains(
const MachineBasicBlock *NewTop,
556 const MachineBasicBlock *OldTop,
557 const MachineBasicBlock *ExitBB,
558 const BlockFilterSet &LoopBlockSet);
559 MachineBasicBlock *findBestLoopTopHelper(MachineBasicBlock *OldTop,
560 const MachineLoop &L,
561 const BlockFilterSet &LoopBlockSet);
562 MachineBasicBlock *findBestLoopTop(
const MachineLoop &L,
563 const BlockFilterSet &LoopBlockSet);
564 MachineBasicBlock *findBestLoopExit(
const MachineLoop &L,
565 const BlockFilterSet &LoopBlockSet,
566 BlockFrequency &ExitFreq);
567 BlockFilterSet collectLoopBlockSet(
const MachineLoop &L);
568 void buildLoopChains(
const MachineLoop &L);
569 void rotateLoop(BlockChain &LoopChain,
const MachineBasicBlock *ExitingBB,
570 BlockFrequency ExitFreq,
const BlockFilterSet &LoopBlockSet);
571 void rotateLoopWithProfile(BlockChain &LoopChain,
const MachineLoop &L,
572 const BlockFilterSet &LoopBlockSet);
573 void buildCFGChains();
574 void optimizeBranches();
578 bool shouldTailDuplicate(MachineBasicBlock *BB);
581 bool isProfitableToTailDup(
const MachineBasicBlock *BB,
582 const MachineBasicBlock *Succ,
583 BranchProbability QProb,
const BlockChain &Chain,
584 const BlockFilterSet *BlockFilter);
587 bool isTrellis(
const MachineBasicBlock *BB,
588 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
589 const BlockChain &Chain,
const BlockFilterSet *BlockFilter);
592 BlockAndTailDupResult getBestTrellisSuccessor(
593 const MachineBasicBlock *BB,
594 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
595 BranchProbability AdjustedSumProb,
const BlockChain &Chain,
596 const BlockFilterSet *BlockFilter);
599 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
600 const MachineBasicBlock *BB,
605 bool canTailDuplicateUnplacedPreds(
const MachineBasicBlock *BB,
606 MachineBasicBlock *Succ,
607 const BlockChain &Chain,
608 const BlockFilterSet *BlockFilter);
612 void precomputeTriangleChains();
615 void applyExtTsp(
bool OptForSize);
618 void assignBlockOrder(
const std::vector<const MachineBasicBlock *> &NewOrder);
621 void createCFGChainExtTsp();
624 MachineBlockPlacement(
const MachineBranchProbabilityInfo *MBPI,
625 MachineLoopInfo *MLI, ProfileSummaryInfo *PSI,
626 std::unique_ptr<MBFIWrapper> MBFI,
627 MachinePostDominatorTree *MPDT,
bool AllowTailMerge)
628 : MBPI(MBPI), MBFI(std::
move(MBFI)), MLI(MLI), MPDT(MPDT), PSI(PSI),
629 AllowTailMerge(AllowTailMerge) {};
631 bool run(MachineFunction &F);
633 static bool allowTailDupPlacement(MachineFunction &MF) {
642 MachineBlockPlacementLegacy() : MachineFunctionPass(ID) {}
644 bool runOnMachineFunction(MachineFunction &MF)
override {
649 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
650 auto MBFI = std::make_unique<MBFIWrapper>(
651 getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI());
652 auto *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
653 auto *MPDT = MachineBlockPlacement::allowTailDupPlacement(MF)
654 ? &getAnalysis<MachinePostDominatorTreeWrapperPass>()
657 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
658 auto *PassConfig = &getAnalysis<TargetPassConfig>();
659 bool AllowTailMerge = PassConfig->getEnableTailMerge();
660 return MachineBlockPlacement(MBPI, MLI, PSI, std::move(MBFI), MPDT,
665 void getAnalysisUsage(AnalysisUsage &AU)
const override {
666 AU.
addRequired<MachineBranchProbabilityInfoWrapperPass>();
667 AU.
addRequired<MachineBlockFrequencyInfoWrapperPass>();
669 AU.
addRequired<MachinePostDominatorTreeWrapperPass>();
680char MachineBlockPlacementLegacy::ID = 0;
685 "Branch Probability Basic Block Placement",
false,
false)
702 OS <<
" ('" << BB->
getName() <<
"')";
713void MachineBlockPlacement::markChainSuccessors(
715 const BlockFilterSet *BlockFilter) {
718 for (MachineBasicBlock *
MBB : Chain) {
719 markBlockSuccessors(Chain,
MBB, LoopHeaderBB, BlockFilter);
729void MachineBlockPlacement::markBlockSuccessors(
730 const BlockChain &Chain,
const MachineBasicBlock *
MBB,
731 const MachineBasicBlock *LoopHeaderBB,
const BlockFilterSet *BlockFilter) {
737 if (BlockFilter && !BlockFilter->count(Succ))
739 BlockChain &SuccChain = *BlockToChain[Succ];
741 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
746 if (SuccChain.UnscheduledPredecessors == 0 ||
747 --SuccChain.UnscheduledPredecessors > 0)
750 auto *NewBB = *SuccChain.begin();
751 if (NewBB->isEHPad())
762BranchProbability MachineBlockPlacement::collectViableSuccessors(
763 const MachineBasicBlock *BB,
const BlockChain &Chain,
764 const BlockFilterSet *BlockFilter,
765 SmallVector<MachineBasicBlock *, 4> &Successors) {
783 for (MachineBasicBlock *Succ : BB->
successors()) {
784 bool SkipSucc =
false;
785 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
788 BlockChain *SuccChain = BlockToChain[Succ];
789 if (SuccChain == &Chain) {
791 }
else if (Succ != *SuccChain->begin()) {
793 <<
" -> Mid chain!\n");
803 return AdjustedSumProb;
808static BranchProbability
814 if (SuccProbN >= SuccProbD)
829 if (Successors.
count(&BB))
832 if (!Successors.
count(Succ))
840bool MachineBlockPlacement::shouldTailDuplicate(MachineBasicBlock *BB) {
861 return (Gain / ThresholdProb) >= EntryFreq;
869bool MachineBlockPlacement::isProfitableToTailDup(
870 const MachineBasicBlock *BB,
const MachineBasicBlock *Succ,
871 BranchProbability QProb,
const BlockChain &Chain,
872 const BlockFilterSet *BlockFilter) {
896 MachineBasicBlock *PDom =
nullptr;
897 SmallVector<MachineBasicBlock *, 4> SuccSuccs;
899 auto AdjustedSuccSumProb =
900 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
902 auto BBFreq = MBFI->getBlockFreq(BB);
903 auto SuccFreq = MBFI->getBlockFreq(Succ);
904 BlockFrequency
P =
BBFreq * PProb;
905 BlockFrequency Qout =
BBFreq * QProb;
906 BlockFrequency EntryFreq = MBFI->getEntryFreq();
909 if (SuccSuccs.
size() == 0)
914 for (MachineBasicBlock *SuccSucc : SuccSuccs) {
916 if (Prob > BestSuccSucc)
926 auto SuccBestPred = BlockFrequency(0);
927 for (MachineBasicBlock *SuccPred : Succ->
predecessors()) {
928 if (SuccPred == Succ || SuccPred == BB ||
929 BlockToChain[SuccPred] == &Chain ||
930 (BlockFilter && !BlockFilter->count(SuccPred)))
934 if (Freq > SuccBestPred)
938 BlockFrequency Qin = SuccBestPred;
959 BranchProbability UProb = BestSuccSucc;
960 BranchProbability VProb = AdjustedSuccSumProb - UProb;
961 BlockFrequency
F = SuccFreq - Qin;
962 BlockFrequency
V = SuccFreq * VProb;
963 BlockFrequency QinU = std::min(Qin,
F) * UProb;
964 BlockFrequency BaseCost =
P +
V;
965 BlockFrequency DupCost = Qout + QinU + std::max(Qin,
F) * VProb;
969 BranchProbability VProb = AdjustedSuccSumProb - UProb;
970 BlockFrequency
U = SuccFreq * UProb;
971 BlockFrequency
V = SuccFreq * VProb;
972 BlockFrequency
F = SuccFreq - Qin;
1002 if (UProb > AdjustedSuccSumProb / 2 &&
1003 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
1004 Chain, BlockFilter))
1007 (
P + V), (Qout + std::max(Qin,
F) * VProb + std::min(Qin,
F) * UProb),
1011 (Qout + std::min(Qin,
F) * AdjustedSuccSumProb +
1012 std::max(Qin,
F) * UProb),
1023bool MachineBlockPlacement::isTrellis(
1024 const MachineBasicBlock *BB,
1025 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
1026 const BlockChain &Chain,
const BlockFilterSet *BlockFilter) {
1035 SmallPtrSet<const MachineBasicBlock *, 8> SeenPreds;
1037 for (MachineBasicBlock *Succ : ViableSuccs) {
1046 if (Successors.count(SuccPred)) {
1048 for (MachineBasicBlock *CheckSucc : SuccPred->successors())
1049 if (!Successors.count(CheckSucc))
1053 const BlockChain *PredChain = BlockToChain[SuccPred];
1054 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
1055 PredChain == &Chain || PredChain == BlockToChain[Succ])
1059 if (!SeenPreds.
insert(SuccPred).second)
1077std::pair<MachineBlockPlacement::WeightedEdge,
1078 MachineBlockPlacement::WeightedEdge>
1079MachineBlockPlacement::getBestNonConflictingEdges(
1080 const MachineBasicBlock *BB,
1090 auto Cmp = [](WeightedEdge
A, WeightedEdge
B) {
return A.Weight >
B.Weight; };
1094 auto BestA = Edges[0].begin();
1095 auto BestB = Edges[1].begin();
1098 if (BestA->Src == BestB->Src) {
1100 auto SecondBestA = std::next(BestA);
1101 auto SecondBestB = std::next(BestB);
1102 BlockFrequency BestAScore = BestA->Weight + SecondBestB->Weight;
1103 BlockFrequency BestBScore = BestB->Weight + SecondBestA->Weight;
1104 if (BestAScore < BestBScore)
1105 BestA = SecondBestA;
1107 BestB = SecondBestB;
1110 if (BestB->Src == BB)
1112 return std::make_pair(*BestA, *BestB);
1122MachineBlockPlacement::BlockAndTailDupResult
1123MachineBlockPlacement::getBestTrellisSuccessor(
1124 const MachineBasicBlock *BB,
1125 const SmallVectorImpl<MachineBasicBlock *> &ViableSuccs,
1126 BranchProbability AdjustedSumProb,
const BlockChain &Chain,
1127 const BlockFilterSet *BlockFilter) {
1129 BlockAndTailDupResult
Result = {
nullptr,
false};
1136 if (Successors.
size() != 2 || ViableSuccs.
size() != 2)
1142 for (
auto *Succ : ViableSuccs) {
1143 for (MachineBasicBlock *SuccPred : Succ->predecessors()) {
1145 if (SuccPred != BB) {
1146 if (BlockFilter && !BlockFilter->count(SuccPred))
1148 const BlockChain *SuccPredChain = BlockToChain[SuccPred];
1149 if (SuccPredChain == &Chain || SuccPredChain == BlockToChain[Succ])
1152 BlockFrequency EdgeFreq = MBFI->getBlockFreq(SuccPred) *
1154 Edges[SuccIndex].
push_back({EdgeFreq, SuccPred, Succ});
1160 WeightedEdge BestA, BestB;
1161 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
1163 if (BestA.Src != BB) {
1167 LLVM_DEBUG(
dbgs() <<
"Trellis, but not one of the chosen edges.\n");
1174 if (BestA.Dest == BestB.Src) {
1177 MachineBasicBlock *Succ1 = BestA.Dest;
1178 MachineBasicBlock *Succ2 = BestB.Dest;
1180 if (allowTailDupPlacement(*
F) && shouldTailDuplicate(Succ2) &&
1181 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
1183 Chain, BlockFilter)) {
1187 <<
", probability: " << Succ2Prob
1188 <<
" (Tail Duplicate)\n");
1190 Result.ShouldTailDup =
true;
1196 ComputedEdges[BestB.Src] = {BestB.Dest,
false};
1198 auto TrellisSucc = BestA.Dest;
1202 <<
", probability: " << SuccProb <<
" (Trellis)\n");
1210bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
1211 const MachineBasicBlock *BB, MachineBasicBlock *Succ,
1212 const BlockChain &Chain,
const BlockFilterSet *BlockFilter) {
1213 if (!shouldTailDuplicate(Succ))
1217 bool Duplicate =
true;
1219 unsigned int NumDup = 0;
1228 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred)) ||
1229 (BlockToChain[Pred] == &Chain && !Succ->
succ_empty()))
1279 if (
F->getFunction().hasProfileData())
1310 if ((NumDup > Succ->
succ_size()) || !Duplicate)
1333void MachineBlockPlacement::precomputeTriangleChains() {
1334 struct TriangleChain {
1335 std::vector<MachineBasicBlock *> Edges;
1337 TriangleChain(MachineBasicBlock *src, MachineBasicBlock *dst)
1338 : Edges({src, dst}) {}
1340 void append(MachineBasicBlock *dst) {
1341 assert(getKey()->isSuccessor(dst) &&
1342 "Attempting to append a block that is not a successor.");
1343 Edges.push_back(dst);
1346 unsigned count()
const {
return Edges.size() - 1; }
1348 MachineBasicBlock *getKey()
const {
return Edges.back(); }
1357 DenseMap<const MachineBasicBlock *, TriangleChain> TriangleChainMap;
1358 for (MachineBasicBlock &BB : *
F) {
1362 MachineBasicBlock *PDom =
nullptr;
1363 for (MachineBasicBlock *Succ : BB.
successors()) {
1371 if (PDom ==
nullptr)
1378 if (!shouldTailDuplicate(PDom))
1380 bool CanTailDuplicate =
true;
1387 CanTailDuplicate =
false;
1393 if (!CanTailDuplicate)
1400 auto Found = TriangleChainMap.
find(&BB);
1403 if (Found != TriangleChainMap.
end()) {
1404 TriangleChain Chain = std::move(Found->second);
1405 TriangleChainMap.
erase(Found);
1407 TriangleChainMap.
insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1409 auto InsertResult = TriangleChainMap.
try_emplace(PDom, &BB, PDom);
1410 assert(InsertResult.second &&
"Block seen twice.");
1418 for (
auto &ChainPair : TriangleChainMap) {
1419 TriangleChain &Chain = ChainPair.second;
1425 MachineBasicBlock *dst = Chain.Edges.back();
1426 Chain.Edges.pop_back();
1427 for (MachineBasicBlock *src :
reverse(Chain.Edges)) {
1430 <<
" as pre-computed based on triangles.\n");
1432 auto InsertResult = ComputedEdges.
insert({src, {dst,
true}});
1433 assert(InsertResult.second &&
"Block seen twice.");
1443static BranchProbability
1479bool MachineBlockPlacement::hasBetterLayoutPredecessor(
1480 const MachineBasicBlock *BB,
const MachineBasicBlock *Succ,
1481 const BlockChain &SuccChain, BranchProbability SuccProb,
1482 BranchProbability RealSuccProb,
const BlockChain &Chain,
1483 const BlockFilterSet *BlockFilter) {
1486 if (SuccChain.UnscheduledPredecessors == 0)
1611 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1612 bool BadCFGConflict =
false;
1615 BlockChain *PredChain = BlockToChain[Pred];
1616 if (Pred == Succ || PredChain == &SuccChain ||
1617 (BlockFilter && !BlockFilter->count(Pred)) || PredChain == &Chain ||
1618 Pred != *std::prev(PredChain->end()) ||
1637 BlockFrequency PredEdgeFreq =
1639 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.
getCompl()) {
1640 BadCFGConflict =
true;
1645 if (BadCFGConflict) {
1647 << SuccProb <<
" (prob) (non-cold CFG conflict)\n");
1664MachineBlockPlacement::BlockAndTailDupResult
1665MachineBlockPlacement::selectBestSuccessor(
const MachineBasicBlock *BB,
1666 const BlockChain &Chain,
1667 const BlockFilterSet *BlockFilter) {
1670 BlockAndTailDupResult BestSucc = {
nullptr,
false};
1673 SmallVector<MachineBasicBlock *, 4> Successors;
1674 auto AdjustedSumProb =
1675 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1682 auto FoundEdge = ComputedEdges.
find(BB);
1683 if (FoundEdge != ComputedEdges.
end()) {
1684 BlockAndTailDupResult
Result = FoundEdge->second;
1685 ComputedEdges.
erase(FoundEdge);
1686 BlockChain *SuccChain = BlockToChain[
Result.BB];
1688 (!BlockFilter || BlockFilter->count(
Result.BB)) &&
1689 SuccChain != &Chain &&
Result.BB == *SuccChain->begin())
1695 if (isTrellis(BB, Successors, Chain, BlockFilter))
1696 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1704 for (MachineBasicBlock *Succ : Successors) {
1706 BranchProbability SuccProb =
1709 BlockChain &SuccChain = *BlockToChain[Succ];
1712 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
1713 Chain, BlockFilter)) {
1715 if (allowTailDupPlacement(*
F) && shouldTailDuplicate(Succ))
1722 <<
", probability: " << SuccProb
1723 << (SuccChain.UnscheduledPredecessors != 0 ?
" (CFG break)" :
"")
1726 if (BestSucc.BB && BestProb >= SuccProb) {
1733 BestProb = SuccProb;
1741 [](std::tuple<BranchProbability, MachineBasicBlock *> L,
1742 std::tuple<BranchProbability, MachineBasicBlock *> R) {
1743 return std::get<0>(L) > std::get<0>(R);
1745 for (
auto &Tup : DupCandidates) {
1746 BranchProbability DupProb;
1747 MachineBasicBlock *Succ;
1748 std::tie(DupProb, Succ) = Tup;
1749 if (DupProb < BestProb)
1751 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter) &&
1752 (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
1754 <<
", probability: " << DupProb
1755 <<
" (Tail Duplicate)\n");
1757 BestSucc.ShouldTailDup =
true;
1778MachineBasicBlock *MachineBlockPlacement::selectBestCandidateBlock(
1779 const BlockChain &Chain, SmallVectorImpl<MachineBasicBlock *> &WorkList) {
1785 return BlockToChain.
lookup(BB) == &Chain;
1788 if (WorkList.
empty())
1791 bool IsEHPad = WorkList[0]->isEHPad();
1793 MachineBasicBlock *BestBlock =
nullptr;
1794 BlockFrequency BestFreq;
1795 for (MachineBasicBlock *
MBB : WorkList) {
1797 "EHPad mismatch between block and work list.");
1799 BlockChain &SuccChain = *BlockToChain[
MBB];
1800 if (&SuccChain == &Chain)
1803 assert(SuccChain.UnscheduledPredecessors == 0 &&
1804 "Found CFG-violating block");
1806 BlockFrequency CandidateFreq = MBFI->getBlockFreq(
MBB);
1829 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
1833 BestFreq = CandidateFreq;
1846MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1847 const BlockChain &PlacedChain,
1852 if (BlockChain *Chain = BlockToChain[&*
I]; Chain != &PlacedChain) {
1853 PrevUnplacedBlockIt =
I;
1857 return *Chain->begin();
1873MachineBasicBlock *MachineBlockPlacement::getFirstUnplacedBlock(
1874 const BlockChain &PlacedChain,
1875 BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
1876 const BlockFilterSet *BlockFilter) {
1878 for (; PrevUnplacedBlockInFilterIt != BlockFilter->end();
1879 ++PrevUnplacedBlockInFilterIt) {
1880 BlockChain *
C = BlockToChain[*PrevUnplacedBlockInFilterIt];
1881 if (
C != &PlacedChain) {
1888void MachineBlockPlacement::fillWorkLists(
1889 const MachineBasicBlock *
MBB, SmallPtrSetImpl<BlockChain *> &UpdatedPreds,
1890 const BlockFilterSet *BlockFilter =
nullptr) {
1891 BlockChain &Chain = *BlockToChain[
MBB];
1892 if (!UpdatedPreds.
insert(&Chain).second)
1896 Chain.UnscheduledPredecessors == 0 &&
1897 "Attempting to place block with unscheduled predecessors in worklist.");
1898 for (MachineBasicBlock *ChainBB : Chain) {
1899 assert(BlockToChain[ChainBB] == &Chain &&
1900 "Block in chain doesn't match BlockToChain map.");
1901 for (MachineBasicBlock *Pred : ChainBB->predecessors()) {
1902 if (BlockFilter && !BlockFilter->count(Pred))
1904 if (BlockToChain[Pred] == &Chain)
1906 ++Chain.UnscheduledPredecessors;
1910 if (Chain.UnscheduledPredecessors != 0)
1913 MachineBasicBlock *BB = *Chain.
begin();
1920void MachineBlockPlacement::buildChain(
const MachineBasicBlock *HeadBB,
1922 BlockFilterSet *BlockFilter) {
1923 assert(HeadBB &&
"BB must not be null.\n");
1924 assert(BlockToChain[HeadBB] == &Chain &&
"BlockToChainMap mis-match.\n");
1926 BlockFilterSet::iterator PrevUnplacedBlockInFilterIt;
1928 PrevUnplacedBlockInFilterIt = BlockFilter->begin();
1930 const MachineBasicBlock *LoopHeaderBB = HeadBB;
1931 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
1932 MachineBasicBlock *BB = *std::prev(Chain.end());
1934 assert(BB &&
"null block found at end of chain in loop.");
1935 assert(BlockToChain[BB] == &Chain &&
"BlockToChainMap mis-match in loop.");
1936 assert(*std::prev(Chain.end()) == BB &&
"BB Not found at end of chain.");
1940 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1941 MachineBasicBlock *BestSucc =
Result.BB;
1942 bool ShouldTailDup =
Result.ShouldTailDup;
1943 if (allowTailDupPlacement(*
F))
1944 ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(
1945 BB, BestSucc, Chain, BlockFilter));
1951 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
1953 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
1957 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockInFilterIt,
1960 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt);
1964 LLVM_DEBUG(
dbgs() <<
"Unnatural loop CFG detected, forcibly merging the "
1965 "layout successor until the CFG reduces\n");
1970 if (allowTailDupPlacement(*
F) && BestSucc && ShouldTailDup) {
1971 repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1972 BlockFilter, PrevUnplacedBlockIt,
1973 PrevUnplacedBlockInFilterIt);
1981 BlockChain &SuccChain = *BlockToChain[BestSucc];
1984 SuccChain.UnscheduledPredecessors = 0;
1987 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
1988 Chain.merge(BestSucc, &SuccChain);
1989 BB = *std::prev(Chain.end());
2010bool MachineBlockPlacement::canMoveBottomBlockToTop(
2011 const MachineBasicBlock *BottomBlock,
const MachineBasicBlock *OldTop) {
2014 MachineBasicBlock *Pred = *BottomBlock->
pred_begin();
2018 MachineBasicBlock *OtherBB = *Pred->
succ_begin();
2019 if (OtherBB == BottomBlock)
2021 if (OtherBB == OldTop)
2029MachineBlockPlacement::TopFallThroughFreq(
const MachineBasicBlock *Top,
2030 const BlockFilterSet &LoopBlockSet) {
2031 BlockFrequency MaxFreq = BlockFrequency(0);
2033 BlockChain *PredChain = BlockToChain[Pred];
2034 if (!LoopBlockSet.count(Pred) &&
2035 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2040 for (MachineBasicBlock *Succ : Pred->
successors()) {
2042 BlockChain *SuccChain = BlockToChain[Succ];
2045 if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) &&
2046 (!SuccChain || Succ == *SuccChain->begin())) {
2052 BlockFrequency EdgeFreq =
2054 if (EdgeFreq > MaxFreq)
2083BlockFrequency MachineBlockPlacement::FallThroughGains(
2084 const MachineBasicBlock *NewTop,
const MachineBasicBlock *OldTop,
2085 const MachineBasicBlock *ExitBB,
const BlockFilterSet &LoopBlockSet) {
2086 BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet);
2087 BlockFrequency FallThrough2Exit = BlockFrequency(0);
2091 BlockFrequency BackEdgeFreq =
2095 MachineBasicBlock *BestPred =
nullptr;
2096 BlockFrequency FallThroughFromPred = BlockFrequency(0);
2097 for (MachineBasicBlock *Pred : NewTop->
predecessors()) {
2098 if (!LoopBlockSet.count(Pred))
2100 BlockChain *PredChain = BlockToChain[Pred];
2101 if (!PredChain || Pred == *std::prev(PredChain->end())) {
2102 BlockFrequency EdgeFreq =
2104 if (EdgeFreq > FallThroughFromPred) {
2105 FallThroughFromPred = EdgeFreq;
2113 BlockFrequency NewFreq = BlockFrequency(0);
2115 for (MachineBasicBlock *Succ : BestPred->
successors()) {
2116 if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ))
2120 BlockChain *SuccChain = BlockToChain[Succ];
2121 if ((SuccChain && (Succ != *SuccChain->begin())) ||
2122 (SuccChain == BlockToChain[BestPred]))
2124 BlockFrequency EdgeFreq = MBFI->getBlockFreq(BestPred) *
2126 if (EdgeFreq > NewFreq)
2129 BlockFrequency OrigEdgeFreq = MBFI->getBlockFreq(BestPred) *
2131 if (NewFreq > OrigEdgeFreq) {
2135 NewFreq = BlockFrequency(0);
2136 FallThroughFromPred = BlockFrequency(0);
2140 BlockFrequency
Result = BlockFrequency(0);
2141 BlockFrequency Gains = BackEdgeFreq + NewFreq;
2142 BlockFrequency Lost =
2143 FallThrough2Top + FallThrough2Exit + FallThroughFromPred;
2171MachineBasicBlock *MachineBlockPlacement::findBestLoopTopHelper(
2172 MachineBasicBlock *OldTop,
const MachineLoop &L,
2173 const BlockFilterSet &LoopBlockSet) {
2177 BlockChain &HeaderChain = *BlockToChain[OldTop];
2178 if (!LoopBlockSet.count(*HeaderChain.begin()))
2180 if (OldTop != *HeaderChain.begin())
2186 BlockFrequency BestGains = BlockFrequency(0);
2187 MachineBasicBlock *BestPred =
nullptr;
2188 for (MachineBasicBlock *Pred : OldTop->
predecessors()) {
2189 if (!LoopBlockSet.count(Pred))
2191 if (Pred ==
L.getHeader())
2199 MachineBasicBlock *OtherBB =
nullptr;
2202 if (OtherBB == OldTop)
2206 if (!canMoveBottomBlockToTop(Pred, OldTop))
2209 BlockFrequency Gains =
2210 FallThroughGains(Pred, OldTop, OtherBB, LoopBlockSet);
2211 if ((Gains > BlockFrequency(0)) &&
2212 (Gains > BestGains ||
2227 (*BestPred->
pred_begin())->succ_size() == 1 &&
2240MachineBlockPlacement::findBestLoopTop(
const MachineLoop &L,
2241 const BlockFilterSet &LoopBlockSet) {
2250 return L.getHeader();
2252 MachineBasicBlock *OldTop =
nullptr;
2253 MachineBasicBlock *NewTop =
L.getHeader();
2254 while (NewTop != OldTop) {
2256 NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet);
2257 if (NewTop != OldTop)
2258 ComputedEdges[NewTop] = {OldTop,
false};
2269MachineBlockPlacement::findBestLoopExit(
const MachineLoop &L,
2270 const BlockFilterSet &LoopBlockSet,
2271 BlockFrequency &ExitFreq) {
2280 BlockChain &HeaderChain = *BlockToChain[
L.getHeader()];
2281 if (!LoopBlockSet.count(*HeaderChain.begin()))
2284 BlockFrequency BestExitEdgeFreq;
2285 unsigned BestExitLoopDepth = 0;
2286 MachineBasicBlock *ExitingBB =
nullptr;
2290 SmallPtrSet<MachineBasicBlock *, 4> BlocksExitingToOuterLoop;
2294 for (MachineBasicBlock *
MBB :
L.getBlocks()) {
2295 BlockChain &Chain = *BlockToChain[
MBB];
2298 if (
MBB != *std::prev(Chain.end()))
2305 MachineBasicBlock *OldExitingBB = ExitingBB;
2306 BlockFrequency OldBestExitEdgeFreq = BestExitEdgeFreq;
2307 bool HasLoopingSucc =
false;
2313 BlockChain &SuccChain = *BlockToChain[Succ];
2315 if (&Chain == &SuccChain) {
2322 if (LoopBlockSet.count(Succ)) {
2325 HasLoopingSucc =
true;
2329 unsigned SuccLoopDepth = 0;
2330 if (MachineLoop *ExitLoop = MLI->
getLoopFor(Succ)) {
2331 SuccLoopDepth = ExitLoop->getLoopDepth();
2332 if (ExitLoop->contains(&L))
2336 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(
MBB) * SuccProb;
2339 <<
getBlockName(Succ) <<
" [L:" << SuccLoopDepth <<
"] ("
2346 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
2347 ExitEdgeFreq > BestExitEdgeFreq ||
2349 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
2350 BestExitEdgeFreq = ExitEdgeFreq;
2355 if (!HasLoopingSucc) {
2357 ExitingBB = OldExitingBB;
2358 BestExitEdgeFreq = OldBestExitEdgeFreq;
2365 dbgs() <<
" No other candidate exit blocks, using loop header\n");
2368 if (
L.getNumBlocks() == 1) {
2369 LLVM_DEBUG(
dbgs() <<
" Loop has 1 block, using loop header as exit\n");
2376 if (!BlocksExitingToOuterLoop.
empty() &&
2377 !BlocksExitingToOuterLoop.
count(ExitingBB))
2382 ExitFreq = BestExitEdgeFreq;
2390bool MachineBlockPlacement::hasViableTopFallthrough(
2391 const MachineBasicBlock *Top,
const BlockFilterSet &LoopBlockSet) {
2393 BlockChain *PredChain = BlockToChain[Pred];
2394 if (!LoopBlockSet.count(Pred) &&
2395 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2400 for (MachineBasicBlock *Succ : Pred->
successors()) {
2402 BlockChain *SuccChain = BlockToChain[Succ];
2405 if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
2423void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
2424 const MachineBasicBlock *ExitingBB,
2425 BlockFrequency ExitFreq,
2426 const BlockFilterSet &LoopBlockSet) {
2430 MachineBasicBlock *Top = *LoopChain.begin();
2431 MachineBasicBlock *Bottom = *std::prev(LoopChain.end());
2434 if (Bottom == ExitingBB)
2441 bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
2446 if (ViableTopFallthrough) {
2447 for (MachineBasicBlock *Succ : Bottom->
successors()) {
2448 BlockChain *SuccChain = BlockToChain[Succ];
2449 if (!LoopBlockSet.count(Succ) &&
2450 (!SuccChain || Succ == *SuccChain->begin()))
2456 BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet);
2457 if (FallThrough2Top >= ExitFreq)
2461 BlockChain::iterator ExitIt =
llvm::find(LoopChain, ExitingBB);
2462 if (ExitIt == LoopChain.end())
2484 if (ViableTopFallthrough) {
2485 assert(std::next(ExitIt) != LoopChain.end() &&
2486 "Exit should not be last BB");
2487 MachineBasicBlock *NextBlockInChain = *std::next(ExitIt);
2495 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
2511void MachineBlockPlacement::rotateLoopWithProfile(
2512 BlockChain &LoopChain,
const MachineLoop &L,
2513 const BlockFilterSet &LoopBlockSet) {
2514 auto RotationPos = LoopChain.end();
2515 MachineBasicBlock *ChainHeaderBB = *LoopChain.begin();
2525 auto ScaleBlockFrequency = [](BlockFrequency Freq,
2526 unsigned Scale) -> BlockFrequency {
2528 return BlockFrequency(0);
2531 return Freq / BranchProbability(1, Scale);
2537 BlockFrequency HeaderFallThroughCost(0);
2539 BlockChain *PredChain = BlockToChain[Pred];
2540 if (!LoopBlockSet.count(Pred) &&
2541 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2542 auto EdgeFreq = MBFI->getBlockFreq(Pred) *
2544 auto FallThruCost = ScaleBlockFrequency(EdgeFreq,
MisfetchCost);
2548 FallThruCost += ScaleBlockFrequency(EdgeFreq,
JumpInstCost);
2549 HeaderFallThroughCost = std::max(HeaderFallThroughCost, FallThruCost);
2558 for (
auto *BB : LoopChain) {
2561 BlockChain *SuccChain = BlockToChain[Succ];
2562 if (!LoopBlockSet.count(Succ) &&
2563 (!SuccChain || Succ == *SuccChain->begin())) {
2565 LargestExitEdgeProb = std::max(LargestExitEdgeProb, SuccProb);
2569 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
2577 for (
auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2578 EndIter = LoopChain.end();
2579 Iter != EndIter; Iter++, TailIter++) {
2582 if (TailIter == LoopChain.end())
2583 TailIter = LoopChain.begin();
2585 auto TailBB = *TailIter;
2588 BlockFrequency
Cost = BlockFrequency(0);
2593 if (Iter != LoopChain.begin())
2594 Cost += HeaderFallThroughCost;
2598 for (
auto &ExitWithFreq : ExitsWithFreq)
2599 if (TailBB != ExitWithFreq.first)
2600 Cost += ExitWithFreq.second;
2616 if (TailBB->isSuccessor(*Iter)) {
2617 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2618 if (TailBB->succ_size() == 1)
2620 else if (TailBB->succ_size() == 2) {
2622 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2623 auto ColderEdgeFreq = TailToHeadProb > BranchProbability(1, 2)
2624 ? TailBBFreq * TailToHeadProb.
getCompl()
2635 if (
Cost < SmallestRotationCost) {
2636 SmallestRotationCost =
Cost;
2641 if (RotationPos != LoopChain.end()) {
2643 <<
" to the top\n");
2644 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2652MachineBlockPlacement::BlockFilterSet
2653MachineBlockPlacement::collectLoopBlockSet(
const MachineLoop &L) {
2657 bool operator()(
const MachineBasicBlock *
X,
2658 const MachineBasicBlock *
Y)
const {
2659 return X->getNumber() <
Y->getNumber();
2662 std::set<const MachineBasicBlock *, MBBCompare> LoopBlockSet;
2674 BlockFrequency LoopFreq(0);
2675 for (
auto *LoopPred :
L.getHeader()->predecessors())
2676 if (!
L.contains(LoopPred))
2677 LoopFreq += MBFI->getBlockFreq(LoopPred) *
2680 for (MachineBasicBlock *LoopBB :
L.getBlocks()) {
2681 if (LoopBlockSet.count(LoopBB))
2686 BlockChain *Chain = BlockToChain[LoopBB];
2687 for (MachineBasicBlock *ChainBB : *Chain)
2688 LoopBlockSet.insert(ChainBB);
2691 LoopBlockSet.insert(
L.block_begin(),
L.block_end());
2696 BlockFilterSet Ret(LoopBlockSet.begin(), LoopBlockSet.end());
2706void MachineBlockPlacement::buildLoopChains(
const MachineLoop &L) {
2709 for (
const MachineLoop *InnerLoop : L)
2710 buildLoopChains(*InnerLoop);
2713 "BlockWorkList not empty when starting to build loop chains.");
2715 "EHPadWorkList not empty when starting to build loop chains.");
2716 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
2721 bool RotateLoopWithProfile =
2729 MachineBasicBlock *LoopTop = findBestLoopTop(L, LoopBlockSet);
2737 PreferredLoopExit =
nullptr;
2738 BlockFrequency ExitFreq;
2739 if (!RotateLoopWithProfile && LoopTop ==
L.getHeader())
2740 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq);
2742 BlockChain &LoopChain = *BlockToChain[LoopTop];
2747 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2748 assert(LoopChain.UnscheduledPredecessors == 0 &&
2749 "LoopChain should not have unscheduled predecessors.");
2750 UpdatedPreds.
insert(&LoopChain);
2752 for (
const MachineBasicBlock *LoopBB : LoopBlockSet)
2753 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
2755 buildChain(LoopTop, LoopChain, &LoopBlockSet);
2757 if (RotateLoopWithProfile)
2758 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2760 rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet);
2764 bool BadLoop =
false;
2765 if (LoopChain.UnscheduledPredecessors) {
2767 dbgs() <<
"Loop chain contains a block without its preds placed!\n"
2768 <<
" Loop header: " <<
getBlockName(*
L.block_begin()) <<
"\n"
2769 <<
" Chain header: " <<
getBlockName(*LoopChain.begin()) <<
"\n";
2771 for (MachineBasicBlock *ChainBB : LoopChain) {
2773 if (!LoopBlockSet.remove(ChainBB)) {
2777 dbgs() <<
"Loop chain contains a block not contained by the loop!\n"
2778 <<
" Loop header: " <<
getBlockName(*
L.block_begin()) <<
"\n"
2779 <<
" Chain header: " <<
getBlockName(*LoopChain.begin()) <<
"\n"
2784 if (!LoopBlockSet.empty()) {
2786 for (
const MachineBasicBlock *LoopBB : LoopBlockSet)
2787 dbgs() <<
"Loop contains blocks never placed into a chain!\n"
2788 <<
" Loop header: " <<
getBlockName(*
L.block_begin()) <<
"\n"
2789 <<
" Chain header: " <<
getBlockName(*LoopChain.begin()) <<
"\n"
2792 assert(!BadLoop &&
"Detected problems with the placement of this loop.");
2795 BlockWorkList.
clear();
2796 EHPadWorkList.
clear();
2799void MachineBlockPlacement::buildCFGChains() {
2805 MachineBasicBlock *BB = &*FI;
2807 new (ChainAllocator.
Allocate()) BlockChain(BlockToChain, BB);
2812 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
2817 MachineBasicBlock *NextBB = &*NextFI;
2820 assert(NextFI != FE &&
"Can't fallthrough past the last block.");
2821 LLVM_DEBUG(
dbgs() <<
"Pre-merging due to unanalyzable fallthrough: "
2824 Chain->merge(NextBB,
nullptr);
2826 BlocksWithUnanalyzableExits.
insert(&*BB);
2834 PreferredLoopExit =
nullptr;
2835 for (MachineLoop *L : *MLI)
2836 buildLoopChains(*L);
2839 "BlockWorkList should be empty before building final chain.");
2841 "EHPadWorkList should be empty before building final chain.");
2843 SmallPtrSet<BlockChain *, 4> UpdatedPreds;
2844 for (MachineBasicBlock &
MBB : *
F)
2845 fillWorkLists(&
MBB, UpdatedPreds);
2847 BlockChain &FunctionChain = *BlockToChain[&
F->front()];
2848 buildChain(&
F->front(), FunctionChain);
2851 using FunctionBlockSetType = SmallPtrSet<MachineBasicBlock *, 16>;
2855 bool BadFunc =
false;
2856 FunctionBlockSetType FunctionBlockSet;
2857 for (MachineBasicBlock &
MBB : *
F)
2858 FunctionBlockSet.insert(&
MBB);
2860 for (MachineBasicBlock *ChainBB : FunctionChain)
2861 if (!FunctionBlockSet.erase(ChainBB)) {
2863 dbgs() <<
"Function chain contains a block not in the function!\n"
2867 if (!FunctionBlockSet.empty()) {
2869 for (MachineBasicBlock *RemainingBB : FunctionBlockSet)
2870 dbgs() <<
"Function contains blocks never placed into a chain!\n"
2871 <<
" Bad block: " <<
getBlockName(RemainingBB) <<
"\n";
2873 assert(!BadFunc &&
"Detected problems with the block placement.");
2878 SmallVector<MachineBasicBlock *, 4> OriginalLayoutSuccessors(
2879 F->getNumBlockIDs());
2881 MachineBasicBlock *LastMBB =
nullptr;
2882 for (
auto &
MBB : *
F) {
2883 if (LastMBB !=
nullptr)
2887 OriginalLayoutSuccessors[
F->back().getNumber()] =
nullptr;
2893 for (MachineBasicBlock *ChainBB : FunctionChain) {
2894 LLVM_DEBUG(
dbgs() << (ChainBB == *FunctionChain.begin() ?
"Placing chain "
2898 F->splice(InsertPos, ChainBB);
2903 if (ChainBB == *FunctionChain.begin())
2911 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
2914 if (!BlocksWithUnanalyzableExits.
count(PrevBB)) {
2920 "Unexpected block with un-analyzable fallthrough!");
2922 TBB = FBB =
nullptr;
2954 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
2956 MachineBasicBlock *PrevBB = &
F->
back();
2960 BlockWorkList.
clear();
2961 EHPadWorkList.
clear();
2964void MachineBlockPlacement::optimizeBranches() {
2965 BlockChain &FunctionChain = *BlockToChain[&
F->front()];
2974 for (MachineBasicBlock *ChainBB : FunctionChain) {
2976 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
2997 auto Dl = ChainBB->findBranchDebugLoc();
3003void MachineBlockPlacement::alignBlocks() {
3010 if (
F->getFunction().hasMinSize() ||
3015 BlockChain &FunctionChain = *BlockToChain[&
F->front()];
3017 if (FunctionChain.begin() == FunctionChain.end())
3020 const BranchProbability ColdProb(1, 5);
3021 BlockFrequency EntryFreq = MBFI->getBlockFreq(&
F->front());
3022 BlockFrequency WeightedEntryFreq = EntryFreq * ColdProb;
3023 for (MachineBasicBlock *ChainBB : FunctionChain) {
3024 if (ChainBB == *FunctionChain.begin())
3031 MachineLoop *
L = MLI->getLoopFor(ChainBB);
3036 unsigned MDAlign = 1;
3037 MDNode *LoopID =
L->getLoopID();
3046 if (S->
getString() ==
"llvm.loop.align") {
3048 "per-loop align metadata should have two operands.");
3051 assert(MDAlign >= 1 &&
"per-loop align value must be positive.");
3057 const Align LoopAlign = std::max(TLIAlign,
Align(MDAlign));
3063 BlockFrequency Freq = MBFI->getBlockFreq(ChainBB);
3064 if (Freq < WeightedEntryFreq)
3069 MachineBasicBlock *LoopHeader =
L->getHeader();
3070 BlockFrequency LoopHeaderFreq = MBFI->getBlockFreq(LoopHeader);
3071 if (Freq < (LoopHeaderFreq * ColdProb))
3081 MachineBasicBlock *LayoutPred =
3084 auto DetermineMaxAlignmentPadding = [&]() {
3091 ChainBB->setMaxBytesForAlignment(MaxBytes);
3097 ChainBB->setAlignment(LoopAlign);
3098 DetermineMaxAlignmentPadding();
3106 BranchProbability LayoutProb =
3108 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
3109 if (LayoutEdgeFreq <= (Freq * ColdProb)) {
3110 ChainBB->setAlignment(LoopAlign);
3111 DetermineMaxAlignmentPadding();
3115 const bool HasMaxBytesOverride =
3120 for (MachineBasicBlock &
MBB : *
F) {
3121 if (HasMaxBytesOverride)
3130 for (
auto MBI = std::next(
F->begin()), MBE =
F->end(); MBI != MBE; ++MBI) {
3131 auto LayoutPred = std::prev(MBI);
3133 if (HasMaxBytesOverride)
3158bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
3159 MachineBasicBlock *BB, MachineBasicBlock *&LPred,
3160 const MachineBasicBlock *LoopHeaderBB, BlockChain &Chain,
3162 BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt) {
3163 bool Removed, DuplicatedToLPred;
3164 bool DuplicatedToOriginalLPred;
3165 Removed = maybeTailDuplicateBlock(
3166 BB, LPred, Chain, BlockFilter, PrevUnplacedBlockIt,
3167 PrevUnplacedBlockInFilterIt, DuplicatedToLPred);
3170 DuplicatedToOriginalLPred = DuplicatedToLPred;
3175 while (DuplicatedToLPred && Removed) {
3176 MachineBasicBlock *DupBB, *DupPred;
3182 BlockChain::iterator ChainEnd = Chain.end();
3183 DupBB = *(--ChainEnd);
3185 if (ChainEnd == Chain.begin())
3187 DupPred = *std::prev(ChainEnd);
3188 Removed = maybeTailDuplicateBlock(
3189 DupBB, DupPred, Chain, BlockFilter, PrevUnplacedBlockIt,
3190 PrevUnplacedBlockInFilterIt, DuplicatedToLPred);
3197 LPred = *std::prev(Chain.end());
3198 if (DuplicatedToOriginalLPred)
3199 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
3216bool MachineBlockPlacement::maybeTailDuplicateBlock(
3217 MachineBasicBlock *BB, MachineBasicBlock *LPred, BlockChain &Chain,
3219 BlockFilterSet::iterator &PrevUnplacedBlockInFilterIt,
3220 bool &DuplicatedToLPred) {
3221 DuplicatedToLPred =
false;
3222 if (!shouldTailDuplicate(BB))
3230 bool Removed =
false;
3231 auto RemovalCallback = [&](MachineBasicBlock *RemBB) {
3236 if (
auto It = BlockToChain.
find(RemBB); It != BlockToChain.
end()) {
3237 It->second->remove(RemBB);
3238 BlockToChain.
erase(It);
3242 if (&(*PrevUnplacedBlockIt) == RemBB) {
3243 PrevUnplacedBlockIt++;
3247 if (RemBB->isEHPad()) {
3258 if (It != BlockFilter->end()) {
3259 if (It < PrevUnplacedBlockInFilterIt) {
3260 const MachineBasicBlock *PrevBB = *PrevUnplacedBlockInFilterIt;
3263 auto Distance = PrevUnplacedBlockInFilterIt - It - 1;
3264 PrevUnplacedBlockInFilterIt = BlockFilter->
erase(It) + Distance;
3265 assert(*PrevUnplacedBlockInFilterIt == PrevBB);
3267 }
else if (It == PrevUnplacedBlockInFilterIt)
3270 PrevUnplacedBlockInFilterIt = BlockFilter->erase(It);
3272 BlockFilter->erase(It);
3277 MLI->removeBlock(RemBB);
3278 if (RemBB == PreferredLoopExit)
3279 PreferredLoopExit =
nullptr;
3284 auto RemovalCallbackRef =
3285 function_ref<void(MachineBasicBlock *)>(RemovalCallback);
3290 SmallVectorImpl<MachineBasicBlock *> *CandidatePtr =
nullptr;
3291 if (
F->getFunction().hasProfileData()) {
3293 findDuplicateCandidates(CandidatePreds, BB, BlockFilter);
3294 if (CandidatePreds.
size() == 0)
3297 CandidatePtr = &CandidatePreds;
3300 &RemovalCallbackRef, CandidatePtr);
3303 DuplicatedToLPred =
false;
3304 for (MachineBasicBlock *Pred : DuplicatedPreds) {
3306 BlockChain *PredChain = BlockToChain[Pred];
3308 DuplicatedToLPred =
true;
3309 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred)) ||
3310 PredChain == &Chain)
3312 for (MachineBasicBlock *NewSucc : Pred->
successors()) {
3313 if (BlockFilter && !BlockFilter->count(NewSucc))
3315 BlockChain *NewChain = BlockToChain[NewSucc];
3316 if (NewChain != &Chain && NewChain != PredChain)
3317 NewChain->UnscheduledPredecessors++;
3327 if (!
MI.isPHI() && !
MI.isMetaInstruction())
3336BlockFrequency MachineBlockPlacement::scaleThreshold(MachineBasicBlock *BB) {
3341bool MachineBlockPlacement::isBestSuccessor(MachineBasicBlock *BB,
3342 MachineBasicBlock *Pred,
3343 BlockFilterSet *BlockFilter) {
3346 if (BlockFilter && !BlockFilter->count(Pred))
3348 BlockChain *PredChain = BlockToChain[Pred];
3349 if (PredChain && (Pred != *std::prev(PredChain->end())))
3354 for (MachineBasicBlock *Succ : Pred->
successors())
3356 if (BlockFilter && !BlockFilter->count(Succ))
3358 BlockChain *SuccChain = BlockToChain[Succ];
3359 if (SuccChain && (Succ != *SuccChain->begin()))
3362 if (SuccProb > BestProb)
3363 BestProb = SuccProb;
3367 if (BBProb <= BestProb)
3372 BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
3373 BlockFrequency Gain = PredFreq * (BBProb - BestProb);
3374 return Gain > scaleThreshold(BB);
3379void MachineBlockPlacement::findDuplicateCandidates(
3380 SmallVectorImpl<MachineBasicBlock *> &Candidates, MachineBasicBlock *BB,
3381 BlockFilterSet *BlockFilter) {
3382 MachineBasicBlock *Fallthrough =
nullptr;
3384 BlockFrequency BBDupThreshold(scaleThreshold(BB));
3389 auto CmpSucc = [&](MachineBasicBlock *
A, MachineBasicBlock *
B) {
3392 auto CmpPred = [&](MachineBasicBlock *
A, MachineBasicBlock *
B) {
3393 return MBFI->getBlockFreq(
A) > MBFI->getBlockFreq(
B);
3398 auto SuccIt = Succs.begin();
3399 if (SuccIt != Succs.end()) {
3444 for (MachineBasicBlock *Pred : Preds) {
3445 BlockFrequency PredFreq = getBlockCountOrFrequency(Pred);
3450 if (!Fallthrough && isBestSuccessor(BB, Pred, BlockFilter)) {
3452 if (SuccIt != Succs.end())
3458 BlockFrequency OrigCost = PredFreq + PredFreq * DefaultBranchProb;
3459 BlockFrequency DupCost;
3460 if (SuccIt == Succs.end()) {
3462 if (Succs.size() > 0)
3463 DupCost += PredFreq;
3466 DupCost += PredFreq;
3470 assert(OrigCost >= DupCost);
3471 OrigCost -= DupCost;
3472 if (OrigCost > BBDupThreshold) {
3474 if (SuccIt != Succs.end())
3482 if ((Candidates.
size() < Preds.size()) && (Candidates.
size() > 0)) {
3483 Candidates[0] = Candidates.
back();
3489void MachineBlockPlacement::initTailDupThreshold() {
3490 DupThreshold = BlockFrequency(0);
3491 if (
F->getFunction().hasProfileData()) {
3495 UseProfileCount =
true;
3500 BlockFrequency MaxFreq = BlockFrequency(0);
3501 for (MachineBasicBlock &
MBB : *
F) {
3502 BlockFrequency Freq = MBFI->getBlockFreq(&
MBB);
3508 DupThreshold = BlockFrequency(MaxFreq * ThresholdProb);
3509 UseProfileCount =
false;
3521 if (OptLevel >= CodeGenOptLevel::Aggressive) {
3533 (OptLevel < CodeGenOptLevel::Aggressive ||
3535 TailDupSize =
TII->getTailDuplicateSize(OptLevel);
3542 auto MBFI = std::make_unique<MBFIWrapper>(
3545 auto *MPDT = MachineBlockPlacement::allowTailDupPlacement(MF)
3549 .getCachedResult<ProfileSummaryAnalysis>(
3554 MachineBlockPlacement MBP(MBPI, MLI, PSI, std::move(MBFI), MPDT,
3566 OS << MapClassName2PassName(
name());
3567 if (!AllowTailMerge)
3568 OS <<
"<no-tail-merge>";
3574 if (std::next(MF.
begin()) == MF.
end())
3578 OptLevel =
F->getTarget().getOptLevel();
3585 PreferredLoopExit =
nullptr;
3588 "BlockToChain map should be empty before starting placement.");
3590 "Computed Edge map should be empty before starting placement.");
3593 initTailDupThreshold();
3595 const bool OptForSize =
3600 bool UseExtTspForPerf =
false;
3601 bool UseExtTspForSize =
false;
3610 if (allowTailDupPlacement(*
F)) {
3613 const bool PreRegAlloc =
false;
3614 TailDup.
initMF(MF, PreRegAlloc, MBPI, MBFI.get(), PSI,
3616 if (!UseExtTspForSize)
3617 precomputeTriangleChains();
3621 if (!UseExtTspForSize)
3631 if (EnableTailMerge) {
3633 BranchFolder BF(
true,
false,
3641 if (!UseExtTspForSize) {
3643 BlockToChain.
clear();
3644 ComputedEdges.
clear();
3654 if (UseExtTspForPerf || UseExtTspForSize) {
3656 !(UseExtTspForPerf && UseExtTspForSize) &&
3657 "UseExtTspForPerf and UseExtTspForSize can not be set simultaneously");
3658 applyExtTsp(UseExtTspForSize);
3659 createCFGChainExtTsp();
3665 BlockToChain.
clear();
3666 ComputedEdges.
clear();
3675 MBFI->view(
"MBP." + MF.
getName(),
false);
3683void MachineBlockPlacement::applyExtTsp(
bool OptForSize) {
3685 DenseMap<const MachineBasicBlock *, uint64_t> BlockIndex;
3687 std::vector<const MachineBasicBlock *> CurrentBlockOrder;
3688 CurrentBlockOrder.reserve(
F->size());
3689 size_t NumBlocks = 0;
3690 for (
const MachineBasicBlock &
MBB : *
F) {
3691 BlockIndex[&
MBB] = NumBlocks++;
3692 CurrentBlockOrder.push_back(&
MBB);
3695 SmallVector<uint64_t, 0> BlockCounts(
F->size());
3696 SmallVector<uint64_t, 0> BlockSizes(
F->size());
3700 for (MachineBasicBlock &
MBB : *
F) {
3702 BlockFrequency BlockFreq = MBFI->getBlockFreq(&
MBB);
3703 BlockCounts[BlockIndex[&
MBB]] = OptForSize ? 1 : BlockFreq.
getFrequency();
3712 size_t NumInsts = std::distance(NonDbgInsts.begin(), NonDbgInsts.end());
3713 BlockSizes[BlockIndex[&
MBB]] = 4 * NumInsts;
3718 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
3729 if (FBB && FBB != FTB)
3736 const uint64_t Freq = Succs.
size() == 1 ? 110 : 100;
3737 for (
const MachineBasicBlock *Succ : Succs)
3738 JumpCounts.
push_back({BlockIndex[&
MBB], BlockIndex[Succ], Freq});
3742 BlockFrequency JumpFreq = BlockFreq * EP;
3749 LLVM_DEBUG(
dbgs() <<
"Applying ext-tsp layout for |V| = " <<
F->size()
3750 <<
" with profile = " <<
F->getFunction().hasProfileData()
3751 <<
" (" <<
F->getName() <<
")" <<
"\n");
3758 std::vector<const MachineBasicBlock *> NewBlockOrder;
3759 NewBlockOrder.reserve(
F->size());
3760 for (uint64_t Node : NewOrder) {
3761 NewBlockOrder.push_back(CurrentBlockOrder[Node]);
3763 const double OptScore =
calcExtTspScore(NewOrder, BlockSizes, JumpCounts);
3767 if (OptForSize && OrgScore > OptScore)
3768 assignBlockOrder(CurrentBlockOrder);
3770 assignBlockOrder(NewBlockOrder);
3773void MachineBlockPlacement::assignBlockOrder(
3774 const std::vector<const MachineBasicBlock *> &NewBlockOrder) {
3775 assert(
F->size() == NewBlockOrder.size() &&
"Incorrect size of block order");
3776 F->RenumberBlocks();
3778 bool HasChanges =
false;
3779 for (
size_t I = 0;
I < NewBlockOrder.size();
I++) {
3780 if (NewBlockOrder[
I] !=
F->getBlockNumbered(
I)) {
3789 SmallVector<MachineBasicBlock *, 4> PrevFallThroughs(
F->getNumBlockIDs());
3790 for (
auto &
MBB : *
F) {
3795 DenseMap<const MachineBasicBlock *, size_t> NewIndex;
3796 for (
const MachineBasicBlock *
MBB : NewBlockOrder) {
3797 NewIndex[
MBB] = NewIndex.
size();
3799 F->sort([&](MachineBasicBlock &L, MachineBasicBlock &R) {
3800 return NewIndex[&
L] < NewIndex[&
R];
3805 const TargetInstrInfo *
TII =
F->getSubtarget().getInstrInfo();
3807 for (
auto &
MBB : *
F) {
3814 if (FTMBB && (NextMBB == EndIt || &*NextMBB != FTMBB)) {
3820 MachineBasicBlock *
TBB =
nullptr, *FBB =
nullptr;
3827void MachineBlockPlacement::createCFGChainExtTsp() {
3828 BlockToChain.
clear();
3829 ComputedEdges.
clear();
3832 MachineBasicBlock *HeadBB = &
F->
front();
3833 BlockChain *FunctionChain =
3834 new (ChainAllocator.
Allocate()) BlockChain(BlockToChain, HeadBB);
3836 for (MachineBasicBlock &
MBB : *
F) {
3839 FunctionChain->merge(&
MBB,
nullptr);
3851class MachineBlockPlacementStats {
3853 const MachineBranchProbabilityInfo *MBPI;
3856 const MachineBlockFrequencyInfo *MBFI;
3859 MachineBlockPlacementStats(
const MachineBranchProbabilityInfo *MBPI,
3860 const MachineBlockFrequencyInfo *MBFI)
3861 : MBPI(MBPI), MBFI(MBFI) {}
3862 bool run(MachineFunction &MF);
3865class MachineBlockPlacementStatsLegacy :
public MachineFunctionPass {
3869 MachineBlockPlacementStatsLegacy() : MachineFunctionPass(
ID) {}
3871 bool runOnMachineFunction(MachineFunction &
F)
override {
3873 &getAnalysis<MachineBranchProbabilityInfoWrapperPass>().getMBPI();
3874 auto *MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
3875 return MachineBlockPlacementStats(MBPI, MBFI).run(
F);
3878 void getAnalysisUsage(AnalysisUsage &AU)
const override {
3879 AU.
addRequired<MachineBranchProbabilityInfoWrapperPass>();
3880 AU.
addRequired<MachineBlockFrequencyInfoWrapperPass>();
3888char MachineBlockPlacementStatsLegacy::ID = 0;
3893 "Basic Block Placement Stats",
false,
false)
3905 MachineBlockPlacementStats(&MBPI, &MBFI).
run(MF);
3911 if (std::next(
F.begin()) ==
F.end())
3920 (
MBB.succ_size() > 1) ? NumCondBranches : NumUncondBranches;
3922 (
MBB.succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
3925 if (
MBB.isLayoutSuccessor(Succ))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static cl::opt< unsigned > TailMergeSize("tail-merge-size", cl::desc("Min number of instructions to consider tail merging"), cl::init(3), cl::Hidden)
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.
const HexagonInstrInfo * TII
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
const SmallVectorImpl< MachineOperand > & Cond
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.
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
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.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
bool erase(const KeyT &Val)
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
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...
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
Remove the branching code at the end of the specific MBB.
bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify) const override
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e....
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const override
Insert branch code into the end of the specified MachineBasicBlock.
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
unsigned getNumOperands() const
Return number of MDNode operands.
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()
succ_reverse_iterator succ_rbegin()
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)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
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.
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 unsigned getMaxPermittedBytesForAlignment(MachineBasicBlock *MBB) const
Return the maximum amount of bytes allowed to be emitted when padding for alignment.
virtual Align getPrefLoopAlignment(MachineLoop *ML=nullptr) const
Return the preferred loop 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.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
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...
DXILDebugInfoMap run(Module &M)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
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< 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
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
cl::opt< std::string > ViewBlockFreqFuncName("view-bfi-func-name", cl::Hidden, cl::desc("The option to specify " "the name of the function " "whose CFG will be displayed."))
auto reverse(ContainerTy &&C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
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(GVDT_None, "none", "do not display graphs."), clEnumValN(GVDT_Fraction, "fraction", "display a graph using the " "fractional block frequency representation."), clEnumValN(GVDT_Integer, "integer", "display a graph using the raw " "integer fractional block frequency representation."), clEnumValN(GVDT_Count, "count", "display a graph using the real " "profile count if available.")))
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
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
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 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.