63 #define DEBUG_TYPE "branch-folder"
65 STATISTIC(NumDeadBlocks,
"Number of dead blocks removed");
66 STATISTIC(NumBranchOpts,
"Number of branches optimized");
67 STATISTIC(NumTailMerge ,
"Number of block tails merged");
68 STATISTIC(NumHoist ,
"Number of times common instructions are hoisted");
69 STATISTIC(NumTailCalls,
"Number of tail calls optimized");
77 cl::desc(
"Max number of predecessors to consider tail merging"),
84 cl::desc(
"Min number of instructions to consider tail merging"),
112 "Control Flow Optimizer",
false,
false)
115 if (skipFunction(*MF.getFunction()))
121 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
124 getAnalysis<MachineBlockFrequencyInfo>());
126 getAnalysis<MachineBranchProbabilityInfo>());
128 MF.getSubtarget().getRegisterInfo(),
129 getAnalysisIfAvailable<MachineModuleInfo>());
135 unsigned MinTailLength)
136 : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength),
137 MBBFreqInfo(FreqInfo), MBPI(ProbInfo) {
138 if (MinCommonTailLength == 0)
141 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge;
break;
149 DEBUG(
dbgs() <<
"\nRemoving MBB: " << *MBB);
157 TriedMerging.erase(MBB);
161 FuncletMembership.erase(MBB);
171 if (!tii)
return false;
173 TriedMerging.clear();
176 AfterBlockPlacement = AfterPlacement;
188 bool MadeChange =
false;
199 bool MadeChangeThisIteration =
true;
200 while (MadeChangeThisIteration) {
201 MadeChangeThisIteration = TailMergeBlocks(MF);
204 if (!AfterBlockPlacement || MadeChangeThisIteration)
205 MadeChangeThisIteration |= OptimizeBranches(MF);
206 if (EnableHoistCommonCode)
207 MadeChangeThisIteration |= HoistCommonCode(MF);
208 MadeChange |= MadeChangeThisIteration;
222 if (!
Op.isJTI())
continue;
225 JTIsLive.
set(
Op.getIndex());
231 for (
unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
232 if (!JTIsLive.test(i)) {
253 unsigned OperandHash = 0;
256 OperandHash = Op.
getReg();
259 OperandHash = Op.
getImm();
279 Hash += ((OperandHash << 3) | Op.
getType()) << (i & 31);
303 unsigned TailLen = 0;
304 while (I1 != MBB1->
begin() && I2 != MBB2->
begin()) {
307 while (I1->isDebugValue()) {
308 if (I1==MBB1->
begin()) {
309 while (I2->isDebugValue()) {
310 if (I2==MBB2->
begin())
322 while (I2->isDebugValue()) {
323 if (I2==MBB2->
begin()) {
331 if (!I1->isIdenticalTo(*I2) ||
347 if (I1 == MBB1->
begin() && I2 != MBB2->
begin()) {
349 while (I2->isDebugValue()) {
350 if (I2 == MBB2->
begin())
356 if (I2 == MBB2->
begin() && I1 != MBB1->
begin()) {
358 while (I1->isDebugValue()) {
359 if (I1 == MBB1->
begin())
400 NewMBB->
splice(NewMBB->
end(), &CurMBB, BBI1, CurMBB.
end());
405 ML->addBasicBlockToLoop(NewMBB, MLI->
getBase());
414 const auto &FuncletI = FuncletMembership.find(&CurMBB);
415 if (FuncletI != FuncletMembership.end()) {
416 auto n = FuncletI->second;
417 FuncletMembership[NewMBB] = n;
428 for (; I !=
E; ++
I) {
429 if (I->isDebugValue())
433 else if (I->mayLoad() || I->mayStore())
454 if (TBB == NextBB && !Cond.
empty() && !FBB) {
468 if (getHash() < o.getHash())
470 if (getHash() > o.getHash())
472 if (getBlock()->getNumber() < o.getBlock()->getNumber())
474 if (getBlock()->getNumber() > o.getBlock()->getNumber())
478 #ifndef _GLIBCXX_DEBUG
487 auto I = MergedBBFreq.find(MBB);
489 if (
I != MergedBBFreq.end())
497 MergedBBFreq[MBB] =
F;
503 return MBFI.printBlockFreq(OS, getBlockFreq(MBB));
509 return MBFI.printBlockFreq(OS, Freq);
513 MBFI.view(Name, isSimple);
518 return MBFI.getEntryFreq();
527 unsigned NumTerms = 0;
529 if (I == MBB->
begin()) {
534 if (!I->isTerminator())
break;
569 unsigned MinCommonTailLength,
unsigned &CommonTailLen,
574 bool AfterPlacement) {
576 if (!FuncletMembership.
empty()) {
577 auto Funclet1 = FuncletMembership.
find(MBB1);
578 assert(Funclet1 != FuncletMembership.
end());
579 auto Funclet2 = FuncletMembership.
find(MBB2);
580 assert(Funclet2 != FuncletMembership.
end());
581 if (Funclet1->second != Funclet2->second)
586 if (CommonTailLen == 0)
589 <<
" and BB#" << MBB2->
getNumber() <<
" is " << CommonTailLen
597 if ((MBB1 == PredBB || MBB2 == PredBB) &&
598 (!AfterPlacement || MBB1->
succ_size() == 1)) {
601 if (CommonTailLen > NumTerms)
610 if (I1 == MBB1->
begin() && I2 == MBB2->
begin() &&
627 if (AfterPlacement && I1 == MBB1->
begin() && I2 == MBB2->
begin()) {
633 return (MBB != &*MF->
begin()) && std::prev(I)->canFallThrough();
635 if (!BothFallThrough(MBB1) || !BothFallThrough(MBB2))
644 unsigned EffectiveTailLen = CommonTailLen;
645 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
646 (MBB1->
succ_size() == 1 || !AfterPlacement) &&
652 if (EffectiveTailLen >= MinCommonTailLength)
664 unsigned BranchFolder::ComputeSameTails(
unsigned CurHash,
665 unsigned MinCommonTailLength,
668 unsigned maxCommonTailLength = 0U;
671 MPIterator HighestMPIter = std::prev(MergePotentials.end());
672 for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
673 B = MergePotentials.begin();
674 CurMPIter !=
B && CurMPIter->getHash() == CurHash; --CurMPIter) {
675 for (MPIterator
I = std::prev(CurMPIter);
I->getHash() == CurHash; --
I) {
676 unsigned CommonTailLen;
679 CommonTailLen, TrialBBI1, TrialBBI2,
682 AfterBlockPlacement)) {
683 if (CommonTailLen > maxCommonTailLength) {
685 maxCommonTailLength = CommonTailLen;
686 HighestMPIter = CurMPIter;
687 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
689 if (HighestMPIter == CurMPIter &&
690 CommonTailLen == maxCommonTailLength)
691 SameTails.push_back(SameTailElt(
I, TrialBBI2));
697 return maxCommonTailLength;
700 void BranchFolder::RemoveBlocksWithHash(
unsigned CurHash,
703 MPIterator CurMPIter,
B;
704 for (CurMPIter = std::prev(MergePotentials.end()),
705 B = MergePotentials.begin();
706 CurMPIter->getHash() == CurHash; --CurMPIter) {
709 if (SuccBB && CurMBB != PredBB)
714 if (CurMPIter->getHash() != CurHash)
716 MergePotentials.erase(CurMPIter, MergePotentials.end());
721 unsigned maxCommonTailLength,
722 unsigned &commonTailIndex) {
724 unsigned TimeEstimate = ~0U;
725 for (
unsigned i = 0, e = SameTails.size(); i != e; ++i) {
727 if (SameTails[i].getBlock() == PredBB) {
734 SameTails[i].getTailStartPos());
735 if (t <= TimeEstimate) {
742 SameTails[commonTailIndex].getTailStartPos();
746 << maxCommonTailLength);
759 SameTails[commonTailIndex].setBlock(newMBB);
760 SameTails[commonTailIndex].setTailStartPos(newMBB->
begin());
769 void BranchFolder::MergeCommonTailDebugLocs(
unsigned commonTailIndex) {
772 std::vector<MachineBasicBlock::iterator> NextCommonInsts(SameTails.size());
773 for (
unsigned int i = 0 ; i != SameTails.size() ; ++i) {
774 if (i != commonTailIndex)
775 NextCommonInsts[i] = SameTails[i].getTailStartPos();
777 assert(SameTails[i].getTailStartPos() == MBB->
begin() &&
778 "MBB is not a common tail only block");
782 for (
auto &
MI : *MBB) {
783 if (
MI.isDebugValue())
786 for (
unsigned int i = 0 ; i < NextCommonInsts.size() ; i++) {
787 if (i == commonTailIndex)
790 auto &Pos = NextCommonInsts[i];
791 assert(Pos != SameTails[i].getBlock()->
end() &&
792 "Reached BB end within common tail");
793 while (Pos->isDebugValue()) {
795 assert(Pos != SameTails[i].getBlock()->
end() &&
796 "Reached BB end within common tail");
798 assert(
MI.isIdenticalTo(*Pos) &&
"Expected matching MIIs!");
800 NextCommonInsts[i] = ++Pos;
813 unsigned CommonTailLen = 0;
814 for (
auto E = MBB->
end(); MBBIStartPos !=
E; ++MBBIStartPos)
822 while (CommonTailLen--) {
823 assert(MBBI != MBBIE &&
"Reached BB end within common tail length!");
826 if (MBBI->isDebugValue()) {
831 while ((MBBICommon != MBBIECommon) && MBBICommon->isDebugValue())
834 assert(MBBICommon != MBBIECommon &&
835 "Reached BB end within common tail length!");
836 assert(MBBICommon->isIdenticalTo(*MBBI) &&
"Expected matching MIIs!");
839 if (MBBICommon->mayLoad() || MBBICommon->mayStore())
840 MBBICommon->setMemRefs(MBBICommon->mergeMemRefsWith(*MBBI));
842 for (
unsigned I = 0,
E = MBBICommon->getNumOperands();
I !=
E; ++
I) {
867 unsigned MinCommonTailLength) {
868 bool MadeChange =
false;
870 DEBUG(
dbgs() <<
"\nTryTailMergeBlocks: ";
871 for (
unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
872 dbgs() <<
"BB#" << MergePotentials[i].getBlock()->getNumber()
873 << (i == e-1 ?
"" :
", ");
876 dbgs() <<
" with successor BB#" << SuccBB->
getNumber() <<
'\n';
878 dbgs() <<
" which has fall-through from BB#"
881 dbgs() <<
"Looking for common tails of at least "
882 << MinCommonTailLength <<
" instruction"
883 << (MinCommonTailLength == 1 ?
"" :
"s") <<
'\n';
891 while (MergePotentials.size() > 1) {
892 unsigned CurHash = MergePotentials.back().getHash();
896 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
902 if (SameTails.empty()) {
903 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
912 &MergePotentials.front().getBlock()->getParent()->front();
913 unsigned commonTailIndex = SameTails.size();
916 if (SameTails.size() == 2 &&
917 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
918 SameTails[1].tailIsWholeBlock())
920 else if (SameTails.size() == 2 &&
921 SameTails[1].getBlock()->isLayoutSuccessor(
922 SameTails[0].getBlock()) &&
923 SameTails[0].tailIsWholeBlock())
928 for (
unsigned i = 0, e = SameTails.size(); i != e; ++i) {
930 if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
936 if (SameTails[i].tailIsWholeBlock())
941 if (commonTailIndex == SameTails.size() ||
942 (SameTails[commonTailIndex].getBlock() == PredBB &&
943 !SameTails[commonTailIndex].tailIsWholeBlock())) {
946 if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
947 maxCommonTailLength, commonTailIndex)) {
948 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
956 setCommonTailEdgeWeights(*MBB);
959 MergeCommonTailDebugLocs(commonTailIndex);
965 for (
unsigned int i=0, e = SameTails.size(); i != e; ++i) {
966 if (commonTailIndex == i)
968 DEBUG(
dbgs() <<
"BB#" << SameTails[i].getBlock()->getNumber()
969 << (i == e-1 ?
"" :
", "));
973 ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
975 MergePotentials.erase(SameTails[i].getMPIter());
986 bool MadeChange =
false;
987 if (!EnableTailMerge)
return MadeChange;
992 if (!AfterBlockPlacement) {
993 MergePotentials.clear();
997 if (!TriedMerging.count(&MBB) && MBB.
succ_empty())
998 MergePotentials.push_back(MergePotentialsElt(
HashEndOfMBB(MBB), &MBB));
1004 for (
unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
1005 TriedMerging.insert(MergePotentials[i].getBlock());
1008 if (MergePotentials.size() >= 2)
1009 MadeChange |= TryTailMergeBlocks(
nullptr,
nullptr, MinCommonTailLength);
1033 if (
I->pred_size() < 2)
continue;
1037 MergePotentials.clear();
1050 if (AfterBlockPlacement && MLI) {
1060 if (TriedMerging.count(PBB))
1068 if (!UniquePreds.
insert(PBB).second)
1072 if (PBB->hasEHPadSuccessor())
1078 if (AfterBlockPlacement && MLI)
1088 if (!Cond.
empty() && TBB == IBB) {
1093 auto Next = ++PBB->getIterator();
1094 if (Next != MF.end())
1108 if (IBB != PredNextBB)
1111 if (TBB != IBB && FBB != IBB)
1113 }
else if (Cond.
empty()) {
1117 if (TBB != IBB && IBB != PredNextBB)
1123 if (TBB && (Cond.
empty() || FBB)) {
1124 DebugLoc dl = PBB->findBranchDebugLoc();
1128 TII->
insertBranch(*PBB, (TBB == IBB) ? FBB : TBB,
nullptr,
1132 MergePotentials.push_back(MergePotentialsElt(
HashEndOfMBB(*PBB), PBB));
1139 for (
unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
1140 TriedMerging.insert(MergePotentials[i].getBlock());
1142 if (MergePotentials.size() >= 2)
1143 MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength);
1147 PredBB = &*std::prev(
I);
1148 if (MergePotentials.size() == 1 &&
1149 MergePotentials.begin()->getBlock() != PredBB)
1150 FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
1163 for (
const auto &Src : SameTails) {
1166 AccumulatedMBBFreq += BlockFreq;
1173 auto EdgeFreq = EdgeFreqLs.begin();
1176 SuccI != SuccE; ++SuccI, ++EdgeFreq)
1180 MBBFreqInfo.
setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1186 std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(),
BlockFrequency(0))
1188 auto EdgeFreq = EdgeFreqLs.begin();
1190 if (SumEdgeFreq > 0) {
1192 SuccI != SuccE; ++SuccI, ++EdgeFreq) {
1194 EdgeFreq->getFrequency(), SumEdgeFreq);
1205 bool MadeChange =
false;
1215 MadeChange |= OptimizeBlock(MBB);
1219 RemoveDeadBlock(MBB);
1238 assert(I != MBB->
end() &&
"empty block!");
1239 return I->isBranch();
1254 if (MBB1I == MBB1->
end() || MBB2I == MBB2->
end())
1262 return MBB2I->isCall() && !MBB1I->isCall();
1269 if (I != MBB.
end() && I->isBranch())
1270 return I->getDebugLoc();
1275 bool MadeChange =
false;
1283 bool SameFunclet =
true;
1284 if (!FuncletMembership.empty() && FallThrough != MF.
end()) {
1285 auto MBBFunclet = FuncletMembership.find(MBB);
1286 assert(MBBFunclet != FuncletMembership.end());
1287 auto FallThroughFunclet = FuncletMembership.find(&*FallThrough);
1288 assert(FallThroughFunclet != FuncletMembership.end());
1289 SameFunclet = MBBFunclet->second == FallThroughFunclet->second;
1301 if (FallThrough == MF.
end()) {
1303 }
else if (FallThrough->isEHPad()) {
1318 MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
1330 bool PriorUnAnalyzable =
1331 TII->
analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond,
true);
1332 if (!PriorUnAnalyzable) {
1335 !PriorCond.
empty());
1340 if (PriorTBB && PriorTBB == PriorFBB) {
1344 if (PriorTBB != MBB)
1345 TII->
insertBranch(PrevBB, PriorTBB,
nullptr, PriorCond, dl);
1348 goto ReoptimizeBlock;
1361 DEBUG(
dbgs() <<
"\nMerging into block: " << PrevBB
1362 <<
"From MBB: " << *MBB);
1364 if (PrevBB.
begin() != PrevBB.
end()) {
1370 while (PrevBBIter != PrevBB.
begin() && MBBIter != MBB->
end()
1371 && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1372 if (!MBBIter->isIdenticalTo(*PrevBBIter))
1375 ++MBBIter; -- PrevBBIter;
1389 if (PriorTBB == MBB && !PriorFBB) {
1393 goto ReoptimizeBlock;
1398 if (PriorFBB == MBB) {
1401 TII->
insertBranch(PrevBB, PriorTBB,
nullptr, PriorCond, dl);
1404 goto ReoptimizeBlock;
1410 if (PriorTBB == MBB) {
1415 TII->
insertBranch(PrevBB, PriorFBB,
nullptr, NewPriorCond, dl);
1418 goto ReoptimizeBlock;
1433 bool DoTransform =
true;
1440 if (FallThrough == --MF.
end() &&
1442 DoTransform =
false;
1448 DEBUG(
dbgs() <<
"\nMoving MBB: " << *MBB
1449 <<
"To make fallthrough to: " << *PriorTBB <<
"\n");
1453 TII->
insertBranch(PrevBB, MBB,
nullptr, NewPriorCond, dl);
1475 bool PredAnalyzable =
1476 !TII->
analyzeBranch(*Pred, PredTBB, PredFBB, PredCond,
true);
1478 if (PredAnalyzable && !PredCond.
empty() && PredTBB == MBB &&
1479 PredTBB != PredFBB) {
1505 bool CurUnAnalyzable =
1507 if (!CurUnAnalyzable) {
1516 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1524 goto ReoptimizeBlock;
1530 if (CurTBB && CurCond.
empty() && !CurFBB &&
1553 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1557 if (!PredHasNoFallThrough && PrevBB.
isSuccessor(MBB) &&
1558 PriorTBB != MBB && PriorFBB != MBB) {
1561 "Bad branch analysis");
1564 assert(!PriorFBB &&
"Machine CFG out of date!");
1569 TII->
insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1574 bool DidChange =
false;
1575 bool HasBranchToSelf =
false;
1581 HasBranchToSelf =
true;
1591 *PMBB, NewCurTBB, NewCurFBB, NewCurCond,
true);
1592 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1596 TII->
insertBranch(*PMBB, NewCurTBB,
nullptr, NewCurCond, pdl);
1606 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1610 if (!HasBranchToSelf)
return MadeChange;
1636 !TII->
analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond,
true) &&
1637 (!CurFallsThru || !CurTBB || !CurFBB) &&
1656 goto ReoptimizeBlock;
1661 if (!CurFallsThru) {
1671 if (SuccBB != MBB && &*SuccPrev != MBB &&
1672 !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1676 goto ReoptimizeBlock;
1696 if (FallThrough != MF.
end() &&
1697 !FallThrough->isEHPad() &&
1698 !TII->
analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond,
true) &&
1715 bool MadeChange =
false;
1718 MadeChange |= HoistCommonCodeInSuccs(MBB);
1729 if (SuccBB != TrueBB)
1734 template <
class Container>
1765 unsigned Reg = MO.getReg();
1784 if (Loc == MBB->
begin())
1797 if (!MO.isReg() || MO.isUse())
1799 unsigned Reg = MO.getReg();
1802 if (Uses.
count(Reg)) {
1818 bool DontMoveAcrossStore =
true;
1819 if (!PI->isSafeToMove(
nullptr, DontMoveAcrossStore) || TII->
isPredicated(*PI))
1828 unsigned Reg = MO.getReg();
1834 if (Uses.
erase(Reg)) {
1837 Uses.
erase(*SubRegs);
1860 if (TBB->
pred_size() > 1 || FBB->pred_size() > 1)
1869 if (Loc == MBB->
end())
1872 bool HasDups =
false;
1879 while (TIB != TIE && FIB != FIE) {
1883 if (TIB == TIE || FIB == FIE)
1896 if (MO.isRegMask()) {
1902 unsigned Reg = MO.getReg();
1906 if (Uses.
count(Reg)) {
1913 if (Defs.
count(Reg) && !MO.isDead()) {
1928 }
else if (!ActiveDefsSet.
count(Reg)) {
1929 if (Defs.
count(Reg)) {
1935 if (MO.isKill() && Uses.
count(Reg))
1938 MO.setIsKill(
false);
1944 bool DontMoveAcrossStore =
true;
1945 if (!TIB->isSafeToMove(
nullptr, DontMoveAcrossStore))
1950 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1952 unsigned Reg = MO.getReg();
1955 if (!AllDefsSet.
count(Reg)) {
1961 ActiveDefsSet.
erase(*AI);
1963 ActiveDefsSet.
erase(Reg);
1969 if (!MO.isReg() || !MO.isDef() || MO.isDead())
1971 unsigned Reg = MO.getReg();
1988 FBB->erase(FBB->begin(), FIB);
1991 bool ChangedLiveIns =
false;
1992 for (
unsigned i = 0, e = LocalDefs.
size(); i != e; ++i) {
1993 unsigned Def = LocalDefs[i];
1994 if (ActiveDefsSet.
count(Def)) {
1996 FBB->addLiveIn(Def);
1997 ChangedLiveIns =
true;
2000 for (
unsigned K : LocalKills) {
2002 FBB->removeLiveIn(K);
2003 ChangedLiveIns =
true;
2006 if (ChangedLiveIns) {
2008 FBB->sortUniqueLiveIns();
unsigned succ_size() const
void view(const Twine &Name, bool isSimple=true)
static unsigned EstimateRuntime(MachineBasicBlock::iterator I, MachineBasicBlock::iterator E)
EstimateRuntime - Make a rough estimate for how long it will take to run the specified code...
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.
BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
static cl::opt< unsigned > TailMergeThreshold("tail-merge-threshold", cl::desc("Max number of predecessors to consider tail merging"), cl::init(150), cl::Hidden)
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
STATISTIC(NumFunctions,"Total number of functions")
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them...
MachineBasicBlock * getMBB() const
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
iterator getFirstNonDebugInstr()
Returns an iterator to the first non-debug instruction in the basic block, or end().
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
void setIsUndef(bool Val=true)
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Address of indexed Jump Table for switch.
void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
static unsigned HashMachineInstr(const MachineInstr &MI)
HashMachineInstr - Compute a hash value for MI and its operands.
void RemoveJumpTable(unsigned Idx)
RemoveJumpTable - Mark the specific index as being dead.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
INITIALIZE_PASS(BranchFolderPass, DEBUG_TYPE,"Control Flow Optimizer", false, false) bool BranchFolderPass
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...
MachineBasicBlock reference.
void moveAfter(MachineBasicBlock *NewBefore)
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB)
getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch instructions on the block...
bool optForSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
BlockT * getHeader() const
void removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask=LaneBitmask::getAll())
Remove the specified register from the live in set.
BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
iterator_range< succ_iterator > successors()
const std::vector< MachineJumpTableEntry > & getJumpTables() const
AnalysisUsage & addRequired()
void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New)
Given a machine basic block that branched to 'Old', change the code and CFG so that it branches to 'N...
LLVM_NODISCARD bool empty() const
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.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
const HexagonInstrInfo * TII
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Name of external global symbol.
Reg
All possible values of the reg field in the ModR/M byte.
static unsigned HashEndOfMBB(const MachineBasicBlock &MBB)
HashEndOfMBB - Hash the last instruction in the MBB.
static bool IsEmptyBlock(MachineBasicBlock *MBB)
void removeBlock(MachineBasicBlock *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
static const DILocation * getMergedLocation(const DILocation *LocA, const DILocation *LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Target-Independent Code Generator Pass Configuration Options.
LLVM_NODISCARD bool empty() const
unsigned getNumOperands() const
Access to explicit operands of the instruction.
static bool isSimple(Instruction *I)
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.
static cl::opt< cl::boolOrDefault > FlagEnableTailMerge("enable-tail-merge", cl::init(cl::BOU_UNSET), cl::Hidden)
static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB, const TargetInstrInfo *TII)
bool canFallThrough()
Return true if the block can implicitly transfer control to the block after it by falling off the end...
static bool blockEndsInUnreachable(const MachineBasicBlock *MBB)
A no successor, non-return block probably ends in unreachable and is cold.
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
virtual bool isUnpredicatedTerminator(const MachineInstr &MI) const
Returns true if the instruction is a terminator instruction that has not been predicated.
iterator getLastNonDebugInstr()
Returns an iterator to the last non-debug instruction in the basic block, or end().
static MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, SmallSet< unsigned, 4 > &Uses, SmallSet< unsigned, 4 > &Defs)
findHoistingInsertPosAndDeps - Find the location to move common instructions in successors to...
virtual bool isUnconditionalTailCall(const MachineInstr &MI) const
Returns true if MI is an unconditional tail call.
void setSuccProbability(succ_iterator I, BranchProbability Prob)
Set successor probability of a given iterator.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
reverse_iterator rbegin()
BasicBlockListType::iterator iterator
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
void setBlockFreq(const MachineBasicBlock *MBB, BlockFrequency F)
TargetInstrInfo - Interface to description of machine instruction set.
iterator find(const_arg_type_t< KeyT > Val)
static void mergeOperations(MachineBasicBlock::iterator MBBIStartPos, MachineBasicBlock &MBBCommon)
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
Address of a global value.
initializer< Ty > init(const Ty &Val)
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
bool isReturn(QueryType Type=AnyInBundle) const
void addLiveIn(MCPhysReg PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
void computeLiveIns(LivePhysRegs &LiveRegs, const MachineRegisterInfo &MRI, MachineBasicBlock &MBB)
Computes the live-in list for MBB assuming all of its successors live-in lists are up-to-date...
LLVM Basic Block Representation.
uint64_t getEntryFreq() const
virtual unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const
Remove the branching code at the end of the specific MBB.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
const MachineOperand & getOperand(unsigned i) const
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.
bool isIndirectBranch(QueryType Type=AnyInBundle) const
Return true if this is an indirect branch, such as a branch through a register.
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
virtual bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const
Reverses the branch condition of the specified condition list, returning false on success and true if...
MCRegAliasIterator enumerates all registers aliasing Reg.
Represent the analysis usage information of a pass.
void clearLiveIns()
Clear live in list.
bool getEnableTailMerge() const
int64_t getOffset() const
Return the offset from the symbol in this operand.
static bool IsBetterFallthrough(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2)
IsBetterFallthrough - Return true if it would be clearly better to fall-through to MBB1 than to fall ...
self_iterator getIterator()
iterator_range< pred_iterator > predecessors()
succ_iterator succ_begin()
void moveBefore(MachineBasicBlock *NewAfter)
Move 'this' block before or after the specified block.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
MCSubRegIterator enumerates all sub-registers of Reg.
pred_iterator pred_begin()
static unsigned CountTerminators(MachineBasicBlock *MBB, MachineBasicBlock::iterator &I)
CountTerminators - Count the number of terminators in the given block and set I to the position of th...
static cl::opt< unsigned > TailMergeSize("tail-merge-size", cl::desc("Min number of instructions to consider tail merging"), cl::init(3), cl::Hidden)
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
DenseMap< const MachineBasicBlock *, int > getFuncletMembership(const MachineFunction &MF)
static void addRegAndItsAliases(unsigned Reg, const TargetRegisterInfo *TRI, Container &Set)
static BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const
Returns true if the live-ins should be tracked after register allocation.
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
IterT skipDebugInstructionsBackward(IterT It, IterT Begin)
Decrement It until it points to a non-debug instruction or to Begin and return the resulting iterator...
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
IterT skipDebugInstructionsForward(IterT It, IterT End)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator...
llvm_unreachable("Unknown RegBank!")
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
virtual bool isLegalToSplitMBBAt(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const
Return true if it's legal to split the given basic block at the specified instruction (i...
Representation of each machine instruction.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
bool hasAddressTaken() const
Test whether this block is potentially the target of an indirect branch.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
virtual void replaceBranchWithTailCall(MachineBasicBlock &MBB, SmallVectorImpl< MachineOperand > &Cond, const MachineInstr &TailCall) const
Replace the conditional branch in MBB with a conditional tail call.
raw_ostream & printBlockFreq(raw_ostream &OS, const MachineBasicBlock *MBB) const
BranchFolder(bool defaultEnableTailMerge, bool CommonHoist, MBFIWrapper &MBFI, const MachineBranchProbabilityInfo &MBPI, unsigned MinCommonTailLength=0)
virtual bool isPredicated(const MachineInstr &MI) const
Returns true if the instruction is already predicated.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
static bool IsBranchOnlyBlock(MachineBasicBlock *MBB)
Abstract Stack Frame Index.
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
LLVM_NODISCARD bool empty() const
static MachineBasicBlock * findFalseBlock(MachineBasicBlock *BB, MachineBasicBlock *TrueBB)
findFalseBlock - BB has a fallthrough.
unsigned getReg() const
getReg - Returns the register number.
void erase(iterator MBBI)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void insert(iterator MBBI, MachineBasicBlock *MBB)
bool operator<(int64_t V1, const APSInt &V2)
virtual bool canMakeTailCallConditional(SmallVectorImpl< MachineOperand > &Cond, const MachineInstr &TailCall) const
Returns true if the tail call can be made conditional on BranchCond.
static bool ProfitableToMerge(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2, unsigned MinCommonTailLength, unsigned &CommonTailLen, MachineBasicBlock::iterator &I1, MachineBasicBlock::iterator &I2, MachineBasicBlock *SuccBB, MachineBasicBlock *PredBB, DenseMap< const MachineBasicBlock *, int > &FuncletMembership, bool AfterPlacement)
ProfitableToMerge - Check if two machine basic blocks have a common tail and decide if it would be pr...
char & BranchFolderPassID
BranchFolding - This pass performs machine code CFG based optimizations to delete branches to branche...
This class implements an extremely fast bulk output stream that can only output to a stream...
const MachineBasicBlock & back() const
std::string Hash(const Unit &U)
This class keeps track of branch frequencies of newly created blocks and tail-merged blocks...
Address of indexed Constant in Constant Pool.
virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail, MachineBasicBlock *NewDest) const
Delete the instruction OldInst and everything after it, replacing it with an unconditional branch to ...
BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) 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...
unsigned pred_size() const
bool isBarrier(QueryType Type=AnyInBundle) const
Returns true if the specified instruction stops control flow from executing the instruction immediate...
bool CorrectExtraCFGEdges(MachineBasicBlock *DestA, MachineBasicBlock *DestB, bool IsCond)
Various pieces of code can cause excess edges in the CFG to be inserted.
This class contains meta information specific to a module.
static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2, MachineBasicBlock::iterator &I1, MachineBasicBlock::iterator &I2)
ComputeCommonTailLength - Given two machine basic blocks, compute the number of instructions they act...
LoopInfoBase< MachineBasicBlock, MachineLoop > & getBase()