98 #define DEBUG_TYPE "peephole-opt"
103 cl::desc(
"Aggressive extension optimization"));
107 cl::desc(
"Disable the peephole optimizer"));
111 cl::desc(
"Disable advanced copy optimization"));
115 cl::desc(
"Disable non-allocatable physical register copy optimization"));
121 cl::desc(
"Limit the length of PHI chains to lookup"));
127 cl::desc(
"Maximum length of recurrence chain when evaluating the benefit "
128 "of commuting operands"));
131 STATISTIC(NumReuse,
"Number of extension results reused");
132 STATISTIC(NumCmps,
"Number of compares eliminated");
133 STATISTIC(NumImmFold,
"Number of move immediate folded");
134 STATISTIC(NumLoadFold,
"Number of loads folded");
135 STATISTIC(NumSelects,
"Number of selects optimized");
136 STATISTIC(NumUncoalescableCopies,
"Number of uncoalescable copies optimized");
137 STATISTIC(NumRewrittenCopies,
"Number of copies rewritten");
138 STATISTIC(NumNAPhysCopies,
"Number of non-allocatable physical copies removed");
142 class ValueTrackerResult;
143 class RecurrenceInstr;
190 bool findNextSource(
unsigned Reg,
unsigned SubReg,
191 RewriteMapTy &RewriteMap);
202 bool findTargetRecurrence(
unsigned Reg,
204 RecurrenceCycle &RC);
215 bool isNAPhysCopy(
unsigned Reg);
222 bool foldRedundantNAPhysCopy(
255 class RecurrenceInstr {
257 typedef std::pair<unsigned, unsigned> IndexPair;
260 RecurrenceInstr(
MachineInstr *MI,
unsigned Idx1,
unsigned Idx2)
261 : MI(MI), CommutePair(std::make_pair(Idx1, Idx2)) {}
274 class ValueTrackerResult {
283 ValueTrackerResult() : Inst(nullptr) {}
284 ValueTrackerResult(
unsigned Reg,
unsigned SubReg) : Inst(nullptr) {
285 addSource(Reg, SubReg);
288 bool isValid()
const {
return getNumSources() > 0; }
298 void addSource(
unsigned SrcReg,
unsigned SrcSubReg) {
302 void setSource(
int Idx,
unsigned SrcReg,
unsigned SrcSubReg) {
303 assert(Idx < getNumSources() &&
"Reg pair source out of index");
307 int getNumSources()
const {
return RegSrcs.size(); }
309 unsigned getSrcReg(
int Idx)
const {
310 assert(Idx < getNumSources() &&
"Reg source out of index");
311 return RegSrcs[Idx].Reg;
314 unsigned getSrcSubReg(
int Idx)
const {
315 assert(Idx < getNumSources() &&
"SubReg source out of index");
316 return RegSrcs[Idx].SubReg;
319 bool operator==(
const ValueTrackerResult &Other) {
320 if (Other.getInst() != getInst())
323 if (Other.getNumSources() != getNumSources())
326 for (
int i = 0, e = Other.getNumSources(); i != e; ++i)
327 if (Other.getSrcReg(i) != getSrcReg(i) ||
328 Other.getSrcSubReg(i) != getSrcSubReg(i))
367 bool UseAdvancedTracking;
376 ValueTrackerResult getNextSourceImpl();
378 ValueTrackerResult getNextSourceFromCopy();
380 ValueTrackerResult getNextSourceFromBitcast();
383 ValueTrackerResult getNextSourceFromRegSequence();
386 ValueTrackerResult getNextSourceFromInsertSubreg();
389 ValueTrackerResult getNextSourceFromExtractSubreg();
392 ValueTrackerResult getNextSourceFromSubregToReg();
394 ValueTrackerResult getNextSourceFromPHI();
409 ValueTracker(
unsigned Reg,
unsigned DefSubReg,
411 bool UseAdvancedTracking =
false,
413 :
Def(nullptr), DefIdx(0), DefSubReg(DefSubReg), Reg(Reg),
414 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI),
TII(
TII) {
428 ValueTracker(
const MachineInstr &MI,
unsigned DefIdx,
unsigned DefSubReg,
430 bool UseAdvancedTracking =
false,
432 :
Def(&MI), DefIdx(DefIdx), DefSubReg(DefSubReg),
433 UseAdvancedTracking(UseAdvancedTracking), MRI(MRI),
TII(
TII) {
435 Def->getOperand(DefIdx).isReg() &&
"Invalid definition");
436 Reg =
Def->getOperand(DefIdx).getReg();
444 ValueTrackerResult getNextSource();
459 "Peephole Optimizations",
false,
false)
473 bool PeepholeOptimizer::
476 unsigned SrcReg, DstReg, SubIdx;
477 if (!
TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
491 DstRC = TRI->getSubClassWithSubReg(DstRC, SubIdx);
501 TRI->getSubClassWithSubReg(MRI->
getRegClass(SrcReg), SubIdx) !=
nullptr;
507 ReachedBBs.
insert(UI.getParent());
515 bool ExtendLife =
true;
521 if (UseMI->
isPHI()) {
527 if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
547 if (UseMI->
getOpcode() == TargetOpcode::SUBREG_TO_REG)
553 if (!LocalMIs.count(UseMI))
555 }
else if (ReachedBBs.
count(UseMBB)) {
559 }
else if (
Aggressive && DT->dominates(MBB, UseMBB)) {
571 if (ExtendLife && !ExtendedUses.
empty())
576 bool Changed =
false;
585 PHIBBs.
insert(UI.getParent());
588 for (
unsigned i = 0, e = Uses.
size(); i != e; ++i) {
592 if (PHIBBs.
count(UseMBB))
603 TII->get(TargetOpcode::COPY), NewVR)
604 .addReg(DstReg, 0, SubIdx);
623 bool PeepholeOptimizer::optimizeCmpInstr(
MachineInstr *MI,
627 unsigned SrcReg, SrcReg2;
628 int CmpMask, CmpValue;
635 if (
TII->optimizeCompareInstr(*MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
644 bool PeepholeOptimizer::optimizeSelect(
MachineInstr *MI,
647 unsigned FalseOp = 0;
648 bool Optimizable =
false;
650 if (
TII->analyzeSelect(*MI, Cond, TrueOp, FalseOp, Optimizable))
654 if (!
TII->optimizeSelect(*MI, LocalMIs))
663 bool PeepholeOptimizer::optimizeCondBranch(
MachineInstr *MI) {
664 return TII->optimizeCondBranch(*MI);
678 bool PeepholeOptimizer::findNextSource(
unsigned Reg,
unsigned SubReg,
679 RewriteMapTy &RewriteMap) {
692 unsigned PHICount = 0;
700 ValueTracker ValTracker(CurSrcPair.Reg, CurSrcPair.SubReg, *MRI,
702 ValueTrackerResult Res;
703 bool ShouldRewrite =
false;
708 Res = ValTracker.getNextSource();
713 ValueTrackerResult CurSrcRes = RewriteMap.lookup(CurSrcPair);
714 if (CurSrcRes.isValid()) {
715 assert(CurSrcRes == Res &&
"ValueTrackerResult found must match");
718 if (CurSrcRes.getNumSources() > 1) {
719 DEBUG(
dbgs() <<
"findNextSource: found PHI cycle, aborting...\n");
724 RewriteMap.insert(std::make_pair(CurSrcPair, Res));
728 unsigned NumSrcs = Res.getNumSources();
731 for (
unsigned i = 0; i < NumSrcs; ++i)
733 Res.getSrcReg(i), Res.getSrcSubReg(i)));
737 CurSrcPair.Reg = Res.getSrcReg(0);
738 CurSrcPair.SubReg = Res.getSrcSubReg(0);
747 ShouldRewrite = TRI->shouldRewriteCopySrc(DefRC, SubReg, SrcRC,
749 }
while (!ShouldRewrite);
762 DEBUG(
dbgs() <<
"findNextSource: PHI limit reached\n");
767 return CurSrcPair.Reg !=
Reg;
779 assert(!SrcRegs.
empty() &&
"No sources to create a PHI instruction?");
785 TII->
get(TargetOpcode::PHI), NewVR);
787 unsigned MBBOpIdx = 2;
788 for (
auto RegPair : SrcRegs) {
789 MIB.
addReg(RegPair.Reg, 0, RegPair.SubReg);
809 unsigned CurrentSrcIdx;
812 CopyRewriter(
MachineInstr &MI) : CopyLike(MI), CurrentSrcIdx(0) {}
814 virtual ~CopyRewriter() {}
841 virtual bool getNextRewritableSource(
unsigned &SrcReg,
unsigned &SrcSubReg,
843 unsigned &TrackSubReg) {
847 if (!CopyLike.isCopy() || CurrentSrcIdx == 1)
858 TrackReg = MODef.
getReg();
866 virtual bool RewriteCurrentSource(
unsigned NewReg,
unsigned NewSubReg) {
867 if (!CopyLike.isCopy() || CurrentSrcIdx != 1)
885 bool HandleMultipleSources =
true) {
888 ValueTrackerResult Res = RewriteMap.
lookup(LookupSrc);
894 unsigned NumSrcs = Res.getNumSources();
896 LookupSrc.Reg = Res.getSrcReg(0);
897 LookupSrc.SubReg = Res.getSrcSubReg(0);
902 if (!HandleMultipleSources)
908 for (
unsigned i = 0; i < NumSrcs; ++i) {
910 Res.getSrcSubReg(i));
912 getNewSource(MRI, TII, PHISrc, RewriteMap, HandleMultipleSources));
919 DEBUG(
dbgs() <<
" Replacing: " << *OrigPHI);
943 class UncoalescableRewriter :
public CopyRewriter {
953 : CopyRewriter(MI), TII(TII), MRI(MRI) {
962 bool getNextRewritableSource(
unsigned &SrcReg,
unsigned &SrcSubReg,
964 unsigned &TrackSubReg)
override {
966 if (CurrentSrcIdx == NumDefs)
969 while (CopyLike.getOperand(CurrentSrcIdx).isDead()) {
971 if (CurrentSrcIdx == NumDefs)
977 TrackReg = MODef.
getReg();
993 "We do not rewrite physical registers");
997 getNewSource(&MRI, &TII, Def, RewriteMap);
1004 BuildMI(*CopyLike.getParent(), &CopyLike, CopyLike.getDebugLoc(),
1005 TII.
get(TargetOpcode::COPY), NewVR)
1013 DEBUG(
dbgs() <<
" Replacing: " << CopyLike);
1027 class InsertSubregRewriter :
public CopyRewriter {
1029 InsertSubregRewriter(
MachineInstr &MI) : CopyRewriter(MI) {
1044 bool getNextRewritableSource(
unsigned &SrcReg,
unsigned &SrcSubReg,
1046 unsigned &TrackSubReg)
override {
1048 if (CurrentSrcIdx == 2)
1053 SrcReg = MOInsertedReg.
getReg();
1059 TrackReg = MODef.
getReg();
1063 TrackSubReg = (
unsigned)CopyLike.getOperand(3).getImm();
1067 bool RewriteCurrentSource(
unsigned NewReg,
unsigned NewSubReg)
override {
1068 if (CurrentSrcIdx != 2)
1079 class ExtractSubregRewriter :
public CopyRewriter {
1084 : CopyRewriter(MI), TII(TII) {
1093 bool getNextRewritableSource(
unsigned &SrcReg,
unsigned &SrcSubReg,
1095 unsigned &TrackSubReg)
override {
1097 if (CurrentSrcIdx == 1)
1102 SrcReg = MOExtractedReg.
getReg();
1107 SrcSubReg = CopyLike.getOperand(2).getImm();
1111 TrackReg = MODef.
getReg();
1116 bool RewriteCurrentSource(
unsigned NewReg,
unsigned NewSubReg)
override {
1118 if (CurrentSrcIdx != 1)
1121 CopyLike.getOperand(CurrentSrcIdx).setReg(NewReg);
1132 CopyLike.RemoveOperand(2);
1134 CopyLike.setDesc(TII.
get(TargetOpcode::COPY));
1137 CopyLike.getOperand(CurrentSrcIdx + 1).setImm(NewSubReg);
1143 class RegSequenceRewriter :
public CopyRewriter {
1145 RegSequenceRewriter(
MachineInstr &MI) : CopyRewriter(MI) {
1165 bool getNextRewritableSource(
unsigned &SrcReg,
unsigned &SrcSubReg,
1167 unsigned &TrackSubReg)
override {
1171 if (CurrentSrcIdx == 0) {
1176 if (CurrentSrcIdx >= CopyLike.getNumOperands())
1179 const MachineOperand &MOInsertedReg = CopyLike.getOperand(CurrentSrcIdx);
1180 SrcReg = MOInsertedReg.
getReg();
1182 if ((SrcSubReg = MOInsertedReg.
getSubReg()))
1187 TrackSubReg = CopyLike.getOperand(CurrentSrcIdx + 1).getImm();
1190 TrackReg = MODef.
getReg();
1195 bool RewriteCurrentSource(
unsigned NewReg,
unsigned NewSubReg)
override {
1198 if ((CurrentSrcIdx & 1) != 1 || CurrentSrcIdx > CopyLike.getNumOperands())
1219 return new UncoalescableRewriter(MI, TII, MRI);
1224 case TargetOpcode::COPY:
1225 return new CopyRewriter(MI);
1226 case TargetOpcode::INSERT_SUBREG:
1227 return new InsertSubregRewriter(MI);
1228 case TargetOpcode::EXTRACT_SUBREG:
1229 return new ExtractSubregRewriter(MI, TII);
1230 case TargetOpcode::REG_SEQUENCE:
1231 return new RegSequenceRewriter(MI);
1248 bool PeepholeOptimizer::optimizeCoalescableCopy(
MachineInstr *MI) {
1249 assert(MI && isCoalescableCopy(*MI) &&
"Invalid argument");
1251 "Coalescer can understand multiple defs?!");
1257 bool Changed =
false;
1259 std::unique_ptr<CopyRewriter> CpyRewriter(
getCopyRewriter(*MI, *TII, *MRI));
1264 unsigned SrcReg, SrcSubReg, TrackReg, TrackSubReg;
1265 while (CpyRewriter->getNextRewritableSource(SrcReg, SrcSubReg, TrackReg,
1268 RewriteMapTy RewriteMap;
1271 if (!findNextSource(TrackReg, TrackSubReg, RewriteMap))
1278 MRI, TII, TrackPair, RewriteMap,
false );
1279 if (SrcReg == NewSrc.
Reg || NewSrc.
Reg == 0)
1283 if (CpyRewriter->RewriteCurrentSource(NewSrc.
Reg, NewSrc.
SubReg)) {
1294 NumRewrittenCopies += Changed;
1309 bool PeepholeOptimizer::optimizeUncoalescableCopy(
1311 assert(MI && isUncoalescableCopy(*MI) &&
"Invalid argument");
1316 std::unique_ptr<CopyRewriter> CpyRewriter(
getCopyRewriter(*MI, *TII, *MRI));
1324 RewriteMapTy RewriteMap;
1325 unsigned Reg,
SubReg, CopyDefReg, CopyDefSubReg;
1326 while (CpyRewriter->getNextRewritableSource(Reg, SubReg, CopyDefReg,
1336 if (!findNextSource(Def.
Reg, Def.
SubReg, RewriteMap))
1343 for (
const auto &Def : RewritePairs) {
1345 MachineInstr *NewCopy = CpyRewriter->RewriteSource(Def, RewriteMap);
1346 assert(NewCopy &&
"Should be able to always generate a new copy");
1347 LocalMIs.
insert(NewCopy);
1352 ++NumUncoalescableCopies;
1359 bool PeepholeOptimizer::isLoadFoldable(
1374 FoldAsLoadDefCandidates.
insert(Reg);
1380 bool PeepholeOptimizer::isMoveImmediate(
1390 ImmDefMIs.
insert(std::make_pair(Reg, MI));
1401 bool PeepholeOptimizer::foldImmediate(
1411 unsigned Reg = MO.
getReg();
1414 if (ImmDefRegs.
count(Reg) == 0)
1417 assert(II != ImmDefMIs.
end() &&
"couldn't find immediate definition");
1440 bool PeepholeOptimizer::foldRedundantCopy(
1443 assert(MI->
isCopy() &&
"expected a COPY machine instruction");
1453 if (CopySrcRegs.
insert(SrcReg).second) {
1455 CopyMIs.
insert(std::make_pair(SrcReg, MI));
1465 if (SrcSubReg != PrevSrcSubReg)
1484 bool PeepholeOptimizer::isNAPhysCopy(
unsigned Reg) {
1489 bool PeepholeOptimizer::foldRedundantNAPhysCopy(
1491 assert(MI->
isCopy() &&
"expected a COPY machine instruction");
1502 NAPhysToVirtMIs.
insert({SrcReg, MI});
1510 auto PrevCopy = NAPhysToVirtMIs.
find(DstReg);
1511 if (PrevCopy == NAPhysToVirtMIs.
end()) {
1514 DEBUG(
dbgs() <<
"NAPhysCopy: intervening clobber forbids erasing " << *MI
1520 if (PrevDstReg == SrcReg) {
1523 DEBUG(
dbgs() <<
"NAPhysCopy: erasing " << *MI <<
'\n');
1532 DEBUG(
dbgs() <<
"NAPhysCopy: missed opportunity " << *MI <<
'\n');
1533 NAPhysToVirtMIs.
erase(PrevCopy);
1544 bool PeepholeOptimizer::findTargetRecurrence(
1546 RecurrenceCycle &RC) {
1548 if (TargetRegs.
count(Reg))
1578 unsigned TiedUseIdx;
1582 if (Idx == TiedUseIdx) {
1583 RC.push_back(RecurrenceInstr(&MI));
1584 return findTargetRecurrence(DefOp.
getReg(), TargetRegs, RC);
1589 RC.push_back(RecurrenceInstr(&MI, Idx, CommIdx));
1590 return findTargetRecurrence(DefOp.
getReg(), TargetRegs, RC);
1615 bool PeepholeOptimizer::optimizeRecurrence(
MachineInstr &PHI) {
1623 bool Changed =
false;
1628 DEBUG(
dbgs() <<
"Optimize recurrence chain from " << PHI);
1629 for (
auto &RI : RC) {
1630 DEBUG(
dbgs() <<
"\tInst: " << *(RI.getMI()));
1631 auto CP = RI.getCommutePair();
1636 DEBUG(
dbgs() <<
"\t\tCommuted: " << *(RI.getMI()));
1648 DEBUG(
dbgs() <<
"********** PEEPHOLE OPTIMIZER **********\n");
1657 DT =
Aggressive ? &getAnalysis<MachineDominatorTree>() :
nullptr;
1658 MLI = &getAnalysis<MachineLoopInfo>();
1660 bool Changed =
false;
1663 bool SeenMoveImm =
false;
1687 bool IsLoopHeader = MLI->isLoopHeader(&MBB);
1703 if (IsLoopHeader && MI->
isPHI()) {
1704 if (optimizeRecurrence(*MI)) {
1714 unsigned Reg =
Op.getReg();
1715 if (
Op.isDef() && isNAPhysCopy(Reg)) {
1716 const auto &Def = NAPhysToVirtMIs.
find(Reg);
1717 if (Def != NAPhysToVirtMIs.
end()) {
1720 DEBUG(
dbgs() <<
"NAPhysCopy: invalidating because of " << *MI
1722 NAPhysToVirtMIs.
erase(Def);
1725 }
else if (
Op.isRegMask()) {
1727 for (
auto &RegMI : NAPhysToVirtMIs) {
1728 unsigned Def = RegMI.first;
1730 DEBUG(
dbgs() <<
"NAPhysCopy: invalidating because of " << *MI
1732 NAPhysToVirtMIs.erase(Def);
1747 DEBUG(
dbgs() <<
"NAPhysCopy: blowing away all info due to " << *MI
1749 NAPhysToVirtMIs.clear();
1752 if ((isUncoalescableCopy(*MI) &&
1753 optimizeUncoalescableCopy(MI, LocalMIs)) ||
1754 (MI->
isCompare() && optimizeCmpInstr(MI, &MBB)) ||
1755 (MI->
isSelect() && optimizeSelect(MI, LocalMIs))) {
1767 if (isCoalescableCopy(*MI) && optimizeCoalescableCopy(MI)) {
1774 (foldRedundantCopy(MI, CopySrcRegs, CopySrcMIs) ||
1775 foldRedundantNAPhysCopy(MI, NAPhysToVirtMIs))) {
1782 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
1785 Changed |= optimizeExtInstr(MI, &MBB, LocalMIs);
1792 Changed |= foldImmediate(MI, &MBB, ImmDefRegs, ImmDefMIs);
1798 if (!isLoadFoldable(MI, FoldAsLoadDefCandidates) &&
1799 !FoldAsLoadDefCandidates.
empty()) {
1812 unsigned FoldAsLoadDefReg = MOp.
getReg();
1813 if (FoldAsLoadDefCandidates.
count(FoldAsLoadDefReg)) {
1818 unsigned FoldedReg = FoldAsLoadDefReg;
1827 LocalMIs.
erase(DefMI);
1832 FoldAsLoadDefCandidates.
erase(FoldedReg);
1847 DEBUG(
dbgs() <<
"Encountered load fold barrier on " << *MI <<
"\n");
1848 FoldAsLoadDefCandidates.
clear();
1857 ValueTrackerResult ValueTracker::getNextSourceFromCopy() {
1858 assert(Def->isCopy() &&
"Invalid definition");
1861 assert(Def->getNumOperands() == 2 &&
"Invalid number of operands");
1863 if (Def->getOperand(DefIdx).getSubReg() != DefSubReg)
1866 return ValueTrackerResult();
1872 ValueTrackerResult ValueTracker::getNextSourceFromBitcast() {
1873 assert(Def->isBitcast() &&
"Invalid definition");
1876 if (Def->hasUnmodeledSideEffects())
1877 return ValueTrackerResult();
1880 if (Def->getDesc().getNumDefs() != 1)
1881 return ValueTrackerResult();
1886 return ValueTrackerResult();
1888 unsigned SrcIdx = Def->getNumOperands();
1889 for (
unsigned OpIdx = DefIdx + 1, EndOpIdx = SrcIdx; OpIdx != EndOpIdx;
1897 assert(!MO.
isDef() &&
"We should have skipped all the definitions by now");
1898 if (SrcIdx != EndOpIdx)
1900 return ValueTrackerResult();
1907 if (
UseMI.isSubregToReg())
1908 return ValueTrackerResult();
1915 ValueTrackerResult ValueTracker::getNextSourceFromRegSequence() {
1916 assert((Def->isRegSequence() || Def->isRegSequenceLike()) &&
1917 "Invalid definition");
1919 if (Def->getOperand(DefIdx).getSubReg())
1934 return ValueTrackerResult();
1939 return ValueTrackerResult();
1943 return ValueTrackerResult();
1948 for (
auto &RegSeqInput : RegSeqInputRegs) {
1949 if (RegSeqInput.SubIdx == DefSubReg) {
1950 if (RegSeqInput.SubReg)
1952 return ValueTrackerResult();
1954 return ValueTrackerResult(RegSeqInput.Reg, RegSeqInput.SubReg);
1961 return ValueTrackerResult();
1964 ValueTrackerResult ValueTracker::getNextSourceFromInsertSubreg() {
1965 assert((Def->isInsertSubreg() || Def->isInsertSubregLike()) &&
1966 "Invalid definition");
1968 if (Def->getOperand(DefIdx).getSubReg())
1972 return ValueTrackerResult();
1977 return ValueTrackerResult();
1982 return ValueTrackerResult();
1991 if (InsertedReg.
SubIdx == DefSubReg) {
1992 return ValueTrackerResult(InsertedReg.
Reg, InsertedReg.
SubReg);
2003 return ValueTrackerResult();
2011 return ValueTrackerResult();
2014 return ValueTrackerResult(BaseReg.
Reg, DefSubReg);
2017 ValueTrackerResult ValueTracker::getNextSourceFromExtractSubreg() {
2018 assert((Def->isExtractSubreg() ||
2019 Def->isExtractSubregLike()) &&
"Invalid definition");
2026 return ValueTrackerResult();
2031 return ValueTrackerResult();
2035 return ValueTrackerResult();
2039 if (ExtractSubregInputReg.
SubReg)
2040 return ValueTrackerResult();
2042 return ValueTrackerResult(ExtractSubregInputReg.
Reg,
2043 ExtractSubregInputReg.
SubIdx);
2046 ValueTrackerResult ValueTracker::getNextSourceFromSubregToReg() {
2047 assert(Def->isSubregToReg() &&
"Invalid definition");
2055 if (DefSubReg != Def->getOperand(3).getImm())
2056 return ValueTrackerResult();
2059 if (Def->getOperand(2).getSubReg())
2060 return ValueTrackerResult();
2062 return ValueTrackerResult(Def->getOperand(2).getReg(),
2063 Def->getOperand(3).getImm());
2067 ValueTrackerResult ValueTracker::getNextSourceFromPHI() {
2068 assert(Def->isPHI() &&
"Invalid definition");
2069 ValueTrackerResult Res;
2073 if (Def->getOperand(0).getSubReg() != DefSubReg)
2074 return ValueTrackerResult();
2077 for (
unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2) {
2078 auto &MO = Def->getOperand(i);
2086 ValueTrackerResult ValueTracker::getNextSourceImpl() {
2087 assert(Def &&
"This method needs a valid definition");
2089 assert(((Def->getOperand(DefIdx).isDef() &&
2090 (DefIdx < Def->getDesc().getNumDefs() ||
2091 Def->getDesc().isVariadic())) ||
2092 Def->getOperand(DefIdx).isImplicit()) &&
2095 return getNextSourceFromCopy();
2096 if (Def->isBitcast())
2097 return getNextSourceFromBitcast();
2100 if (!UseAdvancedTracking)
2101 return ValueTrackerResult();
2102 if (Def->isRegSequence() || Def->isRegSequenceLike())
2103 return getNextSourceFromRegSequence();
2104 if (Def->isInsertSubreg() || Def->isInsertSubregLike())
2105 return getNextSourceFromInsertSubreg();
2106 if (Def->isExtractSubreg() || Def->isExtractSubregLike())
2107 return getNextSourceFromExtractSubreg();
2108 if (Def->isSubregToReg())
2109 return getNextSourceFromSubregToReg();
2111 return getNextSourceFromPHI();
2112 return ValueTrackerResult();
2115 ValueTrackerResult ValueTracker::getNextSource() {
2119 return ValueTrackerResult();
2121 ValueTrackerResult Res = getNextSourceImpl();
2122 if (Res.isValid()) {
2126 bool OneRegSrc = Res.getNumSources() == 1;
2128 Reg = Res.getSrcReg(0);
2138 DefSubReg = Res.getSrcSubReg(0);
static cl::opt< unsigned > MaxRecurrenceChain("recurrence-chain-limit", cl::Hidden, cl::init(3), cl::desc("Maximum length of recurrence chain when evaluating the benefit ""of commuting operands"))
void push_back(const T &Elt)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
bool isLoadFoldBarrier() const
Returns true if it is illegal to fold a load across this instruction.
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...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
STATISTIC(NumFunctions,"Total number of functions")
MachineBasicBlock * getMBB() const
use_instr_nodbg_iterator use_instr_nodbg_begin(unsigned RegNo) const
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
unsigned createVirtualRegister(const TargetRegisterClass *RegClass)
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
static cl::opt< bool > DisableNAPhysCopyOpt("disable-non-allocatable-phys-copy-opt", cl::Hidden, cl::init(false), cl::desc("Disable non-allocatable physical register copy optimization"))
Describe properties that are true of each instruction in the target description file.
void setIsUndef(bool Val=true)
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
bool getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx, SmallVectorImpl< RegSubRegPairAndIdx > &InputRegs) const
Build the equivalent inputs of a REG_SEQUENCE for the given MI and DefIdx.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
MachineInstr * commuteInstruction(MachineInstr &MI, bool NewMI=false, unsigned OpIdx1=CommuteAnyOperandIndex, unsigned OpIdx2=CommuteAnyOperandIndex) const
This method commutes the operands of the given machine instruction MI.
bool canFoldAsLoad(QueryType Type=IgnoreBundle) const
Return true for instructions that can be folded as memory operands in other instructions.
bool isConditionalBranch(QueryType Type=AnyInBundle) const
Return true if this is a branch which may fall through to the next instruction or may transfer contro...
LaneBitmask getSubRegIndexLaneMask(unsigned SubIdx) const
Return a bitmask representing the parts of a register that are covered by SubIdx. ...
iterator_range< mop_iterator > operands()
bool isExtractSubreg() const
void markUsesInDebugValueAsUndef(unsigned Reg) const
markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the specified register as undefined wh...
bool isSelect(QueryType Type=IgnoreBundle) const
Return true if this instruction is a select instruction.
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)
LLVM_NODISCARD bool empty() const
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
const TargetRegisterInfo * getTargetRegisterInfo() const
static cl::opt< bool > Aggressive("aggressive-ext-opt", cl::Hidden, cl::desc("Aggressive extension optimization"))
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
Reg
All possible values of the reg field in the ModR/M byte.
static MachineInstr * insertPHI(MachineRegisterInfo *MRI, const TargetInstrInfo *TII, const SmallVectorImpl< TargetInstrInfo::RegSubRegPair > &SrcRegs, MachineInstr *OrigPHI)
Insert a PHI instruction with incoming edges SrcRegs that are guaranteed to have the same register cl...
LLVM_NODISCARD bool empty() const
unsigned getNumOperands() const
Access to explicit operands of the instruction.
void initializePeepholeOptimizerPass(PassRegistry &)
bool isBitcast(QueryType Type=IgnoreBundle) const
Return true if this instruction is a bitcast instruction.
const TargetRegisterClass * constrainRegClass(unsigned Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
bool getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx, RegSubRegPairAndIdx &InputReg) const
Build the equivalent inputs of a EXTRACT_SUBREG for the given MI and DefIdx.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
TargetInstrInfo - Interface to description of machine instruction set.
iterator find(const_arg_type_t< KeyT > Val)
bool isDebugValue() const
bool isImplicitDef() const
bool isInsertSubreg() const
static const unsigned CommuteAnyOperandIndex
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
initializer< Ty > init(const Ty &Val)
bool erase(const KeyT &Val)
static bool isVirtualRegisterOperand(MachineOperand &MO)
Returns true if MO is a virtual register operand.
unsigned const MachineRegisterInfo * MRI
iterator_range< use_nodbg_iterator > use_nodbg_operands(unsigned Reg) const
static cl::opt< unsigned > RewritePHILimit("rewrite-phi-limit", cl::Hidden, cl::init(10), cl::desc("Limit the length of PHI chains to lookup"))
bool analyzeCompare(const MachineInstr &MI, unsigned &SrcReg, unsigned &SrcReg2, int &Mask, int &Value) const override
For a comparison instruction, return the source registers in SrcReg and SrcReg2 if having two registe...
MachineInstrBuilder & UseMI
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
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 isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx=nullptr) const
Given the index of a register def operand, check if the register def is tied to a source operand...
unsigned getOperandNo() const
getOperandNo - Return the operand # of this MachineOperand in its MachineInstr.
Represent the analysis usage information of a pass.
virtual bool findCommutedOpIndices(MachineInstr &MI, unsigned &SrcOpIdx1, unsigned &SrcOpIdx2) const
Returns true iff the routine could find two commutable operands in the given machine instruction...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore...
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
unsigned getSubReg() const
virtual MachineInstr * optimizeLoadInstr(MachineInstr &MI, const MachineRegisterInfo *MRI, unsigned &FoldAsLoadDefReg, MachineInstr *&DefMI) const
Try to remove the load by folding it to a register operand at the use.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
bool isInsertSubregLike(QueryType Type=IgnoreBundle) const
Return true if this instruction behaves the same way as the generic INSERT_SUBREG instructions...
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
int findRegisterUseOperandIdx(unsigned Reg, bool isKill=false, const TargetRegisterInfo *TRI=nullptr) const
Returns the operand index that is a use of the specific register or -1 if it is not found...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
bool getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const
Build the equivalent inputs of a INSERT_SUBREG for the given MI and DefIdx.
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
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...
A pair composed of a register and a sub-register index.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
LLVM_NODISCARD T pop_back_val()
bool isAllocatable(unsigned PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
bool isCompare(QueryType Type=IgnoreBundle) const
Return true if this instruction is a comparison.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static bool clobbersPhysReg(const uint32_t *RegMask, unsigned PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
static unsigned getReg(const void *D, unsigned RC, unsigned RegNo)
char & PeepholeOptimizerID
PeepholeOptimizer - This pass performs peephole optimizations - like extension and comparison elimina...
bool isExtractSubregLike(QueryType Type=IgnoreBundle) const
Return true if this instruction behaves the same way as the generic EXTRACT_SUBREG instructions...
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
static void clear(coro::Shape &Shape)
void replaceRegWith(unsigned FromReg, unsigned ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
def_iterator def_begin(unsigned RegNo) const
llvm_unreachable("Unknown RegBank!")
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(unsigned Reg) const
static cl::opt< bool > DisablePeephole("disable-peephole", cl::Hidden, cl::init(false), cl::desc("Disable the peephole optimizer"))
bool hasOneNonDBGUse(unsigned RegNo) const
hasOneNonDBGUse - Return true if there is exactly one non-Debug instruction using the specified regis...
void setReg(unsigned Reg)
Change the register this operand corresponds to.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
void setSubReg(unsigned subReg)
void clearKillFlags(unsigned Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
MCInstrDesc const & getDesc(MCInstrInfo const &MCII, MCInst const &MCI)
INITIALIZE_PASS(HexagonGenMux,"hexagon-gen-mux","Hexagon generate mux instructions", false, false) void HexagonGenMux I isValid()
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
unsigned getReg() const
getReg - Returns the register number.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
virtual const TargetInstrInfo * getInstrInfo() const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual bool FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, unsigned Reg, MachineRegisterInfo *MRI) const
'Reg' is known to be defined by a move immediate instruction, try to fold the immediate into the use ...
bool operator==(uint64_t V1, const APInt &V2)
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
INITIALIZE_PASS_BEGIN(PeepholeOptimizer, DEBUG_TYPE,"Peephole Optimizations", false, false) INITIALIZE_PASS_END(PeepholeOptimizer
bool isRegSequence() const
bool isMoveImmediate(QueryType Type=IgnoreBundle) const
Return true if this instruction is a move immediate (including conditional moves) instruction...
bool isRegSequenceLike(QueryType Type=IgnoreBundle) const
Return true if this instruction behaves the same way as the generic REG_SEQUENCE instructions.
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
static cl::opt< bool > DisableAdvCopyOpt("disable-adv-copy-opt", cl::Hidden, cl::init(false), cl::desc("Disable advanced copy optimization"))
static CopyRewriter * getCopyRewriter(MachineInstr &MI, const TargetInstrInfo &TII, MachineRegisterInfo &MRI)
Get the appropriated CopyRewriter for MI.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
A pair composed of a pair of a register and a sub-register index, and another sub-register index...