70 #define DEBUG_TYPE "branch-folder" 72 STATISTIC(NumDeadBlocks,
"Number of dead blocks removed");
73 STATISTIC(NumBranchOpts,
"Number of branches optimized");
74 STATISTIC(NumTailMerge ,
"Number of block tails merged");
75 STATISTIC(NumHoist ,
"Number of times common instructions are hoisted");
76 STATISTIC(NumTailCalls,
"Number of tail calls optimized");
84 cl::desc(
"Max number of predecessors to consider tail merging"),
91 cl::desc(
"Min number of instructions to consider tail merging"),
121 "Control Flow Optimizer",
false,
false)
124 if (skipFunction(MF.getFunction()))
130 bool EnableTailMerge = !MF.getTarget().requiresStructuredCFG() &&
133 getAnalysis<MachineBlockFrequencyInfo>());
135 getAnalysis<MachineBranchProbabilityInfo>(),
136 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
137 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>();
139 MF, MF.getSubtarget().getInstrInfo(), MF.getSubtarget().getRegisterInfo(),
140 MMIWP ? &MMIWP->getMMI() :
nullptr);
147 unsigned MinTailLength)
148 : EnableHoistCommonCode(CommonHoist), MinCommonTailLength(MinTailLength),
149 MBBFreqInfo(FreqInfo), MBPI(ProbInfo), PSI(PSI) {
150 if (MinCommonTailLength == 0)
153 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge;
break;
169 TriedMerging.erase(MBB);
178 EHScopeMembership.erase(MBB);
188 if (!tii)
return false;
190 TriedMerging.clear();
193 AfterBlockPlacement = AfterPlacement;
205 bool MadeChange =
false;
216 bool MadeChangeThisIteration =
true;
217 while (MadeChangeThisIteration) {
218 MadeChangeThisIteration = TailMergeBlocks(MF);
221 if (!AfterBlockPlacement || MadeChangeThisIteration)
222 MadeChangeThisIteration |= OptimizeBranches(MF);
223 if (EnableHoistCommonCode)
224 MadeChangeThisIteration |= HoistCommonCode(MF);
225 MadeChange |= MadeChangeThisIteration;
239 if (!
Op.isJTI())
continue;
242 JTIsLive.
set(
Op.getIndex());
248 for (
unsigned i = 0,
e = JTIsLive.size(); i !=
e; ++i)
249 if (!JTIsLive.test(i)) {
270 unsigned OperandHash = 0;
273 OperandHash = Op.
getReg();
276 OperandHash = Op.
getImm();
296 Hash += ((OperandHash << 3) | Op.
getType()) << (i & 31);
321 while (I != MBB->
begin()) {
342 unsigned TailLen = 0;
346 if (MBBI1 == MBB1->
end() || MBBI2 == MBB2->
end())
348 if (!MBBI1->isIdenticalTo(*MBBI2) ||
354 MBBI1->isInlineAsm()) {
377 }
while (I != OldInst);
386 "Can only handle full register.");
391 BuildMI(OldMBB, OldInst, DL, TII->
get(TargetOpcode::IMPLICIT_DEF),
Reg);
419 NewMBB->
splice(NewMBB->
end(), &CurMBB, BBI1, CurMBB.
end());
424 ML->addBasicBlockToLoop(NewMBB, MLI->
getBase());
433 const auto &EHScopeI = EHScopeMembership.find(&CurMBB);
434 if (EHScopeI != EHScopeMembership.end()) {
435 auto n = EHScopeI->second;
436 EHScopeMembership[NewMBB] = n;
447 for (; I !=
E; ++
I) {
452 else if (I->mayLoadOrStore())
473 if (TBB == NextBB && !Cond.
empty() && !FBB) {
487 if (getHash() < o.getHash())
489 if (getHash() > o.getHash())
491 if (getBlock()->getNumber() < o.getBlock()->getNumber())
493 if (getBlock()->getNumber() > o.getBlock()->getNumber())
497 #ifndef _GLIBCXX_DEBUG 506 auto I = MergedBBFreq.find(MBB);
508 if (
I != MergedBBFreq.end())
511 return MBFI.getBlockFreq(MBB);
516 MergedBBFreq[MBB] =
F;
522 return MBFI.printBlockFreq(OS, getBlockFreq(MBB));
528 return MBFI.printBlockFreq(OS, Freq);
532 MBFI.view(Name, isSimple);
537 return MBFI.getEntryFreq();
546 unsigned NumTerms = 0;
548 if (I == MBB->
begin()) {
553 if (!I->isTerminator())
break;
588 unsigned MinCommonTailLength,
unsigned &CommonTailLen,
597 if (!EHScopeMembership.
empty()) {
598 auto EHScope1 = EHScopeMembership.
find(MBB1);
599 assert(EHScope1 != EHScopeMembership.
end());
600 auto EHScope2 = EHScopeMembership.
find(MBB2);
601 assert(EHScope2 != EHScopeMembership.
end());
602 if (EHScope1->second != EHScope2->second)
607 if (CommonTailLen == 0)
611 << CommonTailLen <<
'\n');
621 bool FullBlockTail1 = I1 == MBB1->
begin();
622 bool FullBlockTail2 = I2 == MBB2->
begin();
629 if ((MBB1 == PredBB || MBB2 == PredBB) &&
630 (!AfterPlacement || MBB1->
succ_size() == 1)) {
633 if (CommonTailLen > NumTerms)
642 if (FullBlockTail1 && FullBlockTail2 &&
659 if (AfterPlacement && FullBlockTail1 && FullBlockTail2) {
665 return (MBB != &*MF->
begin()) && std::prev(I)->canFallThrough();
667 if (!BothFallThrough(MBB1) || !BothFallThrough(MBB2))
676 unsigned EffectiveTailLen = CommonTailLen;
677 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
678 (MBB1->
succ_size() == 1 || !AfterPlacement) &&
684 if (EffectiveTailLen >= MinCommonTailLength)
696 return EffectiveTailLen >= 2 && OptForSize &&
697 (FullBlockTail1 || FullBlockTail2);
700 unsigned BranchFolder::ComputeSameTails(
unsigned CurHash,
701 unsigned MinCommonTailLength,
704 unsigned maxCommonTailLength = 0U;
707 MPIterator HighestMPIter = std::prev(MergePotentials.end());
708 for (MPIterator CurMPIter = std::prev(MergePotentials.end()),
709 B = MergePotentials.begin();
710 CurMPIter !=
B && CurMPIter->getHash() == CurHash; --CurMPIter) {
711 for (MPIterator
I = std::prev(CurMPIter);
I->getHash() == CurHash; --
I) {
712 unsigned CommonTailLen;
715 CommonTailLen, TrialBBI1, TrialBBI2,
718 AfterBlockPlacement, MBBFreqInfo, PSI)) {
719 if (CommonTailLen > maxCommonTailLength) {
721 maxCommonTailLength = CommonTailLen;
722 HighestMPIter = CurMPIter;
723 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
725 if (HighestMPIter == CurMPIter &&
726 CommonTailLen == maxCommonTailLength)
727 SameTails.push_back(SameTailElt(
I, TrialBBI2));
733 return maxCommonTailLength;
736 void BranchFolder::RemoveBlocksWithHash(
unsigned CurHash,
739 MPIterator CurMPIter,
B;
740 for (CurMPIter = std::prev(MergePotentials.end()),
741 B = MergePotentials.begin();
742 CurMPIter->getHash() == CurHash; --CurMPIter) {
745 if (SuccBB && CurMBB != PredBB)
750 if (CurMPIter->getHash() != CurHash)
752 MergePotentials.erase(CurMPIter, MergePotentials.end());
757 unsigned maxCommonTailLength,
758 unsigned &commonTailIndex) {
760 unsigned TimeEstimate = ~0U;
761 for (
unsigned i = 0,
e = SameTails.size(); i !=
e; ++i) {
763 if (SameTails[i].getBlock() == PredBB) {
770 SameTails[i].getTailStartPos());
771 if (t <= TimeEstimate) {
778 SameTails[commonTailIndex].getTailStartPos();
782 << maxCommonTailLength);
795 SameTails[commonTailIndex].setBlock(newMBB);
796 SameTails[commonTailIndex].setTailStartPos(newMBB->
begin());
812 unsigned CommonTailLen = 0;
813 for (
auto E = MBB->
end(); MBBIStartPos !=
E; ++MBBIStartPos)
821 while (CommonTailLen--) {
822 assert(MBBI != MBBIE &&
"Reached BB end within common tail length!");
833 assert(MBBICommon != MBBIECommon &&
834 "Reached BB end within common tail length!");
835 assert(MBBICommon->isIdenticalTo(*MBBI) &&
"Expected matching MIIs!");
838 if (MBBICommon->mayLoadOrStore())
839 MBBICommon->cloneMergedMemRefs(*MBB->
getParent(), {&*MBBICommon, &*MBBI});
841 for (
unsigned I = 0,
E = MBBICommon->getNumOperands();
I !=
E; ++
I) {
855 void BranchFolder::mergeCommonTails(
unsigned commonTailIndex) {
858 std::vector<MachineBasicBlock::iterator> NextCommonInsts(SameTails.size());
859 for (
unsigned int i = 0 ; i != SameTails.size() ; ++i) {
860 if (i != commonTailIndex) {
861 NextCommonInsts[i] = SameTails[i].getTailStartPos();
864 assert(SameTails[i].getTailStartPos() == MBB->
begin() &&
865 "MBB is not a common tail only block");
869 for (
auto &
MI : *MBB) {
873 for (
unsigned int i = 0 ; i < NextCommonInsts.size() ; i++) {
874 if (i == commonTailIndex)
877 auto &Pos = NextCommonInsts[i];
878 assert(Pos != SameTails[i].getBlock()->
end() &&
879 "Reached BB end within common tail");
882 assert(Pos != SameTails[i].getBlock()->
end() &&
883 "Reached BB end within common tail");
885 assert(
MI.isIdenticalTo(*Pos) &&
"Expected matching MIIs!");
887 NextCommonInsts[i] = ++Pos;
903 for (
unsigned Reg : NewLiveIns) {
907 BuildMI(*Pred, InsertBefore, DL, TII->
get(TargetOpcode::IMPLICIT_DEF),
928 unsigned MinCommonTailLength) {
929 bool MadeChange =
false;
932 dbgs() <<
"\nTryTailMergeBlocks: ";
933 for (
unsigned i = 0,
e = MergePotentials.size(); i !=
e; ++i)
dbgs()
935 << (i ==
e - 1 ?
"" :
", ");
936 dbgs() <<
"\n";
if (SuccBB) {
939 dbgs() <<
" which has fall-through from " 941 }
dbgs() <<
"Looking for common tails of at least " 942 << MinCommonTailLength <<
" instruction" 943 << (MinCommonTailLength == 1 ?
"" :
"s") <<
'\n';);
950 while (MergePotentials.size() > 1) {
951 unsigned CurHash = MergePotentials.back().getHash();
955 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
961 if (SameTails.empty()) {
962 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
971 &MergePotentials.front().getBlock()->getParent()->front();
972 unsigned commonTailIndex = SameTails.size();
975 if (SameTails.size() == 2 &&
976 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
977 SameTails[1].tailIsWholeBlock())
979 else if (SameTails.size() == 2 &&
980 SameTails[1].getBlock()->isLayoutSuccessor(
981 SameTails[0].getBlock()) &&
982 SameTails[0].tailIsWholeBlock())
987 for (
unsigned i = 0,
e = SameTails.size(); i !=
e; ++i) {
989 if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
995 if (SameTails[i].tailIsWholeBlock())
1000 if (commonTailIndex == SameTails.size() ||
1001 (SameTails[commonTailIndex].getBlock() == PredBB &&
1002 !SameTails[commonTailIndex].tailIsWholeBlock())) {
1005 if (!CreateCommonTailOnlyBlock(PredBB, SuccBB,
1006 maxCommonTailLength, commonTailIndex)) {
1007 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
1015 setCommonTailEdgeWeights(*MBB);
1019 mergeCommonTails(commonTailIndex);
1025 for (
unsigned int i=0,
e = SameTails.size(); i !=
e; ++i) {
1026 if (commonTailIndex == i)
1029 << (i ==
e - 1 ?
"" :
", "));
1031 replaceTailWithBranchTo(SameTails[i].getTailStartPos(), *MBB);
1033 MergePotentials.erase(SameTails[i].getMPIter());
1044 bool MadeChange =
false;
1045 if (!EnableTailMerge)
1050 MergePotentials.clear();
1054 if (!TriedMerging.count(&MBB) && MBB.
succ_empty())
1055 MergePotentials.push_back(MergePotentialsElt(
HashEndOfMBB(MBB), &MBB));
1061 for (
unsigned i = 0,
e = MergePotentials.size(); i !=
e; ++i)
1062 TriedMerging.insert(MergePotentials[i].getBlock());
1065 if (MergePotentials.size() >= 2)
1066 MadeChange |= TryTailMergeBlocks(
nullptr,
nullptr, MinCommonTailLength);
1089 if (
I->pred_size() < 2)
continue;
1093 MergePotentials.clear();
1106 if (AfterBlockPlacement && MLI) {
1116 if (TriedMerging.count(PBB))
1124 if (!UniquePreds.
insert(PBB).second)
1128 if (PBB->hasEHPadSuccessor())
1134 if (AfterBlockPlacement && MLI)
1144 if (!Cond.
empty() && TBB == IBB) {
1149 auto Next = ++PBB->getIterator();
1150 if (Next != MF.end())
1156 if (TBB && (Cond.
empty() || FBB)) {
1157 DebugLoc dl = PBB->findBranchDebugLoc();
1161 TII->
insertBranch(*PBB, (TBB == IBB) ? FBB : TBB,
nullptr,
1165 MergePotentials.push_back(MergePotentialsElt(
HashEndOfMBB(*PBB), PBB));
1172 for (
unsigned i = 0,
e = MergePotentials.size(); i !=
e; ++i)
1173 TriedMerging.insert(MergePotentials[i].getBlock());
1175 if (MergePotentials.size() >= 2)
1176 MadeChange |= TryTailMergeBlocks(IBB, PredBB, MinCommonTailLength);
1180 PredBB = &*std::prev(
I);
1181 if (MergePotentials.size() == 1 &&
1182 MergePotentials.begin()->getBlock() != PredBB)
1183 FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
1196 for (
const auto &Src : SameTails) {
1199 AccumulatedMBBFreq += BlockFreq;
1206 auto EdgeFreq = EdgeFreqLs.begin();
1209 SuccI != SuccE; ++SuccI, ++EdgeFreq)
1213 MBBFreqInfo.
setBlockFreq(&TailMBB, AccumulatedMBBFreq);
1219 std::accumulate(EdgeFreqLs.begin(), EdgeFreqLs.end(),
BlockFrequency(0))
1221 auto EdgeFreq = EdgeFreqLs.begin();
1223 if (SumEdgeFreq > 0) {
1225 SuccI != SuccE; ++SuccI, ++EdgeFreq) {
1227 EdgeFreq->getFrequency(), SumEdgeFreq);
1238 bool MadeChange =
false;
1248 MadeChange |= OptimizeBlock(MBB);
1252 RemoveDeadBlock(MBB);
1271 assert(I != MBB->
end() &&
"empty block!");
1272 return I->isBranch();
1281 assert(MBB1 && MBB2 &&
"Unknown MachineBasicBlock");
1289 if (MBB1I == MBB1->
end() || MBB2I == MBB2->
end())
1297 return MBB2I->isCall() && !MBB1I->isCall();
1304 if (I != MBB.
end() && I->isBranch())
1305 return I->getDebugLoc();
1314 if (
MI.isDebugInstr()) {
1316 LLVM_DEBUG(
dbgs() <<
"Copied debug entity from empty block to pred: " 1326 if (
MI.isDebugInstr()) {
1328 LLVM_DEBUG(
dbgs() <<
"Copied debug entity from empty block to succ: " 1357 bool MadeChange =
false;
1365 bool SameEHScope =
true;
1366 if (!EHScopeMembership.empty() && FallThrough != MF.
end()) {
1367 auto MBBEHScope = EHScopeMembership.find(MBB);
1368 assert(MBBEHScope != EHScopeMembership.end());
1369 auto FallThroughEHScope = EHScopeMembership.find(&*FallThrough);
1370 assert(FallThroughEHScope != EHScopeMembership.end());
1371 SameEHScope = MBBEHScope->second == FallThroughEHScope->second;
1384 if (FallThrough == MF.
end()) {
1386 }
else if (FallThrough->isEHPad()) {
1401 MJTI->ReplaceMBBInJumpTables(MBB, &*FallThrough);
1413 bool PriorUnAnalyzable =
1414 TII->
analyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond,
true);
1415 if (!PriorUnAnalyzable) {
1418 !PriorCond.
empty());
1423 if (PriorTBB && PriorTBB == PriorFBB) {
1427 if (PriorTBB != MBB)
1428 TII->
insertBranch(PrevBB, PriorTBB,
nullptr, PriorCond, dl);
1431 goto ReoptimizeBlock;
1445 <<
"From MBB: " << *MBB);
1447 if (PrevBB.
begin() != PrevBB.
end()) {
1453 while (PrevBBIter != PrevBB.
begin() && MBBIter != MBB->
end()
1454 && PrevBBIter->isDebugInstr() && MBBIter->isDebugInstr()) {
1455 if (!MBBIter->isIdenticalTo(*PrevBBIter))
1458 ++MBBIter; -- PrevBBIter;
1472 if (PriorTBB == MBB && !PriorFBB) {
1476 goto ReoptimizeBlock;
1481 if (PriorFBB == MBB) {
1484 TII->
insertBranch(PrevBB, PriorTBB,
nullptr, PriorCond, dl);
1487 goto ReoptimizeBlock;
1493 if (PriorTBB == MBB) {
1498 TII->
insertBranch(PrevBB, PriorFBB,
nullptr, NewPriorCond, dl);
1501 goto ReoptimizeBlock;
1516 bool DoTransform =
true;
1523 if (FallThrough == --MF.
end() &&
1525 DoTransform =
false;
1532 <<
"To make fallthrough to: " << *PriorTBB <<
"\n");
1536 TII->
insertBranch(PrevBB, MBB,
nullptr, NewPriorCond, dl);
1560 bool PredAnalyzable =
1561 !TII->
analyzeBranch(*Pred, PredTBB, PredFBB, PredCond,
true);
1563 if (PredAnalyzable && !PredCond.
empty() && PredTBB == MBB &&
1564 PredTBB != PredFBB) {
1590 bool CurUnAnalyzable =
1592 if (!CurUnAnalyzable) {
1601 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1609 goto ReoptimizeBlock;
1615 if (CurTBB && CurCond.
empty() && !CurFBB &&
1638 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1642 if (!PredHasNoFallThrough && PrevBB.
isSuccessor(MBB) &&
1643 PriorTBB != MBB && PriorFBB != MBB) {
1646 "Bad branch analysis");
1649 assert(!PriorFBB &&
"Machine CFG out of date!");
1654 TII->
insertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
1659 bool DidChange =
false;
1660 bool HasBranchToSelf =
false;
1666 HasBranchToSelf =
true;
1676 *PMBB, NewCurTBB, NewCurFBB, NewCurCond,
true);
1677 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1681 TII->
insertBranch(*PMBB, NewCurTBB,
nullptr, NewCurCond, pdl);
1691 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
1695 if (!HasBranchToSelf)
return MadeChange;
1721 !TII->
analyzeBranch(*PredBB, PredTBB, PredFBB, PredCond,
true) &&
1722 (!CurFallsThru || !CurTBB || !CurFBB) &&
1741 goto ReoptimizeBlock;
1746 if (!CurFallsThru) {
1756 if (SuccBB != MBB && &*SuccPrev != MBB &&
1757 !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
1761 goto ReoptimizeBlock;
1781 if (FallThrough != MF.
end() &&
1782 !FallThrough->isEHPad() &&
1783 !TII->
analyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond,
true) &&
1800 bool MadeChange =
false;
1803 MadeChange |= HoistCommonCodeInSuccs(MBB);
1814 if (SuccBB != TrueBB)
1819 template <
class Container>
1873 if (Loc == MBB->
begin())
1886 if (!MO.isReg() || MO.isUse())
1891 if (Uses.
count(Reg)) {
1907 bool DontMoveAcrossStore =
true;
1908 if (!PI->isSafeToMove(
nullptr, DontMoveAcrossStore) || TII->
isPredicated(*PI))
1922 if (Uses.
erase(Reg)) {
1925 Uses.
erase(*SubRegs);
1948 if (TBB->
pred_size() > 1 || FBB->pred_size() > 1)
1957 if (Loc == MBB->
end())
1960 bool HasDups =
false;
1966 while (TIB != TIE && FIB != FIE) {
1970 if (TIB == TIE || FIB == FIE)
1983 if (MO.isRegMask()) {
1993 if (Uses.
count(Reg)) {
2000 if (Defs.
count(Reg) && !MO.isDead()) {
2015 }
else if (!ActiveDefsSet.
count(Reg)) {
2016 if (Defs.
count(Reg)) {
2022 if (MO.isKill() && Uses.
count(Reg))
2025 MO.setIsKill(
false);
2031 bool DontMoveAcrossStore =
true;
2032 if (!TIB->isSafeToMove(
nullptr, DontMoveAcrossStore))
2037 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
2042 if (!AllDefsSet.
count(Reg)) {
2047 ActiveDefsSet.
erase(*AI);
2049 ActiveDefsSet.
erase(Reg);
2055 if (!MO.isReg() || !MO.isDef() || MO.isDead())
2073 FBB->erase(FBB->begin(), FIB);
2075 if (UpdateLiveIns) {
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...
const_iterator end(StringRef path)
Get end iterator over path.
A common definition of LaneBitmask for use in TableGen and CodeGen.
const std::vector< MachineJumpTableEntry > & getJumpTables() 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.
MachineBasicBlock * getMBB() const
This class represents lattice values for constants.
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them...
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...
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
bool isCFIInstruction() const
iterator getFirstNonDebugInstr()
Returns an iterator to the first non-debug instruction in the basic block, or end().
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Analysis providing profile information.
void setIsUndef(bool Val=true)
Address of indexed Jump Table for switch.
virtual MachineInstr & duplicate(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) const
Clones instruction or the whole instruction bundle Orig and insert into MBB before InsertBefore...
void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
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 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...
MachineBasicBlock reference.
STATISTIC(NumFunctions, "Total number of functions")
void moveAfter(MachineBasicBlock *NewBefore)
static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB)
getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch instructions on the block...
virtual unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const
Remove the branching code at the end of the specific MBB.
const MachineBlockFrequencyInfo & getMBFI()
iterator_range< succ_iterator > successors()
virtual bool isUnpredicatedTerminator(const MachineInstr &MI) const
Returns true if the instruction is a terminator instruction that has not been predicated.
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.
INITIALIZE_PASS(BranchFolderPass, DEBUG_TYPE, "Control Flow Optimizer", false, false) bool BranchFolderPass
BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
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...
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
unsigned getNumOperands() const
Retuns the total number of operands.
BranchFolder(bool defaultEnableTailMerge, bool CommonHoist, MBFIWrapper &FreqInfo, const MachineBranchProbabilityInfo &ProbInfo, ProfileSummaryInfo *PSI, unsigned MinTailLength=0)
static void copyDebugInfoToPredecessor(const TargetInstrInfo *TII, MachineBasicBlock &MBB, MachineBasicBlock &PredMBB)
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Name of external global symbol.
static constexpr LaneBitmask getAll()
static unsigned HashEndOfMBB(const MachineBasicBlock &MBB)
HashEndOfMBB - Hash the last instruction in the MBB.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
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...
Target-Independent Code Generator Pass Configuration Options.
BlockT * getHeader() const
static bool countsAsInstruction(const MachineInstr &MI)
Whether MI should be counted as an instruction when calculating common tail.
static bool isSimple(Instruction *I)
bool isIndirectBranch(QueryType Type=AnyInBundle) const
Return true if this is an indirect branch, such as a branch through a register.
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)
void addLiveIns(MachineBasicBlock &MBB, const LivePhysRegs &LiveRegs)
Adds registers contained in LiveRegs to the block live-in list of MBB.
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.
static MachineBasicBlock::iterator skipBackwardPastNonInstructions(MachineBasicBlock::iterator I, MachineBasicBlock *MBB)
Iterate backwards from the given iterator I, towards the beginning of the block.
void eraseCallSiteInfo(const MachineInstr *MI)
Erase the call site info for MI.
iterator getLastNonDebugInstr()
Returns an iterator to the last non-debug instruction in the basic block, or end().
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
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...
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
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
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)
bool isReturn(QueryType Type=AnyInBundle) const
bool getEnableTailMerge() const
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
Address of a global value.
virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail, MachineBasicBlock *NewDest) const
Delete the instruction OldInst and everything after it, replacing it with an unconditional branch to ...
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.
iterator SkipPHIsAndLabels(iterator I)
Return the first instruction in MBB after I that is not a PHI or a label.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
LLVM Basic Block Representation.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
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...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void addLiveOuts(const MachineBasicBlock &MBB)
Adds all live-out registers of basic block MBB.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
static void salvageDebugInfoFromEmptyBlock(const TargetInstrInfo *TII, MachineBasicBlock &MBB)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void init(const TargetRegisterInfo &TRI)
(re-)initializes and clears the set.
MCRegAliasIterator enumerates all registers aliasing Reg.
Represent the analysis usage information of a pass.
void stepBackward(const MachineInstr &MI)
Simulates liveness when stepping backwards over an instruction(bundle).
raw_ostream & printBlockFreq(raw_ostream &OS, const MachineBasicBlock *MBB) const
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()
uint64_t getEntryFreq() const
succ_iterator succ_begin()
bool hasAddressTaken() const
Test whether this block is potentially the target of an indirect branch.
void moveBefore(MachineBasicBlock *NewAfter)
Move 'this' block before or after the specified block.
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...
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()
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
virtual bool canMakeTailCallConditional(SmallVectorImpl< MachineOperand > &Cond, const MachineInstr &TailCall) const
Returns true if the tail call can be made conditional on BranchCond.
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...
virtual bool isPredicated(const MachineInstr &MI) const
Returns true if the instruction is already predicated.
bool isDebugInstr() const
static cl::opt< unsigned > TailMergeSize("tail-merge-size", cl::desc("Min number of instructions to consider tail merging"), cl::init(3), cl::Hidden)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void computeLiveIns(LivePhysRegs &LiveRegs, const MachineBasicBlock &MBB)
Computes registers live-in to MBB assuming all of its successors live-in lists are up-to-date...
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.
bool available(const MachineRegisterInfo &MRI, MCPhysReg Reg) const
Returns true if register Reg and no aliasing register is in the set.
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...
static void addRegAndItsAliases(unsigned Reg, const TargetRegisterInfo *TRI, Container &Set)
static BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
DenseMap< const MachineBasicBlock *, int > getEHScopeMembership(const MachineFunction &MF)
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
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...
IterT skipDebugInstructionsBackward(IterT It, IterT Begin)
Decrement It until it points to a non-debug instruction or to Begin and return the resulting iterator...
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.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
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...
DebugLoc findBranchDebugLoc()
Find and return the merged DebugLoc of the branch instructions of the block.
unsigned succ_size() const
void computeAndAddLiveIns(LivePhysRegs &LiveRegs, MachineBasicBlock &MBB)
Convenience function combining computeLiveIns() and addLiveIns().
IterT skipDebugInstructionsForward(IterT It, IterT End)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator...
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Representation of each machine instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
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.
A set of physical registers with utility functions to track liveness when walking backward/forward th...
bool isEHPad() const
Returns true if the block is a landing pad.
LLVM_NODISCARD bool empty() const
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
int64_t getOffset() const
Return the offset from the symbol in this operand.
Pair of physical register and lane mask.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
const MachineBasicBlock & back() const
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
static bool IsBranchOnlyBlock(MachineBasicBlock *MBB)
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
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
iterator_range< livein_iterator > liveins() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
static MachineBasicBlock * findFalseBlock(MachineBasicBlock *BB, MachineBasicBlock *TrueBB)
findFalseBlock - BB has a fallthrough.
virtual bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const
Reverses the branch condition of the specified condition list, returning false on success and true if...
void erase(iterator MBBI)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void insert(iterator MBBI, MachineBasicBlock *MBB)
void clear()
Clears the set.
static void recomputeLiveIns(MachineBasicBlock &MBB)
Convenience function for recomputing live-in's for MBB.
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
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 > &EHScopeMembership, bool AfterPlacement, BranchFolder::MBFIWrapper &MBBFreqInfo, ProfileSummaryInfo *PSI)
ProfitableToMerge - Check if two machine basic blocks have a common tail and decide if it would be pr...
virtual void replaceBranchWithTailCall(MachineBasicBlock &MBB, SmallVectorImpl< MachineOperand > &Cond, const MachineInstr &TailCall) const
Replace the conditional branch in MBB with a conditional tail call.
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...
This class keeps track of branch frequencies of newly created blocks and tail-merged blocks...
bool isBarrier(QueryType Type=AnyInBundle) const
Returns true if the specified instruction stops control flow from executing the instruction immediate...
virtual bool trackLivenessAfterRegAlloc(const MachineFunction &MF) const
Returns true if the live-ins should be tracked after register allocation.
Address of indexed Constant in Constant Pool.
bool operator<(const DeltaInfo &LHS, int64_t Delta)
Register getReg() const
getReg - Returns the register number.
virtual bool isUnconditionalTailCall(const MachineInstr &MI) const
Returns true if MI is an unconditional tail call.
UnaryPredicate for_each(R &&Range, UnaryPredicate P)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly...
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
const MachineOperand & getOperand(unsigned i) const
static void copyDebugInfoToSuccessor(const TargetInstrInfo *TII, MachineBasicBlock &MBB, MachineBasicBlock &SuccMBB)
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
bool CorrectExtraCFGEdges(MachineBasicBlock *DestA, MachineBasicBlock *DestB, bool IsCond)
Various pieces of code can cause excess edges in the CFG to be inserted.
Wrapper class representing virtual and physical registers.
This class contains meta information specific to a module.
static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1, MachineBasicBlock *MBB2, MachineBasicBlock::iterator &I1, MachineBasicBlock::iterator &I2)
Given two machine basic blocks, return the number of instructions they actually have in common togeth...
LoopInfoBase< MachineBasicBlock, MachineLoop > & getBase()
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.