57 #define DEBUG_TYPE "block-placement"
59 STATISTIC(NumCondBranches,
"Number of conditional branches");
60 STATISTIC(NumUncondBranches,
"Number of unconditional branches");
62 "Potential frequency of taking conditional branches");
64 "Potential frequency of taking unconditional branches");
67 cl::desc(
"Force the alignment of all "
68 "blocks in the function."),
72 "align-all-nofallthru-blocks",
73 cl::desc(
"Force the alignment of all "
74 "blocks that have no fall-through predecessors (i.e. don't add "
75 "nops that are executed)."),
80 "block-placement-exit-block-bias",
81 cl::desc(
"Block frequency percentage a loop exit block needs "
82 "over the original exit to be considered the new exit."),
89 "loop-to-cold-block-ratio",
90 cl::desc(
"Outline loop blocks from loop chain if (frequency of loop) / "
91 "(frequency of block) is greater than this ratio"),
96 cl::desc(
"Model the cost of loop rotation more "
97 "precisely by using profile data."),
101 cl::desc(
"Force the use of precise cost "
102 "loop rotation strategy."),
107 cl::desc(
"Cost that models the probabilistic risk of an instruction "
108 "misfetch due to a jump comparing to falling through, whose cost "
113 cl::desc(
"Cost of jump instructions."),
117 cl::desc(
"Perform tail duplication during placement. "
118 "Creates more fallthrough opportunites in "
119 "outline branches."),
124 cl::desc(
"Perform branch folding during placement. "
125 "Reduces code size."),
130 "tail-dup-placement-threshold",
131 cl::desc(
"Instruction cutoff for tail duplication during layout. "
132 "Tail merging during layout is forced to have a threshold "
133 "that won't conflict."),
cl::init(2),
138 "tail-dup-placement-aggressive-threshold",
139 cl::desc(
"Instruction cutoff for aggressive tail duplication during "
140 "layout. Used at -O3. Tail merging during layout is forced to "
141 "have a threshold that won't conflict."),
cl::init(3),
146 "tail-dup-placement-penalty",
147 cl::desc(
"Cost penalty for blocks that can avoid breaking CFG by copying. "
148 "Copying can increase fallthrough, but it also increases icache "
149 "pressure. This parameter controls the penalty to account for that. "
150 "Percent as integer."),
156 "triangle-chain-count",
157 cl::desc(
"Number of triangle-shaped-CFG's that need to be in a row for the "
158 "triangle tail duplication heuristic to kick in. 0 to disable."),
205 BlockToChainMapType &BlockToChain;
214 : Blocks(1, BB), BlockToChain(BlockToChain), UnscheduledPredecessors(0) {
215 assert(BB &&
"Cannot create a chain with a null basic block");
216 BlockToChain[BB] =
this;
225 const_iterator
begin()
const {
return Blocks.
begin(); }
228 iterator
end() {
return Blocks.
end(); }
229 const_iterator
end()
const {
return Blocks.
end(); }
232 for(iterator i =
begin(); i !=
end(); ++i) {
248 assert(BB &&
"Can't merge a null block.");
249 assert(!Blocks.empty() &&
"Can't merge into an empty chain.");
253 assert(!BlockToChain[BB] &&
254 "Passed chain is null, but BB has entry in BlockToChain.");
255 Blocks.push_back(BB);
256 BlockToChain[BB] =
this;
260 assert(BB == *Chain->begin() &&
"Passed BB is not head of Chain.");
261 assert(Chain->begin() != Chain->end());
266 Blocks.push_back(ChainBB);
267 assert(BlockToChain[ChainBB] == Chain &&
"Incoming blocks not in chain.");
268 BlockToChain[ChainBB] =
this;
289 unsigned UnscheduledPredecessors;
299 struct BlockAndTailDupResult {
305 struct WeightedEdge {
325 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
378 void markChainSuccessors(
380 const BlockFilterSet *BlockFilter =
nullptr);
384 void markBlockSuccessors(
387 const BlockFilterSet *BlockFilter =
nullptr);
390 collectViableSuccessors(
392 const BlockFilterSet *BlockFilter,
394 bool shouldPredBlockBeOutlined(
396 const BlockChain &Chain,
const BlockFilterSet *BlockFilter,
398 bool repeatedlyTailDuplicateBlock(
401 BlockChain &Chain, BlockFilterSet *BlockFilter,
403 bool maybeTailDuplicateBlock(
405 BlockChain &Chain, BlockFilterSet *BlockFilter,
407 bool &DuplicatedToPred);
408 bool hasBetterLayoutPredecessor(
412 const BlockFilterSet *BlockFilter);
413 BlockAndTailDupResult selectBestSuccessor(
415 const BlockFilterSet *BlockFilter);
419 const BlockChain &PlacedChain,
421 const BlockFilterSet *BlockFilter);
430 const BlockFilterSet *BlockFilter);
432 BlockFilterSet *BlockFilter =
nullptr);
434 const MachineLoop &
L,
const BlockFilterSet &LoopBlockSet);
436 const MachineLoop &
L,
const BlockFilterSet &LoopBlockSet);
437 BlockFilterSet collectLoopBlockSet(
const MachineLoop &
L);
441 const BlockFilterSet &LoopBlockSet);
442 void rotateLoopWithProfile(
444 const BlockFilterSet &LoopBlockSet);
445 void buildCFGChains();
446 void optimizeBranches();
453 bool isProfitableToTailDup(
456 const BlockChain &Chain,
const BlockFilterSet *BlockFilter);
460 const BlockChain &Chain,
const BlockFilterSet *BlockFilter);
462 BlockAndTailDupResult getBestTrellisSuccessor(
466 const BlockFilterSet *BlockFilter);
468 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
473 bool canTailDuplicateUnplacedPreds(
475 const BlockChain &Chain,
const BlockFilterSet *BlockFilter);
478 void precomputeTriangleChains();
503 "Branch Probability Basic Block Placement",
false,
false)
519 OS <<
" ('" << BB->
getName() <<
"')";
531 void MachineBlockPlacement::markChainSuccessors(
533 const BlockFilterSet *BlockFilter) {
537 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
547 void MachineBlockPlacement::markBlockSuccessors(
555 if (BlockFilter && !BlockFilter->count(Succ))
557 BlockChain &SuccChain = *BlockToChain[Succ];
559 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
564 if (SuccChain.UnscheduledPredecessors == 0 ||
565 --SuccChain.UnscheduledPredecessors > 0)
568 auto *NewBB = *SuccChain.begin();
569 if (NewBB->isEHPad())
570 EHPadWorkList.push_back(NewBB);
572 BlockWorkList.push_back(NewBB);
582 const BlockFilterSet *BlockFilter,
602 bool SkipSucc =
false;
603 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
606 BlockChain *SuccChain = BlockToChain[Succ];
607 if (SuccChain == &Chain) {
609 }
else if (Succ != *SuccChain->begin()) {
615 AdjustedSumProb -= MBPI->getEdgeProbability(BB, Succ);
620 return AdjustedSumProb;
631 if (SuccProbN >= SuccProbD)
646 if (Successors.
count(&BB))
649 if (!Successors.
count(Succ))
661 bool IsSimple = TailDup.isSimpleBB(BB);
665 return TailDup.shouldTailDuplicate(IsSimple, *BB);
675 uint64_t EntryFreq) {
678 return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
686 bool MachineBlockPlacement::isProfitableToTailDup(
689 const BlockChain &Chain,
const BlockFilterSet *BlockFilter) {
716 auto AdjustedSuccSumProb =
717 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
719 auto BBFreq = MBFI->getBlockFreq(BB);
720 auto SuccFreq = MBFI->getBlockFreq(Succ);
723 uint64_t EntryFreq = MBFI->getEntryFreq();
726 if (SuccSuccs.
size() == 0)
732 auto Prob = MBPI->getEdgeProbability(Succ, SuccSucc);
733 if (Prob > BestSuccSucc)
736 if (MPDT->dominates(SuccSucc, Succ)) {
745 if (SuccPred == Succ || SuccPred == BB
746 || BlockToChain[SuccPred] == &Chain
747 || (BlockFilter && !BlockFilter->count(SuccPred)))
749 auto Freq = MBFI->getBlockFreq(SuccPred)
750 * MBPI->getEdgeProbability(SuccPred, Succ);
751 if (Freq > SuccBestPred)
819 if (UProb > AdjustedSuccSumProb / 2 &&
820 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
828 (Qout +
std::min(Qin, F) * AdjustedSuccSumProb +
840 bool MachineBlockPlacement::isTrellis(
843 const BlockChain &Chain,
const BlockFilterSet *BlockFilter) {
858 if (Successors.count(SuccPred)) {
861 if (!Successors.count(CheckSucc))
865 const BlockChain *PredChain = BlockToChain[SuccPred];
866 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
867 PredChain == &Chain || PredChain == BlockToChain[Succ])
871 if (!SeenPreds.
insert(SuccPred).second)
889 std::pair<MachineBlockPlacement::WeightedEdge,
890 MachineBlockPlacement::WeightedEdge>
891 MachineBlockPlacement::getBestNonConflictingEdges(
902 auto Cmp = [](WeightedEdge
A, WeightedEdge
B) {
return A.Weight >
B.Weight; };
904 std::stable_sort(Edges[0].
begin(), Edges[0].
end(), Cmp);
905 std::stable_sort(Edges[1].
begin(), Edges[1].
end(), Cmp);
906 auto BestA = Edges[0].begin();
907 auto BestB = Edges[1].begin();
910 if (BestA->Src == BestB->Src) {
912 auto SecondBestA = std::next(BestA);
913 auto SecondBestB = std::next(BestB);
916 if (BestAScore < BestBScore)
922 if (BestB->Src == BB)
924 return std::make_pair(*BestA, *BestB);
934 MachineBlockPlacement::BlockAndTailDupResult
935 MachineBlockPlacement::getBestTrellisSuccessor(
939 const BlockFilterSet *BlockFilter) {
941 BlockAndTailDupResult Result = {
nullptr,
false};
948 if (Successors.
size() != 2 || ViableSuccs.
size() != 2)
954 for (
auto Succ : ViableSuccs) {
958 if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
959 BlockToChain[SuccPred] == &Chain ||
960 BlockToChain[SuccPred] == BlockToChain[Succ])
963 MBPI->getEdgeProbability(SuccPred, Succ);
964 Edges[SuccIndex].
push_back({EdgeFreq, SuccPred, Succ});
970 WeightedEdge BestA, BestB;
971 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
973 if (BestA.Src != BB) {
977 DEBUG(
dbgs() <<
"Trellis, but not one of the chosen edges.\n");
984 if (BestA.Dest == BestB.Src) {
991 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
992 isProfitableToTailDup(BB, Succ2, MBPI->getEdgeProbability(BB, Succ1),
993 Chain, BlockFilter)) {
995 MBPI->getEdgeProbability(BB, Succ2), AdjustedSumProb);
997 <<
", probability: " << Succ2Prob <<
" (Tail Duplicate)\n");
999 Result.ShouldTailDup =
true;
1005 ComputedEdges[BestB.Src] = { BestB.Dest,
false };
1007 auto TrellisSucc = BestA.Dest;
1009 MBPI->getEdgeProbability(BB, TrellisSucc), AdjustedSumProb);
1011 <<
", probability: " << SuccProb <<
" (Trellis)\n");
1012 Result.BB = TrellisSucc;
1019 bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
1021 const BlockChain &Chain,
const BlockFilterSet *BlockFilter) {
1022 if (!shouldTailDuplicate(Succ))
1032 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
1033 || BlockToChain[Pred] == &Chain)
1035 if (!TailDup.canTailDuplicate(Succ, Pred)) {
1094 void MachineBlockPlacement::precomputeTriangleChains() {
1095 struct TriangleChain {
1096 std::vector<MachineBasicBlock *> Edges;
1098 : Edges({src, dst}) {}
1101 assert(getKey()->isSuccessor(dst) &&
1102 "Attempting to append a block that is not a successor.");
1106 unsigned count()
const {
return Edges.
size() - 1; }
1109 return Edges.
back();
1116 DEBUG(
dbgs() <<
"Pre-computing triangle chains.\n");
1126 if (!MPDT->dominates(Succ, &BB))
1133 if (PDom ==
nullptr)
1140 if (!shouldTailDuplicate(PDom))
1142 bool CanTailDuplicate =
true;
1148 if (!TailDup.canTailDuplicate(PDom, Pred)) {
1149 CanTailDuplicate =
false;
1155 if (!CanTailDuplicate)
1162 auto Found = TriangleChainMap.
find(&BB);
1165 if (Found != TriangleChainMap.
end()) {
1166 TriangleChain Chain = std::move(Found->second);
1167 TriangleChainMap.
erase(Found);
1169 TriangleChainMap.
insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1171 auto InsertResult = TriangleChainMap.
try_emplace(PDom, &BB, PDom);
1172 assert(InsertResult.second &&
"Block seen twice.");
1180 for (
auto &ChainPair : TriangleChainMap) {
1181 TriangleChain &Chain = ChainPair.second;
1188 Chain.Edges.pop_back();
1191 getBlockName(dst) <<
" as pre-computed based on triangles.\n");
1193 auto InsertResult = ComputedEdges.insert({src, {dst,
true}});
1194 assert(InsertResult.second &&
"Block seen twice.");
1236 bool MachineBlockPlacement::hasBetterLayoutPredecessor(
1240 const BlockFilterSet *BlockFilter) {
1243 if (SuccChain.UnscheduledPredecessors == 0)
1363 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1364 bool BadCFGConflict =
false;
1367 if (Pred == Succ || BlockToChain[Pred] == &SuccChain ||
1368 (BlockFilter && !BlockFilter->count(Pred)) ||
1369 BlockToChain[Pred] == &Chain ||
1389 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, Succ);
1390 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.
getCompl()) {
1391 BadCFGConflict =
true;
1396 if (BadCFGConflict) {
1398 <<
" (prob) (non-cold CFG conflict)\n");
1415 MachineBlockPlacement::BlockAndTailDupResult
1416 MachineBlockPlacement::selectBestSuccessor(
1418 const BlockFilterSet *BlockFilter) {
1421 BlockAndTailDupResult BestSucc = {
nullptr,
false };
1425 auto AdjustedSumProb =
1426 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1432 auto FoundEdge = ComputedEdges.find(BB);
1433 if (FoundEdge != ComputedEdges.end()) {
1435 ComputedEdges.erase(FoundEdge);
1436 BlockChain *SuccChain = BlockToChain[Succ];
1437 if (BB->
isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
1438 SuccChain != &Chain && Succ == *SuccChain->begin())
1439 return FoundEdge->second;
1444 if (isTrellis(BB, Successors, Chain, BlockFilter))
1445 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1454 auto RealSuccProb = MBPI->getEdgeProbability(BB, Succ);
1458 BlockChain &SuccChain = *BlockToChain[Succ];
1461 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
1462 Chain, BlockFilter)) {
1465 DupCandidates.
push_back(std::make_tuple(SuccProb, Succ));
1472 << (SuccChain.UnscheduledPredecessors != 0 ?
" (CFG break)" :
"")
1475 if (BestSucc.BB && BestProb >= SuccProb) {
1476 DEBUG(
dbgs() <<
" Not the best candidate, continuing\n");
1480 DEBUG(
dbgs() <<
" Setting it as best candidate\n");
1482 BestProb = SuccProb;
1489 if (DupCandidates.
size() != 0) {
1491 [](
const std::tuple<BranchProbability, MachineBasicBlock *> &a,
1492 const std::tuple<BranchProbability, MachineBasicBlock *> &b) {
1493 return std::get<0>(a) > std::get<0>(b);
1495 std::stable_sort(DupCandidates.
begin(), DupCandidates.
end(), cmp);
1497 for(
auto &Tup : DupCandidates) {
1500 std::tie(DupProb, Succ) = Tup;
1501 if (DupProb < BestProb)
1503 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
1504 && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
1508 <<
" (Tail Duplicate)\n");
1510 BestSucc.ShouldTailDup =
true;
1539 return BlockToChain.lookup(BB) == &Chain;
1543 if (WorkList.
empty())
1546 bool IsEHPad = WorkList[0]->isEHPad();
1552 "EHPad mismatch between block and work list.");
1554 BlockChain &SuccChain = *BlockToChain[MBB];
1555 if (&SuccChain == &Chain)
1558 assert(SuccChain.UnscheduledPredecessors == 0 &&
1559 "Found CFG-violating block");
1563 MBFI->printBlockFreq(
dbgs(), CandidateFreq) <<
" (freq)\n");
1583 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
1587 BestFreq = CandidateFreq;
1601 const BlockChain &PlacedChain,
1603 const BlockFilterSet *BlockFilter) {
1606 if (BlockFilter && !BlockFilter->count(&*
I))
1608 if (BlockToChain[&*
I] != &PlacedChain) {
1609 PrevUnplacedBlockIt =
I;
1613 return *BlockToChain[&*
I]->begin();
1619 void MachineBlockPlacement::fillWorkLists(
1622 const BlockFilterSet *BlockFilter =
nullptr) {
1623 BlockChain &Chain = *BlockToChain[MBB];
1624 if (!UpdatedPreds.
insert(&Chain).second)
1628 Chain.UnscheduledPredecessors == 0 &&
1629 "Attempting to place block with unscheduled predecessors in worklist.");
1631 assert(BlockToChain[ChainBB] == &Chain &&
1632 "Block in chain doesn't match BlockToChain map.");
1634 if (BlockFilter && !BlockFilter->count(Pred))
1636 if (BlockToChain[Pred] == &Chain)
1638 ++Chain.UnscheduledPredecessors;
1642 if (Chain.UnscheduledPredecessors != 0)
1647 EHPadWorkList.push_back(BB);
1649 BlockWorkList.push_back(BB);
1652 void MachineBlockPlacement::buildChain(
1654 BlockFilterSet *BlockFilter) {
1655 assert(HeadBB &&
"BB must not be null.\n");
1656 assert(BlockToChain[HeadBB] == &Chain &&
"BlockToChainMap mis-match.\n");
1660 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
1663 assert(BB &&
"null block found at end of chain in loop.");
1664 assert(BlockToChain[BB] == &Chain &&
"BlockToChainMap mis-match in loop.");
1665 assert(*std::prev(Chain.end()) == BB &&
"BB Not found at end of chain.");
1670 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1672 bool ShouldTailDup = Result.ShouldTailDup;
1674 ShouldTailDup |= (BestSucc && shouldTailDuplicate(BestSucc));
1680 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
1682 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
1685 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
1689 DEBUG(
dbgs() <<
"Unnatural loop CFG detected, forcibly merging the "
1690 "layout successor until the CFG reduces\n");
1699 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1700 BlockFilter, PrevUnplacedBlockIt))
1705 BlockChain &SuccChain = *BlockToChain[BestSucc];
1708 SuccChain.UnscheduledPredecessors = 0;
1711 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
1712 Chain.merge(BestSucc, &SuccChain);
1713 BB = *std::prev(Chain.end());
1716 DEBUG(
dbgs() <<
"Finished forming chain for header block "
1731 MachineBlockPlacement::findBestLoopTop(
const MachineLoop &
L,
1732 const BlockFilterSet &LoopBlockSet) {
1740 if (F->getFunction()->optForSize())
1746 BlockChain &HeaderChain = *BlockToChain[L.
getHeader()];
1747 if (!LoopBlockSet.count(*HeaderChain.begin()))
1756 if (!LoopBlockSet.count(Pred))
1759 << Pred->succ_size() <<
" successors, ";
1760 MBFI->printBlockFreq(
dbgs(), Pred) <<
" freq\n");
1761 if (Pred->succ_size() > 1)
1765 if (!BestPred || PredFreq > BestPredFreq ||
1766 (!(PredFreq < BestPredFreq) &&
1767 Pred->isLayoutSuccessor(L.
getHeader()))) {
1769 BestPredFreq = PredFreq;
1775 DEBUG(
dbgs() <<
" final top unchanged\n");
1781 (*BestPred->
pred_begin())->succ_size() == 1 &&
1795 MachineBlockPlacement::findBestLoopExit(
const MachineLoop &L,
1796 const BlockFilterSet &LoopBlockSet) {
1805 BlockChain &HeaderChain = *BlockToChain[L.
getHeader()];
1806 if (!LoopBlockSet.count(*HeaderChain.begin()))
1810 unsigned BestExitLoopDepth = 0;
1820 BlockChain &Chain = *BlockToChain[MBB];
1823 if (MBB != *std::prev(Chain.end()))
1832 bool HasLoopingSucc =
false;
1838 BlockChain &SuccChain = *BlockToChain[Succ];
1840 if (&Chain == &SuccChain) {
1846 auto SuccProb = MBPI->getEdgeProbability(MBB, Succ);
1847 if (LoopBlockSet.count(Succ)) {
1850 HasLoopingSucc =
true;
1854 unsigned SuccLoopDepth = 0;
1855 if (
MachineLoop *ExitLoop = MLI->getLoopFor(Succ)) {
1856 SuccLoopDepth = ExitLoop->getLoopDepth();
1857 if (ExitLoop->contains(&L))
1858 BlocksExitingToOuterLoop.
insert(MBB);
1861 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
1863 <<
getBlockName(Succ) <<
" [L:" << SuccLoopDepth <<
"] (";
1864 MBFI->printBlockFreq(
dbgs(), ExitEdgeFreq) <<
")\n");
1870 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
1871 ExitEdgeFreq > BestExitEdgeFreq ||
1873 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
1874 BestExitEdgeFreq = ExitEdgeFreq;
1879 if (!HasLoopingSucc) {
1881 ExitingBB = OldExitingBB;
1882 BestExitEdgeFreq = OldBestExitEdgeFreq;
1888 DEBUG(
dbgs() <<
" No other candidate exit blocks, using loop header\n");
1892 DEBUG(
dbgs() <<
" Loop has 1 block, using loop header as exit\n");
1899 if (!BlocksExitingToOuterLoop.
empty() &&
1900 !BlocksExitingToOuterLoop.
count(ExitingBB))
1913 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
1915 const BlockFilterSet &LoopBlockSet) {
1923 if (Bottom == ExitingBB)
1926 bool ViableTopFallthrough =
false;
1928 BlockChain *PredChain = BlockToChain[Pred];
1929 if (!LoopBlockSet.count(Pred) &&
1930 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1931 ViableTopFallthrough =
true;
1939 if (ViableTopFallthrough) {
1941 BlockChain *SuccChain = BlockToChain[Succ];
1942 if (!LoopBlockSet.count(Succ) &&
1943 (!SuccChain || Succ == *SuccChain->begin()))
1948 BlockChain::iterator ExitIt =
find(LoopChain, ExitingBB);
1949 if (ExitIt == LoopChain.end())
1971 if (ViableTopFallthrough) {
1972 assert(std::next(ExitIt) != LoopChain.end() &&
1973 "Exit should not be last BB");
1982 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
1998 void MachineBlockPlacement::rotateLoopWithProfile(
2000 const BlockFilterSet &LoopBlockSet) {
2002 auto HeaderIter =
find(LoopChain, HeaderBB);
2003 auto RotationPos = LoopChain.end();
2022 for (
auto *Pred : HeaderBB->predecessors()) {
2023 BlockChain *PredChain = BlockToChain[Pred];
2024 if (!LoopBlockSet.count(Pred) &&
2025 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2027 MBFI->getBlockFreq(Pred) * MBPI->getEdgeProbability(Pred, HeaderBB);
2028 auto FallThruCost = ScaleBlockFrequency(EdgeFreq,
MisfetchCost);
2031 if (Pred->succ_size() == 1)
2032 FallThruCost += ScaleBlockFrequency(EdgeFreq,
JumpInstCost);
2033 HeaderFallThroughCost =
std::max(HeaderFallThroughCost, FallThruCost);
2042 for (
auto BB : LoopChain) {
2045 BlockChain *SuccChain = BlockToChain[Succ];
2046 if (!LoopBlockSet.count(Succ) &&
2047 (!SuccChain || Succ == *SuccChain->begin())) {
2048 auto SuccProb = MBPI->getEdgeProbability(BB, Succ);
2049 LargestExitEdgeProb =
std::max(LargestExitEdgeProb, SuccProb);
2053 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
2061 for (
auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2062 EndIter = LoopChain.end();
2063 Iter != EndIter; Iter++, TailIter++) {
2066 if (TailIter == LoopChain.end())
2067 TailIter = LoopChain.begin();
2069 auto TailBB = *TailIter;
2077 if (Iter != HeaderIter)
2078 Cost += HeaderFallThroughCost;
2082 for (
auto &ExitWithFreq : ExitsWithFreq)
2083 if (TailBB != ExitWithFreq.first)
2084 Cost += ExitWithFreq.second;
2100 if (TailBB->isSuccessor(*Iter)) {
2101 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2102 if (TailBB->succ_size() == 1)
2103 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
2105 else if (TailBB->succ_size() == 2) {
2106 auto TailToHeadProb = MBPI->getEdgeProbability(TailBB, *Iter);
2107 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2109 ? TailBBFreq * TailToHeadProb.
getCompl()
2111 Cost += ScaleBlockFrequency(TailToHeadFreq,
MisfetchCost) +
2119 if (Cost < SmallestRotationCost) {
2120 SmallestRotationCost = Cost;
2125 if (RotationPos != LoopChain.end()) {
2127 <<
" to the top\n");
2128 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2137 MachineBlockPlacement::collectLoopBlockSet(
const MachineLoop &L) {
2138 BlockFilterSet LoopBlockSet;
2149 if (F->getFunction()->getEntryCount()) {
2151 for (
auto LoopPred : L.
getHeader()->predecessors())
2153 LoopFreq += MBFI->getBlockFreq(LoopPred) *
2154 MBPI->getEdgeProbability(LoopPred, L.
getHeader());
2160 LoopBlockSet.insert(LoopBB);
2165 return LoopBlockSet;
2174 void MachineBlockPlacement::buildLoopChains(
const MachineLoop &L) {
2178 buildLoopChains(*InnerLoop);
2180 assert(BlockWorkList.empty() &&
2181 "BlockWorkList not empty when starting to build loop chains.");
2182 assert(EHPadWorkList.empty() &&
2183 "EHPadWorkList not empty when starting to build loop chains.");
2184 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
2189 bool RotateLoopWithProfile =
2199 RotateLoopWithProfile ? L.getHeader() : findBestLoopTop(L, LoopBlockSet);
2204 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
2205 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet);
2207 BlockChain &LoopChain = *BlockToChain[LoopTop];
2213 assert(LoopChain.UnscheduledPredecessors == 0 &&
2214 "LoopChain should not have unscheduled predecessors.");
2215 UpdatedPreds.
insert(&LoopChain);
2218 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
2220 buildChain(LoopTop, LoopChain, &LoopBlockSet);
2222 if (RotateLoopWithProfile)
2223 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2225 rotateLoop(LoopChain, PreferredLoopExit, LoopBlockSet);
2229 bool BadLoop =
false;
2230 if (LoopChain.UnscheduledPredecessors) {
2232 dbgs() <<
"Loop chain contains a block without its preds placed!\n"
2233 <<
" Loop header: " <<
getBlockName(*L.block_begin()) <<
"\n"
2234 <<
" Chain header: " <<
getBlockName(*LoopChain.begin()) <<
"\n";
2238 if (!LoopBlockSet.remove(ChainBB)) {
2242 dbgs() <<
"Loop chain contains a block not contained by the loop!\n"
2243 <<
" Loop header: " <<
getBlockName(*L.block_begin()) <<
"\n"
2244 <<
" Chain header: " <<
getBlockName(*LoopChain.begin()) <<
"\n"
2249 if (!LoopBlockSet.empty()) {
2252 dbgs() <<
"Loop contains blocks never placed into a chain!\n"
2253 <<
" Loop header: " <<
getBlockName(*L.block_begin()) <<
"\n"
2254 <<
" Chain header: " <<
getBlockName(*LoopChain.begin()) <<
"\n"
2257 assert(!BadLoop &&
"Detected problems with the placement of this loop.");
2260 BlockWorkList.clear();
2261 EHPadWorkList.clear();
2264 void MachineBlockPlacement::buildCFGChains() {
2272 new (ChainAllocator.Allocate()) BlockChain(BlockToChain, BB);
2285 assert(NextFI != FE &&
"Can't fallthrough past the last block.");
2286 DEBUG(
dbgs() <<
"Pre-merging due to unanalyzable fallthrough: "
2289 Chain->merge(NextBB,
nullptr);
2291 BlocksWithUnanalyzableExits.insert(&*BB);
2299 PreferredLoopExit =
nullptr;
2301 buildLoopChains(*L);
2303 assert(BlockWorkList.empty() &&
2304 "BlockWorkList should be empty before building final chain.");
2305 assert(EHPadWorkList.empty() &&
2306 "EHPadWorkList should be empty before building final chain.");
2310 fillWorkLists(&MBB, UpdatedPreds);
2312 BlockChain &FunctionChain = *BlockToChain[&F->front()];
2313 buildChain(&F->front(), FunctionChain);
2320 bool BadFunc =
false;
2321 FunctionBlockSetType FunctionBlockSet;
2323 FunctionBlockSet.insert(&MBB);
2326 if (!FunctionBlockSet.erase(ChainBB)) {
2328 dbgs() <<
"Function chain contains a block not in the function!\n"
2332 if (!FunctionBlockSet.empty()) {
2335 dbgs() <<
"Function contains blocks never placed into a chain!\n"
2336 <<
" Bad block: " <<
getBlockName(RemainingBB) <<
"\n";
2338 assert(!BadFunc &&
"Detected problems with the block placement.");
2343 DEBUG(
dbgs() <<
"[MBP] Function: "<< F->getName() <<
"\n");
2345 DEBUG(
dbgs() << (ChainBB == *FunctionChain.begin() ?
"Placing chain "
2349 F->splice(InsertPos, ChainBB);
2354 if (ChainBB == *FunctionChain.begin())
2365 if (!BlocksWithUnanalyzableExits.count(PrevBB)) {
2371 "Unexpected block with un-analyzable fallthrough!");
2373 TBB = FBB =
nullptr;
2406 F->
back().updateTerminator();
2408 BlockWorkList.clear();
2409 EHPadWorkList.clear();
2412 void MachineBlockPlacement::optimizeBranches() {
2413 BlockChain &FunctionChain = *BlockToChain[&F->front()];
2428 if (TBB && !Cond.
empty() && FBB &&
2429 MBPI->getEdgeProbability(ChainBB, FBB) >
2430 MBPI->getEdgeProbability(ChainBB, TBB) &&
2432 DEBUG(
dbgs() <<
"Reverse order of the two branches: "
2435 << MBPI->getEdgeProbability(ChainBB, FBB) <<
" vs "
2436 << MBPI->getEdgeProbability(ChainBB, TBB) <<
"\n");
2440 ChainBB->updateTerminator();
2446 void MachineBlockPlacement::alignBlocks() {
2452 if (F->getFunction()->optForSize())
2454 BlockChain &FunctionChain = *BlockToChain[&F->front()];
2455 if (FunctionChain.begin() == FunctionChain.end())
2462 if (ChainBB == *FunctionChain.begin())
2473 unsigned Align = TLI->getPrefLoopAlignment(L);
2480 if (Freq < WeightedEntryFreq)
2487 if (Freq < (LoopHeaderFreq * ColdProb))
2498 ChainBB->setAlignment(Align);
2507 MBPI->getEdgeProbability(LayoutPred, ChainBB);
2508 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2509 if (LayoutEdgeFreq <= (Freq * ColdProb))
2510 ChainBB->setAlignment(Align);
2529 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2532 BlockChain &Chain, BlockFilterSet *BlockFilter,
2534 bool Removed, DuplicatedToLPred;
2535 bool DuplicatedToOriginalLPred;
2536 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2537 PrevUnplacedBlockIt,
2541 DuplicatedToOriginalLPred = DuplicatedToLPred;
2547 while (DuplicatedToLPred) {
2548 assert (Removed &&
"Block must have been removed to be duplicated into its "
2549 "layout predecessor.");
2556 BlockChain::iterator ChainEnd = Chain.end();
2557 DupBB = *(--ChainEnd);
2559 if (ChainEnd == Chain.begin())
2561 DupPred = *std::prev(ChainEnd);
2562 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2563 PrevUnplacedBlockIt,
2571 LPred = *std::prev(Chain.end());
2572 if (DuplicatedToOriginalLPred)
2573 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2591 bool MachineBlockPlacement::maybeTailDuplicateBlock(
2593 BlockChain &Chain, BlockFilterSet *BlockFilter,
2595 bool &DuplicatedToLPred) {
2596 DuplicatedToLPred =
false;
2597 if (!shouldTailDuplicate(BB))
2600 DEBUG(
dbgs() <<
"Redoing tail duplication for Succ#"
2605 bool Removed =
false;
2606 auto RemovalCallback =
2612 bool InWorkList =
true;
2614 if (BlockToChain.count(RemBB)) {
2615 BlockChain *Chain = BlockToChain[RemBB];
2616 InWorkList = Chain->UnscheduledPredecessors == 0;
2617 Chain->remove(RemBB);
2618 BlockToChain.erase(RemBB);
2622 if (&(*PrevUnplacedBlockIt) == RemBB) {
2623 PrevUnplacedBlockIt++;
2629 if (RemBB->isEHPad())
2630 RemoveList = EHPadWorkList;
2639 BlockFilter->remove(RemBB);
2643 MLI->removeBlock(RemBB);
2644 if (RemBB == PreferredLoopExit)
2645 PreferredLoopExit =
nullptr;
2647 DEBUG(
dbgs() <<
"TailDuplicator deleted block: "
2650 auto RemovalCallbackRef =
2654 bool IsSimple = TailDup.isSimpleBB(BB);
2655 TailDup.tailDuplicateAndUpdate(IsSimple, BB, LPred,
2656 &DuplicatedPreds, &RemovalCallbackRef);
2659 DuplicatedToLPred =
false;
2662 BlockChain* PredChain = BlockToChain[Pred];
2664 DuplicatedToLPred =
true;
2665 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
2666 || PredChain == &Chain)
2669 if (BlockFilter && !BlockFilter->count(NewSucc))
2671 BlockChain *NewChain = BlockToChain[NewSucc];
2672 if (NewChain != &Chain && NewChain != PredChain)
2673 NewChain->UnscheduledPredecessors++;
2679 bool MachineBlockPlacement::runOnMachineFunction(
MachineFunction &MF) {
2684 if (std::next(MF.
begin()) == MF.
end())
2688 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2689 MBFI = llvm::make_unique<BranchFolder::MBFIWrapper>(
2690 getAnalysis<MachineBlockFrequencyInfo>());
2691 MLI = &getAnalysis<MachineLoopInfo>();
2698 PreferredLoopExit =
nullptr;
2700 assert(BlockToChain.empty() &&
2701 "BlockToChain map should be empty before starting placement.");
2702 assert(ComputedEdges.empty() &&
2703 "Computed Edge map should be empty before starting placement.");
2724 MPDT = &getAnalysis<MachinePostDominatorTree>();
2727 TailDup.initMF(MF, MBPI,
true, TailDupSize);
2728 precomputeTriangleChains();
2740 if (MF.
size() > 3 && EnableTailMerge) {
2743 *MBPI, TailMergeSize);
2746 getAnalysisIfAvailable<MachineModuleInfo>(), MLI,
2749 BlockToChain.clear();
2750 ComputedEdges.clear();
2753 MPDT->runOnMachineFunction(MF);
2754 ChainAllocator.DestroyAll();
2762 BlockToChain.clear();
2763 ComputedEdges.clear();
2764 ChainAllocator.DestroyAll();
2773 for (
auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
2774 auto LayoutPred = std::prev(MBI);
2782 MBFI->view(
"MBP." + MF.getName(),
false);
2825 "Basic Block Placement Stats",
false,
false)
2831 bool MachineBlockPlacementStats::runOnMachineFunction(
MachineFunction &F) {
2833 if (std::next(F.begin()) == F.end())
2836 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
2837 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2842 (MBB.
succ_size() > 1) ? NumCondBranches : NumUncondBranches;
2844 (MBB.
succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
2851 BlockFreq * MBPI->getEdgeProbability(&MBB, Succ);
unsigned succ_size() const
static cl::opt< unsigned > AlignAllBlock("align-all-blocks", cl::desc("Force the alignment of all ""blocks in the function."), cl::init(0), cl::Hidden)
void push_back(const T &Elt)
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
bool isEHPad() const
Returns true if the block is a landing pad.
const_iterator end(StringRef path)
Get end iterator over path.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
typename SuperClass::const_iterator const_iterator
STATISTIC(NumFunctions,"Total number of functions")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
static BranchProbability getAdjustedProbability(BranchProbability OrigProb, BranchProbability AdjustedSumProb)
The helper function returns the branch probability that is adjusted or normalized over the new total ...
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
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 > 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)
void initializeMachineBlockPlacementStatsPass(PassRegistry &)
An efficient, type-erasing, non-owning reference to a callable.
uint32_t getNumerator() const
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
static BranchProbability getLayoutSuccessorProbThreshold(const MachineBasicBlock *BB)
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
static BranchProbability getOne()
const std::vector< BlockT * > & getBlocks() const
Get a list of the basic blocks which make up this loop.
char & MachineBlockPlacementStatsID
MachineBlockPlacementStats - This pass collects statistics about the basic block placement using bran...
bool optForSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
void setAlignment(unsigned Align)
Set alignment of the basic block.
BlockT * getHeader() const
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
iterator_range< succ_iterator > successors()
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
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)."), cl::init(0), cl::Hidden)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
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...
CodeGenOpt::Level getOptLevel() const
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
static cl::opt< bool > Aggressive("aggressive-ext-opt", cl::Hidden, cl::desc("Aggressive extension optimization"))
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
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)
friend const_iterator begin(StringRef path, Style style)
Get begin iterator over path.
block placement Basic Block Placement Stats
Target-Independent Code Generator Pass Configuration Options.
LLVM_NODISCARD bool empty() const
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Optional< uint64_t > getEntryCount() const
Get the entry count for this function.
cl::opt< std::string > ViewBlockFreqFuncName
TargetInstrInfo - Interface to description of machine instruction set.
iterator find(const_arg_type_t< KeyT > Val)
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)
cl::opt< unsigned > ProfileLikelyProb
initializer< Ty > init(const Ty &Val)
bool erase(const KeyT &Val)
cl::opt< GVDAGType > ViewBlockLayoutWithBFI
friend const_iterator end(StringRef path)
Get end iterator over path.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
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(3), cl::Hidden)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
bool getEnableTailMerge() const
static bool greaterWithBias(BlockFrequency A, BlockFrequency B, uint64_t EntryFreq)
Compare 2 BlockFrequency's with a small penalty for A.
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)
iterator_range< pred_iterator > predecessors()
LLVM_NODISCARD bool empty() const
succ_iterator succ_begin()
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)
iterator erase(const_iterator CI)
pred_iterator pred_begin()
void initializeMachineBlockPlacementPass(PassRegistry &)
static cl::opt< unsigned > TailMergeSize("tail-merge-size", cl::desc("Min number of instructions to consider tail merging"), cl::init(3), cl::Hidden)
Branch Probability Basic Block Placement
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE,"Branch Probability Basic Block Placement", false, false) INITIALIZE_PASS_END(MachineBlockPlacement
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
virtual const TargetLowering * getTargetLowering() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void updateTerminator()
Update the terminator instructions in block to account for changes to the layout. ...
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 > JumpInstCost("jump-inst-cost", cl::desc("Cost of jump instructions."), cl::init(1), cl::Hidden)
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
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.
A BumpPtrAllocator that allows only elements of a specific type to be allocated.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
void setPreservesAll()
Set by analyses that do not transform their input at all.
typename SuperClass::iterator iterator
unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const override
Remove the branching code at the end of the specific MBB.
Branch Probability Basic Block static false std::string getBlockName(const MachineBasicBlock *BB)
Helper to print the name of a MBB.
cl::opt< unsigned > StaticLikelyProb
block_iterator block_end() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
static uint64_t getMaxFrequency()
Returns the maximum possible frequency, the saturation value.
void emplace_back(ArgTypes &&...Args)
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)
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
char & MachineBlockPlacementID
MachineBlockPlacement - This pass places basic blocks based on branch probabilities.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
static bool hasSameSuccessors(MachineBasicBlock &BB, SmallPtrSetImpl< const MachineBasicBlock * > &Successors)
Check if BB has exactly the successors in Successors.
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)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
virtual const TargetInstrInfo * getInstrInfo() const
Branch Probability Basic Block false
block_iterator block_begin() const
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
static BranchProbability getZero()
Utility class to perform tail duplication.
bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
static cl::opt< bool > TailDupPlacement("tail-dup-placement", cl::desc("Perform tail duplication during placement. ""Creates more fallthrough opportunites in ""outline branches."), cl::init(true), cl::Hidden)
bool requiresStructuredCFG() const
unsigned pred_size() const
This file describes how to lower LLVM code to machine code.
BranchProbability getCompl() const