76 #define DEBUG_TYPE "block-placement" 78 STATISTIC(NumCondBranches,
"Number of conditional branches");
79 STATISTIC(NumUncondBranches,
"Number of unconditional branches");
81 "Potential frequency of taking conditional branches");
83 "Potential frequency of taking unconditional branches");
87 cl::desc(
"Force the alignment of all blocks in the function in log2 format " 88 "(e.g 4 means align on 16B boundaries)."),
92 "align-all-nofallthru-blocks",
93 cl::desc(
"Force the alignment of all blocks that have no fall-through " 94 "predecessors (i.e. don't add nops that are executed). In log2 " 95 "format (e.g 4 means align on 16B boundaries)."),
100 "block-placement-exit-block-bias",
101 cl::desc(
"Block frequency percentage a loop exit block needs " 102 "over the original exit to be considered the new exit."),
109 "loop-to-cold-block-ratio",
110 cl::desc(
"Outline loop blocks from loop chain if (frequency of loop) / " 111 "(frequency of block) is greater than this ratio"),
115 "force-loop-cold-block",
116 cl::desc(
"Force outlining cold blocks from loops."),
121 cl::desc(
"Model the cost of loop rotation more " 122 "precisely by using profile data."),
127 cl::desc(
"Force the use of precise cost " 128 "loop rotation strategy."),
133 cl::desc(
"Cost that models the probabilistic risk of an instruction " 134 "misfetch due to a jump comparing to falling through, whose cost " 139 cl::desc(
"Cost of jump instructions."),
143 cl::desc(
"Perform tail duplication during placement. " 144 "Creates more fallthrough opportunites in " 145 "outline branches."),
150 cl::desc(
"Perform branch folding during placement. " 151 "Reduces code size."),
156 "tail-dup-placement-threshold",
157 cl::desc(
"Instruction cutoff for tail duplication during layout. " 158 "Tail merging during layout is forced to have a threshold " 159 "that won't conflict."),
cl::init(2),
164 "tail-dup-placement-aggressive-threshold",
165 cl::desc(
"Instruction cutoff for aggressive tail duplication during " 166 "layout. Used at -O3. Tail merging during layout is forced to " 167 "have a threshold that won't conflict."),
cl::init(4),
172 "tail-dup-placement-penalty",
173 cl::desc(
"Cost penalty for blocks that can avoid breaking CFG by copying. " 174 "Copying can increase fallthrough, but it also increases icache " 175 "pressure. This parameter controls the penalty to account for that. " 176 "Percent as integer."),
182 "triangle-chain-count",
183 cl::desc(
"Number of triangle-shaped-CFG's that need to be in a row for the " 184 "triangle tail duplication heuristic to kick in. 0 to disable."),
231 BlockToChainMapType &BlockToChain;
240 : Blocks(1, BB), BlockToChain(BlockToChain) {
241 assert(BB &&
"Cannot create a chain with a null basic block");
242 BlockToChain[BB] =
this;
251 const_iterator
begin()
const {
return Blocks.
begin(); }
254 iterator
end() {
return Blocks.
end(); }
255 const_iterator
end()
const {
return Blocks.
end(); }
258 for(iterator i =
begin(); i !=
end(); ++i) {
274 assert(BB &&
"Can't merge a null block.");
275 assert(!Blocks.
empty() &&
"Can't merge into an empty chain.");
279 assert(!BlockToChain[BB] &&
280 "Passed chain is null, but BB has entry in BlockToChain.");
282 BlockToChain[BB] =
this;
286 assert(BB == *Chain->begin() &&
"Passed BB is not head of Chain.");
287 assert(Chain->begin() != Chain->end());
293 assert(BlockToChain[ChainBB] == Chain &&
"Incoming blocks not in chain.");
294 BlockToChain[ChainBB] =
this;
315 unsigned UnscheduledPredecessors = 0;
323 struct BlockAndTailDupResult {
329 struct WeightedEdge {
349 std::unique_ptr<BranchFolder::MBFIWrapper> MBFI;
404 void markChainSuccessors(
406 const BlockFilterSet *BlockFilter =
nullptr);
410 void markBlockSuccessors(
413 const BlockFilterSet *BlockFilter =
nullptr);
416 collectViableSuccessors(
418 const BlockFilterSet *BlockFilter,
420 bool shouldPredBlockBeOutlined(
422 const BlockChain &Chain,
const BlockFilterSet *BlockFilter,
424 bool repeatedlyTailDuplicateBlock(
427 BlockChain &Chain, BlockFilterSet *BlockFilter,
429 bool maybeTailDuplicateBlock(
431 BlockChain &Chain, BlockFilterSet *BlockFilter,
433 bool &DuplicatedToLPred);
434 bool hasBetterLayoutPredecessor(
438 const BlockFilterSet *BlockFilter);
439 BlockAndTailDupResult selectBestSuccessor(
441 const BlockFilterSet *BlockFilter);
445 const BlockChain &PlacedChain,
447 const BlockFilterSet *BlockFilter);
456 const BlockFilterSet *BlockFilter);
459 BlockFilterSet *BlockFilter =
nullptr);
463 const BlockFilterSet &LoopBlockSet);
465 const BlockFilterSet &LoopBlockSet);
469 const BlockFilterSet &LoopBlockSet);
471 const MachineLoop &L,
const BlockFilterSet &LoopBlockSet);
473 const MachineLoop &L,
const BlockFilterSet &LoopBlockSet);
475 const MachineLoop &L,
const BlockFilterSet &LoopBlockSet,
477 BlockFilterSet collectLoopBlockSet(
const MachineLoop &L);
482 void rotateLoopWithProfile(
484 const BlockFilterSet &LoopBlockSet);
485 void buildCFGChains();
486 void optimizeBranches();
493 bool isProfitableToTailDup(
496 const BlockChain &Chain,
const BlockFilterSet *BlockFilter);
501 const BlockChain &Chain,
const BlockFilterSet *BlockFilter);
504 BlockAndTailDupResult getBestTrellisSuccessor(
508 const BlockFilterSet *BlockFilter);
511 static std::pair<WeightedEdge, WeightedEdge> getBestNonConflictingEdges(
517 bool canTailDuplicateUnplacedPreds(
519 const BlockChain &Chain,
const BlockFilterSet *BlockFilter);
523 void precomputeTriangleChains();
534 bool allowTailDupPlacement()
const {
558 "Branch Probability Basic Block Placement",
false,
false)
575 OS <<
" ('" << BB->
getName() <<
"')";
587 void MachineBlockPlacement::markChainSuccessors(
589 const BlockFilterSet *BlockFilter) {
593 markBlockSuccessors(Chain, MBB, LoopHeaderBB, BlockFilter);
603 void MachineBlockPlacement::markBlockSuccessors(
611 if (BlockFilter && !BlockFilter->count(Succ))
613 BlockChain &SuccChain = *BlockToChain[Succ];
615 if (&Chain == &SuccChain || Succ == LoopHeaderBB)
620 if (SuccChain.UnscheduledPredecessors == 0 ||
621 --SuccChain.UnscheduledPredecessors > 0)
624 auto *NewBB = *SuccChain.begin();
625 if (NewBB->isEHPad())
638 const BlockFilterSet *BlockFilter,
658 bool SkipSucc =
false;
659 if (Succ->isEHPad() || (BlockFilter && !BlockFilter->count(Succ))) {
662 BlockChain *SuccChain = BlockToChain[Succ];
663 if (SuccChain == &Chain) {
665 }
else if (Succ != *SuccChain->begin()) {
667 <<
" -> Mid chain!\n");
677 return AdjustedSumProb;
688 if (SuccProbN >= SuccProbD)
703 if (Successors.
count(&BB))
706 if (!Successors.
count(Succ))
732 uint64_t EntryFreq) {
735 return (Gain / ThresholdProb).getFrequency() >= EntryFreq;
743 bool MachineBlockPlacement::isProfitableToTailDup(
746 const BlockChain &Chain,
const BlockFilterSet *BlockFilter) {
773 auto AdjustedSuccSumProb =
774 collectViableSuccessors(Succ, Chain, BlockFilter, SuccSuccs);
776 auto BBFreq = MBFI->getBlockFreq(BB);
777 auto SuccFreq = MBFI->getBlockFreq(Succ);
780 uint64_t EntryFreq = MBFI->getEntryFreq();
783 if (SuccSuccs.
size() == 0)
790 if (Prob > BestSuccSucc)
802 if (SuccPred == Succ || SuccPred == BB
803 || BlockToChain[SuccPred] == &Chain
804 || (BlockFilter && !BlockFilter->count(SuccPred)))
806 auto Freq = MBFI->getBlockFreq(SuccPred)
808 if (Freq > SuccBestPred)
876 if (UProb > AdjustedSuccSumProb / 2 &&
877 !hasBetterLayoutPredecessor(Succ, PDom, *BlockToChain[PDom], UProb, UProb,
881 (P + V), (Qout +
std::max(Qin, F) * VProb + std::min(Qin, F) * UProb),
885 (Qout + std::min(Qin, F) * AdjustedSuccSumProb +
897 bool MachineBlockPlacement::isTrellis(
900 const BlockChain &Chain,
const BlockFilterSet *BlockFilter) {
915 if (Successors.count(SuccPred)) {
918 if (!Successors.count(CheckSucc))
922 const BlockChain *PredChain = BlockToChain[SuccPred];
923 if (SuccPred == BB || (BlockFilter && !BlockFilter->count(SuccPred)) ||
924 PredChain == &Chain || PredChain == BlockToChain[Succ])
928 if (!SeenPreds.
insert(SuccPred).second)
946 std::pair<MachineBlockPlacement::WeightedEdge,
947 MachineBlockPlacement::WeightedEdge>
948 MachineBlockPlacement::getBestNonConflictingEdges(
959 auto Cmp = [](WeightedEdge A, WeightedEdge
B) {
return A.Weight >
B.Weight; };
963 auto BestA = Edges[0].begin();
964 auto BestB = Edges[1].begin();
967 if (BestA->Src == BestB->Src) {
969 auto SecondBestA = std::next(BestA);
970 auto SecondBestB = std::next(BestB);
973 if (BestAScore < BestBScore)
979 if (BestB->Src == BB)
981 return std::make_pair(*BestA, *BestB);
991 MachineBlockPlacement::BlockAndTailDupResult
992 MachineBlockPlacement::getBestTrellisSuccessor(
996 const BlockFilterSet *BlockFilter) {
998 BlockAndTailDupResult Result = {
nullptr,
false};
1005 if (Successors.
size() != 2 || ViableSuccs.
size() != 2)
1011 for (
auto Succ : ViableSuccs) {
1015 if ((BlockFilter && !BlockFilter->count(SuccPred)) ||
1016 BlockToChain[SuccPred] == &Chain ||
1017 BlockToChain[SuccPred] == BlockToChain[Succ])
1021 Edges[SuccIndex].
push_back({EdgeFreq, SuccPred, Succ});
1027 WeightedEdge BestA, BestB;
1028 std::tie(BestA, BestB) = getBestNonConflictingEdges(BB, Edges);
1030 if (BestA.Src != BB) {
1034 LLVM_DEBUG(
dbgs() <<
"Trellis, but not one of the chosen edges.\n");
1041 if (BestA.Dest == BestB.Src) {
1047 if (allowTailDupPlacement() && shouldTailDuplicate(Succ2) &&
1048 canTailDuplicateUnplacedPreds(BB, Succ2, Chain, BlockFilter) &&
1050 Chain, BlockFilter)) {
1054 <<
", probability: " << Succ2Prob
1055 <<
" (Tail Duplicate)\n");
1057 Result.ShouldTailDup =
true;
1063 ComputedEdges[BestB.Src] = { BestB.Dest,
false };
1065 auto TrellisSucc = BestA.Dest;
1069 <<
", probability: " << SuccProb <<
" (Trellis)\n");
1070 Result.BB = TrellisSucc;
1077 bool MachineBlockPlacement::canTailDuplicateUnplacedPreds(
1079 const BlockChain &Chain,
const BlockFilterSet *BlockFilter) {
1080 if (!shouldTailDuplicate(Succ))
1084 bool Duplicate =
true;
1086 unsigned int NumDup = 0;
1095 if (Pred == BB || (BlockFilter && !BlockFilter->count(Pred))
1096 || BlockToChain[Pred] == &Chain)
1175 if ((NumDup > Succ->
succ_size()) || !Duplicate)
1198 void MachineBlockPlacement::precomputeTriangleChains() {
1199 struct TriangleChain {
1200 std::vector<MachineBasicBlock *> Edges;
1203 : Edges({src, dst}) {}
1206 assert(getKey()->isSuccessor(dst) &&
1207 "Attempting to append a block that is not a successor.");
1208 Edges.push_back(dst);
1211 unsigned count()
const {
return Edges.size() - 1; }
1214 return Edges.
back();
1238 if (PDom ==
nullptr)
1245 if (!shouldTailDuplicate(PDom))
1247 bool CanTailDuplicate =
true;
1254 CanTailDuplicate =
false;
1260 if (!CanTailDuplicate)
1267 auto Found = TriangleChainMap.
find(&BB);
1270 if (Found != TriangleChainMap.
end()) {
1271 TriangleChain Chain = std::move(Found->second);
1272 TriangleChainMap.
erase(Found);
1274 TriangleChainMap.
insert(std::make_pair(Chain.getKey(), std::move(Chain)));
1276 auto InsertResult = TriangleChainMap.
try_emplace(PDom, &BB, PDom);
1277 assert(InsertResult.second &&
"Block seen twice.");
1285 for (
auto &ChainPair : TriangleChainMap) {
1286 TriangleChain &Chain = ChainPair.second;
1293 Chain.Edges.pop_back();
1297 <<
" as pre-computed based on triangles.\n");
1299 auto InsertResult = ComputedEdges.
insert({src, {dst,
true}});
1300 assert(InsertResult.second &&
"Block seen twice.");
1342 bool MachineBlockPlacement::hasBetterLayoutPredecessor(
1346 const BlockFilterSet *BlockFilter) {
1349 if (SuccChain.UnscheduledPredecessors == 0)
1469 BlockFrequency CandidateEdgeFreq = MBFI->getBlockFreq(BB) * RealSuccProb;
1470 bool BadCFGConflict =
false;
1473 BlockChain *PredChain = BlockToChain[Pred];
1474 if (Pred == Succ || PredChain == &SuccChain ||
1475 (BlockFilter && !BlockFilter->count(Pred)) ||
1476 PredChain == &Chain || Pred != *std::prev(PredChain->end()) ||
1497 if (PredEdgeFreq * HotProb >= CandidateEdgeFreq * HotProb.
getCompl()) {
1498 BadCFGConflict =
true;
1503 if (BadCFGConflict) {
1505 << SuccProb <<
" (prob) (non-cold CFG conflict)\n");
1522 MachineBlockPlacement::BlockAndTailDupResult
1523 MachineBlockPlacement::selectBestSuccessor(
1525 const BlockFilterSet *BlockFilter) {
1528 BlockAndTailDupResult BestSucc = {
nullptr,
false };
1532 auto AdjustedSumProb =
1533 collectViableSuccessors(BB, Chain, BlockFilter, Successors);
1540 auto FoundEdge = ComputedEdges.
find(BB);
1541 if (FoundEdge != ComputedEdges.
end()) {
1543 ComputedEdges.
erase(FoundEdge);
1544 BlockChain *SuccChain = BlockToChain[Succ];
1545 if (BB->
isSuccessor(Succ) && (!BlockFilter || BlockFilter->count(Succ)) &&
1546 SuccChain != &Chain && Succ == *SuccChain->begin())
1547 return FoundEdge->second;
1552 if (isTrellis(BB, Successors, Chain, BlockFilter))
1553 return getBestTrellisSuccessor(BB, Successors, AdjustedSumProb, Chain,
1566 BlockChain &SuccChain = *BlockToChain[Succ];
1569 if (hasBetterLayoutPredecessor(BB, Succ, SuccChain, SuccProb, RealSuccProb,
1570 Chain, BlockFilter)) {
1572 if (allowTailDupPlacement() && shouldTailDuplicate(Succ))
1573 DupCandidates.
push_back(std::make_tuple(SuccProb, Succ));
1579 <<
", probability: " << SuccProb
1580 << (SuccChain.UnscheduledPredecessors != 0 ?
" (CFG break)" :
"")
1583 if (BestSucc.BB && BestProb >= SuccProb) {
1590 BestProb = SuccProb;
1598 [](std::tuple<BranchProbability, MachineBasicBlock *> L,
1599 std::tuple<BranchProbability, MachineBasicBlock *> R) {
1600 return std::get<0>(L) > std::get<0>(R);
1602 for (
auto &Tup : DupCandidates) {
1605 std::tie(DupProb, Succ) = Tup;
1606 if (DupProb < BestProb)
1608 if (canTailDuplicateUnplacedPreds(BB, Succ, Chain, BlockFilter)
1609 && (isProfitableToTailDup(BB, Succ, BestProb, Chain, BlockFilter))) {
1611 <<
", probability: " << DupProb
1612 <<
" (Tail Duplicate)\n");
1614 BestSucc.ShouldTailDup =
true;
1643 return BlockToChain.
lookup(BB) == &Chain;
1647 if (WorkList.
empty())
1650 bool IsEHPad = WorkList[0]->isEHPad();
1656 "EHPad mismatch between block and work list.");
1658 BlockChain &SuccChain = *BlockToChain[MBB];
1659 if (&SuccChain == &Chain)
1662 assert(SuccChain.UnscheduledPredecessors == 0 &&
1663 "Found CFG-violating block");
1667 MBFI->printBlockFreq(
dbgs(), CandidateFreq) <<
" (freq)\n");
1687 if (BestBlock && (IsEHPad ^ (BestFreq >= CandidateFreq)))
1691 BestFreq = CandidateFreq;
1705 const BlockChain &PlacedChain,
1707 const BlockFilterSet *BlockFilter) {
1710 if (BlockFilter && !BlockFilter->count(&*
I))
1712 if (BlockToChain[&*
I] != &PlacedChain) {
1713 PrevUnplacedBlockIt =
I;
1717 return *BlockToChain[&*
I]->
begin();
1723 void MachineBlockPlacement::fillWorkLists(
1726 const BlockFilterSet *BlockFilter =
nullptr) {
1727 BlockChain &Chain = *BlockToChain[MBB];
1728 if (!UpdatedPreds.
insert(&Chain).second)
1732 Chain.UnscheduledPredecessors == 0 &&
1733 "Attempting to place block with unscheduled predecessors in worklist.");
1735 assert(BlockToChain[ChainBB] == &Chain &&
1736 "Block in chain doesn't match BlockToChain map.");
1738 if (BlockFilter && !BlockFilter->count(Pred))
1740 if (BlockToChain[Pred] == &Chain)
1742 ++Chain.UnscheduledPredecessors;
1746 if (Chain.UnscheduledPredecessors != 0)
1756 void MachineBlockPlacement::buildChain(
1758 BlockFilterSet *BlockFilter) {
1759 assert(HeadBB &&
"BB must not be null.\n");
1760 assert(BlockToChain[HeadBB] == &Chain &&
"BlockToChainMap mis-match.\n");
1764 markChainSuccessors(Chain, LoopHeaderBB, BlockFilter);
1767 assert(BB &&
"null block found at end of chain in loop.");
1768 assert(BlockToChain[BB] == &Chain &&
"BlockToChainMap mis-match in loop.");
1769 assert(*std::prev(Chain.end()) == BB &&
"BB Not found at end of chain.");
1774 auto Result = selectBestSuccessor(BB, Chain, BlockFilter);
1776 bool ShouldTailDup = Result.ShouldTailDup;
1777 if (allowTailDupPlacement())
1778 ShouldTailDup |= (BestSucc && canTailDuplicateUnplacedPreds(BB, BestSucc,
1786 BestSucc = selectBestCandidateBlock(Chain, BlockWorkList);
1788 BestSucc = selectBestCandidateBlock(Chain, EHPadWorkList);
1791 BestSucc = getFirstUnplacedBlock(Chain, PrevUnplacedBlockIt, BlockFilter);
1795 LLVM_DEBUG(
dbgs() <<
"Unnatural loop CFG detected, forcibly merging the " 1796 "layout successor until the CFG reduces\n");
1801 if (allowTailDupPlacement() && BestSucc && ShouldTailDup) {
1805 if (repeatedlyTailDuplicateBlock(BestSucc, BB, LoopHeaderBB, Chain,
1806 BlockFilter, PrevUnplacedBlockIt))
1811 BlockChain &SuccChain = *BlockToChain[BestSucc];
1814 SuccChain.UnscheduledPredecessors = 0;
1817 markChainSuccessors(SuccChain, LoopHeaderBB, BlockFilter);
1818 Chain.merge(BestSucc, &SuccChain);
1819 BB = *std::prev(Chain.end());
1841 MachineBlockPlacement::canMoveBottomBlockToTop(
1851 if (OtherBB == BottomBlock)
1853 if (OtherBB == OldTop)
1861 MachineBlockPlacement::TopFallThroughFreq(
1863 const BlockFilterSet &LoopBlockSet) {
1866 BlockChain *PredChain = BlockToChain[Pred];
1867 if (!LoopBlockSet.count(Pred) &&
1868 (!PredChain || Pred == *std::prev(PredChain->end()))) {
1875 BlockChain *SuccChain = BlockToChain[Succ];
1878 if (!LoopBlockSet.count(Succ) && (SuccProb > TopProb) &&
1879 (!SuccChain || Succ == *SuccChain->begin())) {
1887 if (EdgeFreq > MaxFreq)
1917 MachineBlockPlacement::FallThroughGains(
1921 const BlockFilterSet &LoopBlockSet) {
1922 BlockFrequency FallThrough2Top = TopFallThroughFreq(OldTop, LoopBlockSet);
1925 FallThrough2Exit = MBFI->getBlockFreq(NewTop) *
1934 if (!LoopBlockSet.count(Pred))
1936 BlockChain *PredChain = BlockToChain[Pred];
1937 if (!PredChain || Pred == *std::prev(PredChain->end())) {
1940 if (EdgeFreq > FallThroughFromPred) {
1941 FallThroughFromPred = EdgeFreq;
1952 if ((Succ == NewTop) || (Succ == BestPred) || !LoopBlockSet.count(Succ))
1954 if (ComputedEdges.
find(Succ) != ComputedEdges.
end())
1956 BlockChain *SuccChain = BlockToChain[Succ];
1957 if ((SuccChain && (Succ != *SuccChain->begin())) ||
1958 (SuccChain == BlockToChain[BestPred]))
1962 if (EdgeFreq > NewFreq)
1967 if (NewFreq > OrigEdgeFreq) {
1972 FallThroughFromPred = 0;
1979 FallThroughFromPred;
1981 Result = Gains - Lost;
2008 MachineBlockPlacement::findBestLoopTopHelper(
2011 const BlockFilterSet &LoopBlockSet) {
2015 BlockChain &HeaderChain = *BlockToChain[OldTop];
2016 if (!LoopBlockSet.count(*HeaderChain.begin()))
2025 if (!LoopBlockSet.count(Pred))
2030 << Pred->succ_size() <<
" successors, ";
2031 MBFI->printBlockFreq(
dbgs(), Pred) <<
" freq\n");
2032 if (Pred->succ_size() > 2)
2036 if (Pred->succ_size() == 2) {
2038 if (OtherBB == OldTop)
2042 if (!canMoveBottomBlockToTop(Pred, OldTop))
2047 if ((Gains > 0) && (Gains > BestGains ||
2048 ((Gains == BestGains) && Pred->isLayoutSuccessor(OldTop)))) {
2075 MachineBlockPlacement::findBestLoopTop(
const MachineLoop &L,
2076 const BlockFilterSet &LoopBlockSet) {
2092 while (NewTop != OldTop) {
2094 NewTop = findBestLoopTopHelper(OldTop, L, LoopBlockSet);
2095 if (NewTop != OldTop)
2096 ComputedEdges[NewTop] = { OldTop,
false };
2107 MachineBlockPlacement::findBestLoopExit(
const MachineLoop &L,
2108 const BlockFilterSet &LoopBlockSet,
2118 BlockChain &HeaderChain = *BlockToChain[L.
getHeader()];
2119 if (!LoopBlockSet.count(*HeaderChain.begin()))
2123 unsigned BestExitLoopDepth = 0;
2133 BlockChain &Chain = *BlockToChain[MBB];
2136 if (MBB != *std::prev(Chain.end()))
2145 bool HasLoopingSucc =
false;
2151 BlockChain &SuccChain = *BlockToChain[Succ];
2153 if (&Chain == &SuccChain) {
2160 if (LoopBlockSet.count(Succ)) {
2163 HasLoopingSucc =
true;
2167 unsigned SuccLoopDepth = 0;
2169 SuccLoopDepth = ExitLoop->getLoopDepth();
2170 if (ExitLoop->contains(&L))
2171 BlocksExitingToOuterLoop.
insert(MBB);
2174 BlockFrequency ExitEdgeFreq = MBFI->getBlockFreq(MBB) * SuccProb;
2178 MBFI->printBlockFreq(
dbgs(), ExitEdgeFreq) <<
")\n");
2184 if (!ExitingBB || SuccLoopDepth > BestExitLoopDepth ||
2185 ExitEdgeFreq > BestExitEdgeFreq ||
2187 !(ExitEdgeFreq < BestExitEdgeFreq * Bias))) {
2188 BestExitEdgeFreq = ExitEdgeFreq;
2193 if (!HasLoopingSucc) {
2195 ExitingBB = OldExitingBB;
2196 BestExitEdgeFreq = OldBestExitEdgeFreq;
2203 dbgs() <<
" No other candidate exit blocks, using loop header\n");
2207 LLVM_DEBUG(
dbgs() <<
" Loop has 1 block, using loop header as exit\n");
2214 if (!BlocksExitingToOuterLoop.
empty() &&
2215 !BlocksExitingToOuterLoop.
count(ExitingBB))
2220 ExitFreq = BestExitEdgeFreq;
2229 MachineBlockPlacement::hasViableTopFallthrough(
2231 const BlockFilterSet &LoopBlockSet) {
2233 BlockChain *PredChain = BlockToChain[Pred];
2234 if (!LoopBlockSet.count(Pred) &&
2235 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2242 BlockChain *SuccChain = BlockToChain[Succ];
2245 if ((!SuccChain || Succ == *SuccChain->begin()) && SuccProb > TopProb) {
2263 void MachineBlockPlacement::rotateLoop(BlockChain &LoopChain,
2266 const BlockFilterSet &LoopBlockSet) {
2274 if (Bottom == ExitingBB)
2277 bool ViableTopFallthrough = hasViableTopFallthrough(Top, LoopBlockSet);
2282 if (ViableTopFallthrough) {
2284 BlockChain *SuccChain = BlockToChain[Succ];
2285 if (!LoopBlockSet.count(Succ) &&
2286 (!SuccChain || Succ == *SuccChain->begin()))
2292 BlockFrequency FallThrough2Top = TopFallThroughFreq(Top, LoopBlockSet);
2293 if (FallThrough2Top >= ExitFreq)
2297 BlockChain::iterator ExitIt =
llvm::find(LoopChain, ExitingBB);
2298 if (ExitIt == LoopChain.end())
2320 if (ViableTopFallthrough) {
2321 assert(std::next(ExitIt) != LoopChain.end() &&
2322 "Exit should not be last BB");
2331 std::rotate(LoopChain.begin(), std::next(ExitIt), LoopChain.end());
2347 void MachineBlockPlacement::rotateLoopWithProfile(
2349 const BlockFilterSet &LoopBlockSet) {
2350 auto RotationPos = LoopChain.end();
2371 BlockChain *PredChain = BlockToChain[Pred];
2372 if (!LoopBlockSet.count(Pred) &&
2373 (!PredChain || Pred == *std::prev(PredChain->end()))) {
2374 auto EdgeFreq = MBFI->getBlockFreq(Pred) *
2376 auto FallThruCost = ScaleBlockFrequency(EdgeFreq,
MisfetchCost);
2379 if (Pred->succ_size() == 1)
2380 FallThruCost += ScaleBlockFrequency(EdgeFreq,
JumpInstCost);
2381 HeaderFallThroughCost =
std::max(HeaderFallThroughCost, FallThruCost);
2390 for (
auto BB : LoopChain) {
2393 BlockChain *SuccChain = BlockToChain[Succ];
2394 if (!LoopBlockSet.count(Succ) &&
2395 (!SuccChain || Succ == *SuccChain->begin())) {
2397 LargestExitEdgeProb =
std::max(LargestExitEdgeProb, SuccProb);
2401 auto ExitFreq = MBFI->getBlockFreq(BB) * LargestExitEdgeProb;
2409 for (
auto Iter = LoopChain.begin(), TailIter = std::prev(LoopChain.end()),
2410 EndIter = LoopChain.end();
2411 Iter != EndIter; Iter++, TailIter++) {
2414 if (TailIter == LoopChain.end())
2415 TailIter = LoopChain.begin();
2417 auto TailBB = *TailIter;
2425 if (Iter != LoopChain.begin())
2426 Cost += HeaderFallThroughCost;
2430 for (
auto &ExitWithFreq : ExitsWithFreq)
2431 if (TailBB != ExitWithFreq.first)
2432 Cost += ExitWithFreq.second;
2448 if (TailBB->isSuccessor(*Iter)) {
2449 auto TailBBFreq = MBFI->getBlockFreq(TailBB);
2450 if (TailBB->succ_size() == 1)
2451 Cost += ScaleBlockFrequency(TailBBFreq.getFrequency(),
2453 else if (TailBB->succ_size() == 2) {
2455 auto TailToHeadFreq = TailBBFreq * TailToHeadProb;
2457 ? TailBBFreq * TailToHeadProb.
getCompl()
2459 Cost += ScaleBlockFrequency(TailToHeadFreq,
MisfetchCost) +
2468 if (Cost < SmallestRotationCost) {
2469 SmallestRotationCost = Cost;
2474 if (RotationPos != LoopChain.end()) {
2476 <<
" to the top\n");
2477 std::rotate(LoopChain.begin(), RotationPos, LoopChain.end());
2486 MachineBlockPlacement::collectLoopBlockSet(
const MachineLoop &L) {
2487 BlockFilterSet LoopBlockSet;
2502 LoopFreq += MBFI->getBlockFreq(LoopPred) *
2506 auto Freq = MBFI->getBlockFreq(LoopBB).getFrequency();
2509 LoopBlockSet.insert(LoopBB);
2514 return LoopBlockSet;
2523 void MachineBlockPlacement::buildLoopChains(
const MachineLoop &L) {
2527 buildLoopChains(*InnerLoop);
2530 "BlockWorkList not empty when starting to build loop chains.");
2532 "EHPadWorkList not empty when starting to build loop chains.");
2533 BlockFilterSet LoopBlockSet = collectLoopBlockSet(L);
2538 bool RotateLoopWithProfile =
2554 PreferredLoopExit =
nullptr;
2556 if (!RotateLoopWithProfile && LoopTop == L.getHeader())
2557 PreferredLoopExit = findBestLoopExit(L, LoopBlockSet, ExitFreq);
2559 BlockChain &LoopChain = *BlockToChain[LoopTop];
2565 assert(LoopChain.UnscheduledPredecessors == 0 &&
2566 "LoopChain should not have unscheduled predecessors.");
2567 UpdatedPreds.
insert(&LoopChain);
2570 fillWorkLists(LoopBB, UpdatedPreds, &LoopBlockSet);
2572 buildChain(LoopTop, LoopChain, &LoopBlockSet);
2574 if (RotateLoopWithProfile)
2575 rotateLoopWithProfile(LoopChain, L, LoopBlockSet);
2577 rotateLoop(LoopChain, PreferredLoopExit, ExitFreq, LoopBlockSet);
2581 bool BadLoop =
false;
2582 if (LoopChain.UnscheduledPredecessors) {
2584 dbgs() <<
"Loop chain contains a block without its preds placed!\n" 2585 <<
" Loop header: " << getBlockName(*L.block_begin()) <<
"\n" 2586 <<
" Chain header: " << getBlockName(*LoopChain.begin()) <<
"\n";
2590 if (!LoopBlockSet.remove(ChainBB)) {
2594 dbgs() <<
"Loop chain contains a block not contained by the loop!\n" 2595 <<
" Loop header: " <<
getBlockName(*L.block_begin()) <<
"\n" 2596 <<
" Chain header: " <<
getBlockName(*LoopChain.begin()) <<
"\n" 2601 if (!LoopBlockSet.empty()) {
2604 dbgs() <<
"Loop contains blocks never placed into a chain!\n" 2605 <<
" Loop header: " <<
getBlockName(*L.block_begin()) <<
"\n" 2606 <<
" Chain header: " <<
getBlockName(*LoopChain.begin()) <<
"\n" 2609 assert(!BadLoop &&
"Detected problems with the placement of this loop.");
2612 BlockWorkList.
clear();
2613 EHPadWorkList.
clear();
2616 void MachineBlockPlacement::buildCFGChains() {
2624 new (ChainAllocator.
Allocate()) BlockChain(BlockToChain, BB);
2630 if (!TII->
analyzeBranch(*BB, TBB, FBB, Cond) || !FI->canFallThrough())
2637 assert(NextFI != FE &&
"Can't fallthrough past the last block.");
2638 LLVM_DEBUG(
dbgs() <<
"Pre-merging due to unanalyzable fallthrough: " 2641 Chain->merge(NextBB,
nullptr);
2643 BlocksWithUnanalyzableExits.
insert(&*BB);
2651 PreferredLoopExit =
nullptr;
2653 buildLoopChains(*L);
2656 "BlockWorkList should be empty before building final chain.");
2658 "EHPadWorkList should be empty before building final chain.");
2662 fillWorkLists(&MBB, UpdatedPreds);
2664 BlockChain &FunctionChain = *BlockToChain[&F->front()];
2665 buildChain(&F->front(), FunctionChain);
2672 bool BadFunc =
false;
2673 FunctionBlockSetType FunctionBlockSet;
2675 FunctionBlockSet.insert(&MBB);
2678 if (!FunctionBlockSet.erase(ChainBB)) {
2680 dbgs() <<
"Function chain contains a block not in the function!\n" 2684 if (!FunctionBlockSet.empty()) {
2687 dbgs() <<
"Function contains blocks never placed into a chain!\n" 2688 <<
" Bad block: " <<
getBlockName(RemainingBB) <<
"\n";
2690 assert(!BadFunc &&
"Detected problems with the block placement.");
2695 LLVM_DEBUG(
dbgs() <<
"[MBP] Function: " << F->getName() <<
"\n");
2697 LLVM_DEBUG(
dbgs() << (ChainBB == *FunctionChain.begin() ?
"Placing chain " 2701 F->splice(InsertPos, ChainBB);
2706 if (ChainBB == *FunctionChain.begin())
2717 if (!BlocksWithUnanalyzableExits.
count(PrevBB)) {
2723 "Unexpected block with un-analyzable fallthrough!");
2725 TBB = FBB =
nullptr;
2758 F->
back().updateTerminator();
2760 BlockWorkList.
clear();
2761 EHPadWorkList.
clear();
2764 void MachineBlockPlacement::optimizeBranches() {
2765 BlockChain &FunctionChain = *BlockToChain[&F->
front()];
2780 if (TBB && !Cond.
empty() && FBB &&
2792 ChainBB->updateTerminator();
2798 void MachineBlockPlacement::alignBlocks() {
2807 BlockChain &FunctionChain = *BlockToChain[&F->
front()];
2808 if (FunctionChain.begin() == FunctionChain.end())
2815 if (ChainBB == *FunctionChain.begin())
2833 if (Freq < WeightedEntryFreq)
2840 if (Freq < (LoopHeaderFreq * ColdProb))
2856 ChainBB->setAlignment(Align);
2866 BlockFrequency LayoutEdgeFreq = MBFI->getBlockFreq(LayoutPred) * LayoutProb;
2867 if (LayoutEdgeFreq <= (Freq * ColdProb))
2868 ChainBB->setAlignment(Align);
2887 bool MachineBlockPlacement::repeatedlyTailDuplicateBlock(
2890 BlockChain &Chain, BlockFilterSet *BlockFilter,
2892 bool Removed, DuplicatedToLPred;
2893 bool DuplicatedToOriginalLPred;
2894 Removed = maybeTailDuplicateBlock(BB, LPred, Chain, BlockFilter,
2895 PrevUnplacedBlockIt,
2899 DuplicatedToOriginalLPred = DuplicatedToLPred;
2905 while (DuplicatedToLPred) {
2906 assert(Removed &&
"Block must have been removed to be duplicated into its " 2907 "layout predecessor.");
2914 BlockChain::iterator ChainEnd = Chain.end();
2915 DupBB = *(--ChainEnd);
2917 if (ChainEnd == Chain.begin())
2919 DupPred = *std::prev(ChainEnd);
2920 Removed = maybeTailDuplicateBlock(DupBB, DupPred, Chain, BlockFilter,
2921 PrevUnplacedBlockIt,
2929 LPred = *std::prev(Chain.end());
2930 if (DuplicatedToOriginalLPred)
2931 markBlockSuccessors(Chain, LPred, LoopHeaderBB, BlockFilter);
2949 bool MachineBlockPlacement::maybeTailDuplicateBlock(
2951 BlockChain &Chain, BlockFilterSet *BlockFilter,
2953 bool &DuplicatedToLPred) {
2954 DuplicatedToLPred =
false;
2955 if (!shouldTailDuplicate(BB))
2963 bool Removed =
false;
2964 auto RemovalCallback =
2970 bool InWorkList =
true;
2972 if (BlockToChain.
count(RemBB)) {
2973 BlockChain *Chain = BlockToChain[RemBB];
2974 InWorkList = Chain->UnscheduledPredecessors == 0;
2975 Chain->remove(RemBB);
2976 BlockToChain.
erase(RemBB);
2980 if (&(*PrevUnplacedBlockIt) == RemBB) {
2981 PrevUnplacedBlockIt++;
2987 if (RemBB->isEHPad())
2988 RemoveList = EHPadWorkList;
2999 BlockFilter->remove(RemBB);
3004 if (RemBB == PreferredLoopExit)
3005 PreferredLoopExit =
nullptr;
3010 auto RemovalCallbackRef =
3016 &DuplicatedPreds, &RemovalCallbackRef);
3019 DuplicatedToLPred =
false;
3022 BlockChain* PredChain = BlockToChain[Pred];
3024 DuplicatedToLPred =
true;
3025 if (Pred == LPred || (BlockFilter && !BlockFilter->count(Pred))
3026 || PredChain == &Chain)
3029 if (BlockFilter && !BlockFilter->count(NewSucc))
3031 BlockChain *NewChain = BlockToChain[NewSucc];
3032 if (NewChain != &Chain && NewChain != PredChain)
3033 NewChain->UnscheduledPredecessors++;
3039 bool MachineBlockPlacement::runOnMachineFunction(
MachineFunction &MF) {
3044 if (std::next(MF.
begin()) == MF.
end())
3048 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
3049 MBFI = std::make_unique<BranchFolder::MBFIWrapper>(
3050 getAnalysis<MachineBlockFrequencyInfo>());
3051 MLI = &getAnalysis<MachineLoopInfo>();
3055 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
3059 PreferredLoopExit =
nullptr;
3062 "BlockToChain map should be empty before starting placement.");
3064 "Computed Edge map should be empty before starting placement.");
3084 if (allowTailDupPlacement()) {
3085 MPDT = &getAnalysis<MachinePostDominatorTree>();
3090 bool PreRegAlloc =
false;
3091 TailDup.
initMF(MF, PreRegAlloc, MBPI, &MBFI->getMBFI(), PSI,
3093 precomputeTriangleChains();
3105 if (MF.
size() > 3 && EnableTailMerge) {
3108 *MBPI, PSI, TailMergeSize);
3110 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
3112 MMIWP ? &MMIWP->getMMI() :
nullptr, MLI,
3115 BlockToChain.
clear();
3116 ComputedEdges.
clear();
3128 BlockToChain.
clear();
3129 ComputedEdges.
clear();
3139 for (
auto MBI = std::next(MF.begin()), MBE = MF.end(); MBI != MBE; ++MBI) {
3140 auto LayoutPred = std::prev(MBI);
3141 if (!LayoutPred->isSuccessor(&*MBI))
3145 if (ViewBlockLayoutWithBFI !=
GVDT_None &&
3146 (ViewBlockFreqFuncName.empty() ||
3148 MBFI->view(
"MBP." + MF.getName(),
false);
3196 "Basic Block Placement Stats",
false,
false)
3200 "Basic Block Placement
Stats", false, false)
3202 bool MachineBlockPlacementStats::runOnMachineFunction(
MachineFunction &F) {
3204 if (std::next(F.begin()) == F.end())
3207 MBPI = &getAnalysis<MachineBranchProbabilityInfo>();
3208 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
3213 (MBB.
succ_size() > 1) ? NumCondBranches : NumUncondBranches;
3215 (MBB.
succ_size() > 1) ? CondBranchTakenFreq : UncondBranchTakenFreq;
bool shouldTailDuplicate(bool IsSimple, MachineBasicBlock &TailBB)
Determine if it is profitable to duplicate this block.
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)
const_iterator end(StringRef path)
Get end iterator over path.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
reference emplace_back(ArgTypes &&... Args)
void initMF(MachineFunction &MF, bool PreRegAlloc, const MachineBranchProbabilityInfo *MBPI, const MachineBlockFrequencyInfo *MBFI, ProfileSummaryInfo *PSI, bool LayoutMode, unsigned TailDupSize=0)
Prepare to run on a specific machine function.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
BranchProbability getCompl() const
bool dominates(const MachineDomTreeNode *A, const MachineDomTreeNode *B) const
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
typename SuperClass::const_iterator const_iterator
This class represents lattice values for constants.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
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)
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
static BranchProbability getAdjustedProbability(BranchProbability OrigProb, BranchProbability AdjustedSumProb)
The helper function returns the branch probability that is adjusted or normalized over the new total ...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
void push_back(const T &Elt)
bool requiresStructuredCFG() const
Analysis providing profile information.
virtual const TargetLowering * getTargetLowering() const
void initializeMachineBlockPlacementStatsPass(PassRegistry &)
virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const
Insert branch code into the end of the specified MachineBasicBlock.
An efficient, type-erasing, non-owning reference to a callable.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
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)
STATISTIC(NumFunctions, "Total number of functions")
static BranchProbability getLayoutSuccessorProbThreshold(const MachineBasicBlock *BB)
static BranchProbability getOne()
virtual unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const
Remove the branching code at the end of the specific MBB.
char & MachineBlockPlacementStatsID
MachineBlockPlacementStats - This pass collects statistics about the basic block placement using bran...
CodeGenOpt::Level getOptLevel() 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...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
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.
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 OptimizeFunction(MachineFunction &MF, const TargetInstrInfo *tii, const TargetRegisterInfo *tri, MachineModuleInfo *mmi, MachineLoopInfo *mli=nullptr, bool AfterPlacement=false)
Perhaps branch folding, tail merging and other CFG optimizations on the given function.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void removeBlock(MachineBasicBlock *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
block placement Basic Block Placement Stats
Target-Independent Code Generator Pass Configuration Options.
BlockT * getHeader() const
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
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)
bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
void DestroyAll()
Call the destructor of each allocated object and deallocate all but the current slab and reset the cu...
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
virtual const TargetInstrInfo * getInstrInfo() const
cl::opt< std::string > ViewBlockFreqFuncName
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
TargetInstrInfo - Interface to description of machine instruction set.
iterator find(const_arg_type_t< KeyT > Val)
static bool isSimpleBB(MachineBasicBlock *TailBB)
True if this BB has only one unconditional jump.
cl::opt< unsigned > ProfileLikelyProb
bool getEnableTailMerge() const
virtual bool alignLoopsWithOptSize() const
Should loops be aligned even when the function is marked OptSize (but not MinSize).
bool tailDuplicateAndUpdate(bool IsSimple, MachineBasicBlock *MBB, MachineBasicBlock *ForcedLayoutPred, SmallVectorImpl< MachineBasicBlock *> *DuplicatedPreds=nullptr, function_ref< void(MachineBasicBlock *)> *RemovalCallback=nullptr)
Tail duplicate a single basic block into its predecessors, and then clean up.
initializer< Ty > init(const Ty &Val)
bool erase(const KeyT &Val)
cl::opt< GVDAGType > ViewBlockLayoutWithBFI
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
succ_reverse_iterator succ_rbegin()
static cl::opt< bool > BranchFoldPlacement("branch-fold-placement", cl::desc("Perform branch folding during placement. " "Reduces code size."), cl::init(true), cl::Hidden)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVM_NODISCARD bool empty() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool canTailDuplicate(MachineBasicBlock *TailBB, MachineBasicBlock *PredBB)
Returns true if TailBB can successfully be duplicated into PredBB.
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)
virtual Align getPrefLoopAlignment(MachineLoop *ML=nullptr) const
Return the preferred loop alignment.
Represent the analysis usage information of a pass.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
static bool greaterWithBias(BlockFrequency A, BlockFrequency B, uint64_t EntryFreq)
Compare 2 BlockFrequency's with a small penalty for A.
iterator_range< pred_iterator > predecessors()
bool hasProfileData(bool IncludeSynthetic=false) const
Return true if the function is annotated with profile data.
T * Allocate(size_t num=1)
Allocate space for an array of objects without constructing them.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
succ_iterator succ_begin()
virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e...
iterator erase(const_iterator CI)
const MachineBasicBlock & front() const
pred_iterator pred_begin()
void initializeMachineBlockPlacementPass(PassRegistry &)
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)
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
static cl::opt< unsigned > TailMergeSize("tail-merge-size", cl::desc("Min number of instructions to consider tail merging"), cl::init(3), cl::Hidden)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
This struct is a compact representation of a valid (non-zero power of two) alignment.
Branch Probability Basic Block Placement
This base class for TargetLowering contains the SelectionDAG-independent parts that can be used from ...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
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...
void setAlignment(Align A)
Set alignment of the basic block.
Align max(MaybeAlign Lhs, Align Rhs)
static cl::opt< bool > ForceLoopColdBlock("force-loop-cold-block", cl::desc("Force outlining cold blocks from loops."), cl::init(false), cl::Hidden)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
void updateTerminator()
Update the terminator instructions in block to account for changes to the layout. ...
static cl::opt< unsigned > JumpInstCost("jump-inst-cost", cl::desc("Cost of jump instructions."), cl::init(1), 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)
INITIALIZE_PASS_BEGIN(MachineBlockPlacement, DEBUG_TYPE, "Branch Probability Basic Block Placement", false, false) INITIALIZE_PASS_END(MachineBlockPlacement
A BumpPtrAllocator that allows only elements of a specific type to be allocated.
unsigned pred_size() const
bool isLayoutSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB will be emitted immediately after this block, such that if this bloc...
const Function & getFunction() const
Return the LLVM function that this machine code represents.
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.
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 setPreservesAll()
Set by analyses that do not transform their input at all.
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...
typename SuperClass::iterator iterator
unsigned succ_size() const
Branch Probability Basic Block static false std::string getBlockName(const MachineBasicBlock *BB)
Helper to print the name of a MBB.
cl::opt< unsigned > StaticLikelyProb
LLVM_NODISCARD bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
unsigned succ_size(const Instruction *I)
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
static uint64_t getMaxFrequency()
Returns the maximum possible frequency, the saturation value.
bool isEHPad() const
Returns true if the block is a landing pad.
LLVM_NODISCARD bool empty() const
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
static bool hasSameSuccessors(MachineBasicBlock &BB, SmallPtrSetImpl< const MachineBasicBlock *> &Successors)
Check if BB has exactly the successors in Successors.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
char & MachineBlockPlacementID
MachineBlockPlacement - This pass places basic blocks based on branch probabilities.
block_iterator block_end() const
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
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)
LLVM_NODISCARD bool empty() const
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
virtual bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const
Reverses the branch condition of the specified condition list, returning false on success and true if...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void stable_sort(R &&Range)
A raw_ostream that writes to an std::string.
MachinePostDominatorTree - an analysis pass wrapper for DominatorTree used to compute the post-domina...
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
static BranchProbability getZero()
Utility class to perform tail duplication.
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)
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
block_iterator block_begin() const
uint32_t getNumerator() const
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)
This file describes how to lower LLVM code to machine code.