70#define DEBUG_TYPE "twoaddressinstruction"
72STATISTIC(NumTwoAddressInstrs,
"Number of two-address instructions");
73STATISTIC(NumCommuted ,
"Number of instructions commuted to coalesce");
74STATISTIC(NumAggrCommuted ,
"Number of instructions aggressively commuted");
75STATISTIC(NumConvertedTo3Addr,
"Number of instructions promoted to 3-address");
76STATISTIC(NumReSchedUps,
"Number of instructions re-scheduled up");
77STATISTIC(NumReSchedDowns,
"Number of instructions re-scheduled down");
82 cl::desc(
"Coalesce copies by rescheduling (default=true)"),
86 "twoaddr-analyze-revcopy-tied",
87 cl::desc(
"Analyze tied operands when looking for reversed copy chain"),
94 cl::desc(
"Maximum number of dataflow edges to traverse when evaluating "
95 "the benefit of commuting operands"));
99class TwoAddressInstructionImpl {
132 bool noUseAfterLastDef(
Register Reg,
unsigned Dist,
unsigned &LastDef);
135 bool &IsSrcPhys,
bool &IsDstPhys)
const;
145 bool &IsDstPhys)
const;
160 unsigned RegBIdx,
unsigned RegCIdx,
unsigned Dist);
177 unsigned SrcIdx,
unsigned DstIdx,
178 unsigned &Dist,
bool shouldOnlyCommute);
193 void processTiedPairs(
MachineInstr *
MI, TiedPairList&,
unsigned &Dist);
195 bool processStatepoint(
MachineInstr *
MI, TiedOperandMap &TiedOperands);
210 TwoAddressInstructionLegacyPass() : MachineFunctionPass(ID) {}
213 bool runOnMachineFunction(MachineFunction &MF)
override {
214 TwoAddressInstructionImpl Impl(MF,
this);
218 Impl.setOptLevel(CodeGenOptLevel::None);
222 void getAnalysisUsage(AnalysisUsage &AU)
const override {
244 TwoAddressInstructionImpl Impl(MF, MFAM, LIS);
267char TwoAddressInstructionLegacyPass::ID = 0;
272 "Two-Address instruction pass",
false,
false)
274TwoAddressInstructionImpl::TwoAddressInstructionImpl(
277 : MF(&Func),
TII(Func.getSubtarget().getInstrInfo()),
278 TRI(Func.getSubtarget().getRegisterInfo()),
279 InstrItins(Func.getSubtarget().getInstrItineraryData()),
280 MRI(&Func.getRegInfo()),
282 OptLevel(Func.getTarget().getOptLevel()) {}
284TwoAddressInstructionImpl::TwoAddressInstructionImpl(
MachineFunction &Func,
286 : MF(&
Func),
TII(
Func.getSubtarget().getInstrInfo()),
287 TRI(
Func.getSubtarget().getRegisterInfo()),
288 InstrItins(
Func.getSubtarget().getInstrItineraryData()),
289 MRI(&
Func.getRegInfo()), OptLevel(
Func.getTarget().getOptLevel()) {
291 LV = LVWrapper ? &LVWrapper->
getLV() :
nullptr;
293 LIS = LISWrapper ? &LISWrapper->
getLIS() :
nullptr;
298TwoAddressInstructionImpl::getSingleDef(
Register Reg,
300 MachineInstr *Ret =
nullptr;
302 if (
DefMI.getParent() != BB ||
DefMI.isDebugValue())
306 else if (Ret != &
DefMI)
314 int DefRegIdx =
MI->findRegisterDefOperandIdx(DefReg,
TRI);
317 return MI->isRegTiedToUseOperand(DefRegIdx, &TiedOpIdx);
327bool TwoAddressInstructionImpl::isRevCopyChain(
Register FromReg,
Register ToReg,
330 for (
int i = 0; i < Maxlen; i++) {
331 MachineInstr *
Def = getSingleDef(TmpReg,
MBB);
336 TmpReg =
Def->getOperand(1).getReg();
337 else if (
unsigned TiedOpIdx;
339 Register TiedUseReg =
Def->getOperand(TiedOpIdx).getReg();
342 if (TiedUseReg == TmpReg)
358bool TwoAddressInstructionImpl::noUseAfterLastDef(
Register Reg,
unsigned Dist,
361 unsigned LastUse = Dist;
363 MachineInstr *
MI = MO.getParent();
364 if (
MI->getParent() !=
MBB ||
MI->isDebugValue())
366 auto DI = DistanceMap.
find(
MI);
367 if (DI == DistanceMap.
end())
369 if (MO.isUse() && DI->second < LastUse)
370 LastUse = DI->second;
371 if (MO.isDef() && DI->second > LastDef)
372 LastDef = DI->second;
375 return !(LastUse > LastDef && LastUse < Dist);
381bool TwoAddressInstructionImpl::isCopyToReg(MachineInstr &
MI,
Register &SrcReg,
383 bool &IsDstPhys)
const {
386 if (
MI.isCopy() ||
MI.isSubregToReg()) {
387 DstReg =
MI.getOperand(0).getReg();
388 SrcReg =
MI.getOperand(1).getReg();
389 }
else if (
MI.isInsertSubreg()) {
390 DstReg =
MI.getOperand(0).getReg();
391 SrcReg =
MI.getOperand(2).getReg();
401bool TwoAddressInstructionImpl::isPlainlyKilled(
const MachineInstr *
MI,
408 LiveInterval::const_iterator
I = LR.
find(useIdx);
409 assert(
I != LR.
end() &&
"Reg must be live-in to use.");
415bool TwoAddressInstructionImpl::isPlainlyKilled(
const MachineInstr *
MI,
430 return isPlainlyKilled(MI, LIS->getRegUnit(U));
434 return MI->killsRegister(
Reg,
nullptr);
439bool TwoAddressInstructionImpl::isPlainlyKilled(
440 const MachineOperand &MO)
const {
461bool TwoAddressInstructionImpl::isKilled(MachineInstr &
MI,
Register Reg,
462 bool allowFalsePositives)
const {
475 if (std::next(Begin) != MRI->
def_end())
478 bool IsSrcPhys, IsDstPhys;
482 if (!isCopyToReg(*
DefMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
491 for (
unsigned i = 0,
NumOps =
MI.getNumOperands(); i !=
NumOps; ++i) {
496 if (
MI.isRegTiedToDefOperand(i, &ti)) {
497 DstReg =
MI.getOperand(ti).getReg();
506MachineInstr *TwoAddressInstructionImpl::findOnlyInterestingUse(
508 bool &IsDstPhys)
const {
509 MachineOperand *UseOp =
nullptr;
515 if (
MI->getParent() !=
MBB)
517 if (isPlainlyKilled(
MI,
Reg))
526 if (isCopyToReg(
UseMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
535 if (
UseMI.isCommutable()) {
538 if (
TII->findCommutedOpIndices(
UseMI, Src1, Src2)) {
539 MachineOperand &MO =
UseMI.getOperand(Src1);
554 while (
Reg.isVirtual()) {
556 if (
SI == RegMap.
end())
560 if (
Reg.isPhysical())
566bool TwoAddressInstructionImpl::regsAreCompatible(
Register RegA,
572 return TRI->regsOverlap(RegA, RegB);
576void TwoAddressInstructionImpl::removeMapRegEntry(
577 const MachineOperand &MO, DenseMap<Register, Register> &RegMap)
const {
580 "removeMapRegEntry must be called with a register or regmask operand.");
583 for (
auto SI : RegMap) {
590 if (
TRI->regsOverlap(ToReg,
Reg))
596 for (
auto SrcReg : Srcs)
597 RegMap.erase(SrcReg);
608void TwoAddressInstructionImpl::removeClobberedSrcRegMap(MachineInstr *
MI) {
621 if (!Dst || Dst.isVirtual())
625 if (regsAreCompatible(Dst,
getMappedReg(Src, SrcRegMap)))
629 for (
const MachineOperand &MO :
MI->operands()) {
631 removeMapRegEntry(MO, SrcRegMap);
639 removeMapRegEntry(MO, SrcRegMap);
644bool TwoAddressInstructionImpl::regOverlapsSet(
645 const SmallVectorImpl<Register> &Set,
Register Reg)
const {
647 if (
TRI->regsOverlap(R,
Reg))
655bool TwoAddressInstructionImpl::isProfitableToCommute(
Register RegA,
660 if (OptLevel == CodeGenOptLevel::None)
681 if (!isPlainlyKilled(
MI, RegC))
698 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA);
699 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA);
705 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
711 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
717 unsigned LastDefC = 0;
718 if (!noUseAfterLastDef(RegC, Dist, LastDefC))
723 unsigned LastDefB = 0;
724 if (!noUseAfterLastDef(RegB, Dist, LastDefB))
750 if (
TII->hasCommutePreference(*
MI, Commute))
755 return LastDefB && LastDefC && LastDefC > LastDefB;
760bool TwoAddressInstructionImpl::commuteInstruction(MachineInstr *
MI,
765 Register RegC =
MI->getOperand(RegCIdx).getReg();
767 MachineInstr *NewMI =
TII->commuteInstruction(*
MI,
false, RegBIdx, RegCIdx);
769 if (NewMI ==
nullptr) {
776 "TargetInstrInfo::commuteInstruction() should not return a new "
777 "instruction unless it was requested.");
782 Register RegA =
MI->getOperand(DstIdx).getReg();
783 SrcRegMap[RegA] = FromRegC;
791bool TwoAddressInstructionImpl::isProfitableToConv3Addr(
Register RegA,
803 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA));
808bool TwoAddressInstructionImpl::convertInstTo3Addr(
811 MachineInstrSpan MIS(mi,
MBB);
812 MachineInstr *NewMI =
TII->convertToThreeAddress(*mi, LV, LIS);
816 for (MachineInstr &
MI : MIS)
817 DistanceMap.
insert(std::make_pair(&
MI, Dist++));
820 LLVM_DEBUG(
dbgs() <<
"2addr: CONVERTED IN-PLACE TO 3-ADDR: " << *mi);
823 dbgs() <<
"2addr: CONVERTING 2-ADDR: " << *mi;
824 dbgs() <<
"2addr: TO 3-ADDR: " << *NewMI;
828 if (
auto OldInstrNum = mi->peekDebugInstrNum()) {
829 assert(mi->getNumExplicitDefs() == 1);
833 unsigned OldIdx = mi->defs().begin()->getOperandNo();
834 unsigned NewIdx = NewMI->
defs().
begin()->getOperandNo();
839 std::make_pair(NewInstrNum, NewIdx));
850 SrcRegMap.
erase(RegA);
851 DstRegMap.
erase(RegB);
857void TwoAddressInstructionImpl::scanUses(
Register DstReg) {
863 while (MachineInstr *
UseMI =
864 findOnlyInterestingUse(
Reg,
MBB, IsCopy, NewReg, IsDstPhys)) {
865 if (IsCopy && !Processed.insert(
UseMI).second)
869 if (DI != DistanceMap.
end())
877 SrcRegMap[NewReg] =
Reg;
882 if (!VirtRegPairs.
empty()) {
884 while (!VirtRegPairs.
empty()) {
886 bool isNew = DstRegMap.
insert(std::make_pair(FromReg, ToReg)).second;
888 assert(DstRegMap[FromReg] == ToReg &&
"Can't map to two dst registers!");
891 bool isNew = DstRegMap.
insert(std::make_pair(DstReg, ToReg)).second;
893 assert(DstRegMap[DstReg] == ToReg &&
"Can't map to two dst registers!");
909void TwoAddressInstructionImpl::processCopy(MachineInstr *
MI) {
910 if (Processed.count(
MI))
913 bool IsSrcPhys, IsDstPhys;
915 if (!isCopyToReg(*
MI, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
918 if (IsDstPhys && !IsSrcPhys) {
919 DstRegMap.
insert(std::make_pair(SrcReg, DstReg));
920 }
else if (!IsDstPhys && IsSrcPhys) {
921 bool isNew = SrcRegMap.
insert(std::make_pair(DstReg, SrcReg)).second;
923 assert(SrcRegMap[DstReg] == SrcReg &&
924 "Can't map to two src physical registers!");
929 Processed.insert(
MI);
935bool TwoAddressInstructionImpl::rescheduleMIBelowKill(
943 MachineInstr *
MI = &*mi;
944 auto DI = DistanceMap.
find(
MI);
945 if (DI == DistanceMap.
end())
949 MachineInstr *KillMI =
nullptr;
953 "Reg should not have empty live interval.");
956 LiveInterval::const_iterator
I = LI.
find(MBBEndIdx);
957 if (
I != LI.
end() &&
I->start < MBBEndIdx)
978 bool SeenStore =
true;
979 if (!
MI->isSafeToMove(SeenStore))
989 for (
const MachineOperand &MO :
MI->operands()) {
998 Uses.push_back(MOReg);
999 if (MOReg !=
Reg && isPlainlyKilled(MO))
1008 while (End !=
MBB->
end()) {
1010 if (End->isCopy() && regOverlapsSet(Defs, End->getOperand(1).getReg()))
1011 Defs.
push_back(End->getOperand(0).getReg());
1018 unsigned NumVisited = 0;
1021 for (MachineInstr &OtherMI :
make_range(End, KillPos)) {
1023 if (OtherMI.isDebugOrPseudoInstr())
1025 if (NumVisited > 10)
1028 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1029 OtherMI.isBranch() || OtherMI.isTerminator())
1032 for (
const MachineOperand &MO : OtherMI.operands()) {
1039 if (regOverlapsSet(
Uses, MOReg))
1042 if (!MO.
isDead() && regOverlapsSet(Defs, MOReg))
1048 if (regOverlapsSet(Defs, MOReg))
1050 bool isKill = isPlainlyKilled(MO);
1051 if (MOReg !=
Reg && ((isKill && regOverlapsSet(
Uses, MOReg)) ||
1052 regOverlapsSet(Kills, MOReg)))
1055 if (MOReg ==
Reg && !isKill)
1059 assert((MOReg !=
Reg || &OtherMI == KillMI) &&
1060 "Found multiple kills of a register in a basic block");
1066 while (Begin !=
MBB->
begin() && std::prev(Begin)->isDebugInstr())
1075 auto CopyMI =
MBBI++;
1077 if (!CopyMI->isDebugOrPseudoInstr())
1086 DistanceMap.
erase(DI);
1102bool TwoAddressInstructionImpl::isDefTooClose(
Register Reg,
unsigned Dist,
1110 if (DDI == DistanceMap.
end())
1112 unsigned DefDist = DDI->second;
1113 assert(Dist > DefDist &&
"Visited def already?");
1123bool TwoAddressInstructionImpl::rescheduleKillAboveMI(
1131 MachineInstr *
MI = &*mi;
1132 auto DI = DistanceMap.
find(
MI);
1133 if (DI == DistanceMap.
end())
1137 MachineInstr *KillMI =
nullptr;
1141 "Reg should not have empty live interval.");
1144 LiveInterval::const_iterator
I = LI.
find(MBBEndIdx);
1145 if (
I != LI.
end() &&
I->start < MBBEndIdx)
1153 if (!KillMI ||
MI == KillMI)
1161 bool IsCopySrcPhys, IsCopyDstPhys;
1166 if (!isCopyToReg(*KillMI, CopySrcReg, CopyDstReg, IsCopySrcPhys,
1170 if (CopySrcReg !=
Reg || IsCopySrcPhys || !IsCopyDstPhys)
1178 bool SeenStore =
true;
1186 for (
const MachineOperand &MO : KillMI->
operands()) {
1193 if (isDefTooClose(MOReg, DI->second,
MI))
1195 bool isKill = isPlainlyKilled(MO);
1196 if (MOReg ==
Reg && !isKill)
1198 Uses.push_back(MOReg);
1199 if (isKill && MOReg !=
Reg)
1209 unsigned NumVisited = 0;
1210 for (MachineInstr &OtherMI :
1213 if (OtherMI.isDebugOrPseudoInstr())
1215 if (NumVisited > 10)
1218 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1219 OtherMI.isBranch() || OtherMI.isTerminator())
1223 for (
const MachineOperand &MO : OtherMI.operands()) {
1230 if (regOverlapsSet(Defs, MOReg))
1234 if (regOverlapsSet(Kills, MOReg))
1237 if (&OtherMI !=
MI && MOReg ==
Reg && !isPlainlyKilled(MO))
1246 if (regOverlapsSet(
Uses, MOReg))
1248 if (MOReg.
isPhysical() && regOverlapsSet(LiveDefs, MOReg))
1257 while (InsertPos !=
MBB->
begin() && std::prev(InsertPos)->isDebugInstr())
1261 while (std::prev(From)->isDebugInstr())
1265 nmi = std::prev(InsertPos);
1266 DistanceMap.
erase(DI);
1292bool TwoAddressInstructionImpl::tryInstructionCommute(MachineInstr *
MI,
1297 if (!
MI->isCommutable())
1300 bool MadeChange =
false;
1301 Register DstOpReg =
MI->getOperand(DstOpIdx).getReg();
1302 Register BaseOpReg =
MI->getOperand(BaseOpIdx).getReg();
1303 unsigned OpsNum =
MI->getDesc().getNumOperands();
1304 unsigned OtherOpIdx =
MI->getDesc().getNumDefs();
1305 for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1310 if (OtherOpIdx == BaseOpIdx || !
MI->getOperand(OtherOpIdx).isReg() ||
1311 !
TII->findCommutedOpIndices(*
MI, BaseOpIdx, OtherOpIdx))
1314 Register OtherOpReg =
MI->getOperand(OtherOpIdx).getReg();
1315 bool AggressiveCommute =
false;
1319 bool OtherOpKilled = isKilled(*
MI, OtherOpReg,
false);
1320 bool DoCommute = !BaseOpKilled && OtherOpKilled;
1323 isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg,
MI, Dist)) {
1325 AggressiveCommute =
true;
1329 if (DoCommute && commuteInstruction(
MI, DstOpIdx, BaseOpIdx, OtherOpIdx,
1333 if (AggressiveCommute)
1340 BaseOpReg = OtherOpReg;
1341 BaseOpKilled = OtherOpKilled;
1344 OpsNum =
MI->getDesc().getNumOperands();
1357bool TwoAddressInstructionImpl::tryInstructionTransform(
1359 unsigned SrcIdx,
unsigned DstIdx,
unsigned &Dist,
bool shouldOnlyCommute) {
1360 if (OptLevel == CodeGenOptLevel::None)
1363 MachineInstr &
MI = *mi;
1364 Register regA =
MI.getOperand(DstIdx).getReg();
1365 Register regB =
MI.getOperand(SrcIdx).getReg();
1367 assert(regB.
isVirtual() &&
"cannot make instruction into two-address form");
1368 bool regBKilled = isKilled(
MI, regB,
true);
1373 bool Commuted = tryInstructionCommute(&
MI, DstIdx, SrcIdx, regBKilled, Dist);
1386 if (Commuted && !ConvertibleTo3Addr)
1389 if (shouldOnlyCommute)
1402 regB =
MI.getOperand(SrcIdx).getReg();
1403 regBKilled = isKilled(
MI, regB,
true);
1406 if (ConvertibleTo3Addr) {
1409 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1411 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
1412 ++NumConvertedTo3Addr;
1437 if (
MI.mayLoad() && !regBKilled) {
1439 unsigned LoadRegIndex;
1441 TII->getOpcodeAfterMemoryUnfold(
MI.getOpcode(),
1446 const MCInstrDesc &UnfoldMCID =
TII->get(NewOpc);
1451 TII->getRegClass(UnfoldMCID, LoadRegIndex));
1453 SmallVector<MachineInstr *, 2> NewMIs;
1454 if (!
TII->unfoldMemoryOperand(*MF,
MI,
Reg,
1461 "Unfolded a load into multiple instructions!");
1463 NewMIs[1]->addRegisterKilled(
Reg,
TRI);
1469 DistanceMap.
insert(std::make_pair(NewMIs[0], Dist++));
1470 DistanceMap.
insert(std::make_pair(NewMIs[1], Dist));
1473 <<
"2addr: NEW INST: " << *NewMIs[1]);
1476 unsigned NewDstIdx =
1477 NewMIs[1]->findRegisterDefOperandIdx(regA,
nullptr);
1478 unsigned NewSrcIdx =
1479 NewMIs[1]->findRegisterUseOperandIdx(regB,
nullptr);
1481 bool TransformResult =
1482 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist,
true);
1483 (void)TransformResult;
1484 assert(!TransformResult &&
1485 "tryInstructionTransform() should return false.");
1486 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1490 for (
const MachineOperand &MO :
MI.operands()) {
1494 if (NewMIs[0]->killsRegister(MO.
getReg(),
nullptr))
1499 "Kill missing after load unfold!");
1504 if (NewMIs[1]->registerDefIsDead(MO.
getReg(),
1510 "Dead flag missing after load unfold!");
1521 for (
const MachineOperand &MO :
MI.operands()) {
1529 MI.eraseFromParent();
1545 NewMIs[0]->eraseFromParent();
1546 NewMIs[1]->eraseFromParent();
1547 DistanceMap.
erase(NewMIs[0]);
1548 DistanceMap.
erase(NewMIs[1]);
1561bool TwoAddressInstructionImpl::collectTiedOperands(
1562 MachineInstr *
MI, TiedOperandMap &TiedOperands) {
1563 bool AnyOps =
false;
1564 unsigned NumOps =
MI->getNumOperands();
1566 for (
unsigned SrcIdx = 0; SrcIdx <
NumOps; ++SrcIdx) {
1567 unsigned DstIdx = 0;
1568 if (!
MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1571 MachineOperand &SrcMO =
MI->getOperand(SrcIdx);
1572 MachineOperand &DstMO =
MI->getOperand(DstIdx);
1576 if (SrcReg == DstReg)
1579 assert(SrcReg && SrcMO.
isUse() &&
"two address instruction invalid");
1593 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1600void TwoAddressInstructionImpl::processTiedPairs(MachineInstr *
MI,
1601 TiedPairList &TiedPairs,
1603 bool IsEarlyClobber =
llvm::any_of(TiedPairs, [
MI](
auto const &TP) {
1604 return MI->getOperand(TP.second).isEarlyClobber();
1607 bool RemovedKillFlag =
false;
1608 bool AllUsesCopied =
true;
1610 SlotIndex LastCopyIdx;
1612 unsigned SubRegB = 0;
1613 for (
auto &TP : TiedPairs) {
1614 unsigned SrcIdx = TP.first;
1615 unsigned DstIdx = TP.second;
1617 const MachineOperand &DstMO =
MI->getOperand(DstIdx);
1622 RegB =
MI->getOperand(SrcIdx).getReg();
1623 SubRegB =
MI->getOperand(SrcIdx).getSubReg();
1629 AllUsesCopied =
false;
1632 LastCopiedReg = RegA;
1634 assert(RegB.
isVirtual() &&
"cannot make instruction into two-address form");
1640 for (
unsigned i = 0; i !=
MI->getNumOperands(); ++i)
1642 !
MI->getOperand(i).isReg() ||
1643 MI->getOperand(i).getReg() != RegA);
1647 MachineInstrBuilder MIB =
BuildMI(*
MI->getParent(),
MI,
MI->getDebugLoc(),
1648 TII->get(TargetOpcode::COPY), RegA);
1651 MIB.
addReg(RegB, {}, SubRegB);
1657 "tied subregister must be a truncation");
1662 &&
"tied subregister must be a truncation");
1669 DistanceMap.
insert(std::make_pair(&*PrevMI, Dist));
1670 DistanceMap[
MI] = ++Dist;
1680 LI.
addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1683 S.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1686 for (MCRegUnit Unit :
TRI->regunits(RegA)) {
1690 LR->
addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1698 MachineOperand &MO =
MI->getOperand(SrcIdx);
1700 "inconsistent operand info for 2-reg pass");
1701 if (isPlainlyKilled(MO)) {
1703 RemovedKillFlag =
true;
1716 if (
MI->isBundle()) {
1720 "tied subregister uses in bundled instructions not supported");
1727 if (AllUsesCopied) {
1730 for (MachineOperand &MO :
MI->all_uses()) {
1731 if (MO.
getReg() == RegB) {
1732 if (MO.
getSubReg() == SubRegB && !IsEarlyClobber) {
1733 if (isPlainlyKilled(MO)) {
1735 RemovedKillFlag =
true;
1737 MO.
setReg(LastCopiedReg);
1740 RemainingUses |=
TRI->getSubRegIndexLaneMask(MO.
getSubReg());
1746 if (RemovedKillFlag && RemainingUses.
none() && LV &&
1753 if (RemovedKillFlag && RemainingUses.
none())
1754 SrcRegMap[LastCopiedReg] = RegB;
1759 auto Shrink = [=](
LiveRange &LR, LaneBitmask LaneMask) {
1763 if ((LaneMask & RemainingUses).
any())
1767 S->
end = LastCopyIdx;
1772 bool ShrinkLI =
true;
1774 ShrinkLI &= Shrink(S, S.LaneMask);
1778 }
else if (RemovedKillFlag) {
1783 for (MachineOperand &MO :
MI->all_uses()) {
1784 if (MO.
getReg() == RegB) {
1799bool TwoAddressInstructionImpl::processStatepoint(
1800 MachineInstr *
MI, TiedOperandMap &TiedOperands) {
1802 bool NeedCopy =
false;
1803 for (
auto &TO : TiedOperands) {
1805 if (TO.second.size() != 1) {
1810 unsigned SrcIdx = TO.second[0].first;
1811 unsigned DstIdx = TO.second[0].second;
1813 MachineOperand &DstMO =
MI->getOperand(DstIdx);
1816 assert(RegB ==
MI->getOperand(SrcIdx).getReg());
1829 if (DefLI.overlaps(UseLI)) {
1831 <<
" UseLI overlaps with DefLI\n");
1840 <<
" not killed by statepoint\n");
1847 <<
" to register class of " <<
printReg(RegA,
TRI, 0)
1859 for (
const VNInfo *VNI :
Other.valnos) {
1863 for (
auto &S :
Other) {
1864 VNInfo *VNI = NewVNIs[S.
valno->
id];
1865 LiveRange::Segment NewSeg(S.
start, S.
end, VNI);
1872 if (
MI->getOperand(SrcIdx).isKill())
1874 LiveVariables::VarInfo &SrcInfo = LV->
getVarInfo(RegB);
1875 LiveVariables::VarInfo &DstInfo = LV->
getVarInfo(RegA);
1878 for (
auto *KillMI : DstInfo.
Kills)
1886bool TwoAddressInstructionImpl::run() {
1887 bool MadeChange =
false;
1889 LLVM_DEBUG(
dbgs() <<
"********** REWRITING TWO-ADDR INSTRS **********\n");
1898 TiedOperandMap TiedOperands;
1899 for (MachineBasicBlock &
MBBI : *MF) {
1902 DistanceMap.
clear();
1910 if (mi->isDebugInstr()) {
1917 if (mi->isRegSequence()) {
1918 eliminateRegSequence(mi);
1922 DistanceMap.
insert(std::make_pair(&*mi, ++Dist));
1928 if (!collectTiedOperands(&*mi, TiedOperands)) {
1929 removeClobberedSrcRegMap(&*mi);
1934 ++NumTwoAddressInstrs;
1941 if (TiedOperands.size() == 1) {
1942 SmallVectorImpl<std::pair<unsigned, unsigned>> &TiedPairs
1943 = TiedOperands.begin()->second;
1944 if (TiedPairs.
size() == 1) {
1945 unsigned SrcIdx = TiedPairs[0].first;
1946 unsigned DstIdx = TiedPairs[0].second;
1947 Register SrcReg = mi->getOperand(SrcIdx).getReg();
1948 Register DstReg = mi->getOperand(DstIdx).getReg();
1949 if (SrcReg != DstReg &&
1950 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist,
false)) {
1953 TiedOperands.clear();
1954 removeClobberedSrcRegMap(&*mi);
1961 if (mi->getOpcode() == TargetOpcode::STATEPOINT &&
1962 processStatepoint(&*mi, TiedOperands)) {
1963 TiedOperands.clear();
1970 for (
auto &TO : TiedOperands) {
1971 processTiedPairs(&*mi, TO.second, Dist);
1976 if (mi->isInsertSubreg()) {
1979 unsigned SubIdx = mi->getOperand(3).getImm();
1980 mi->removeOperand(3);
1981 assert(mi->getOperand(0).getSubReg() == 0 &&
"Unexpected subreg idx");
1982 mi->getOperand(0).setSubReg(SubIdx);
1983 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1984 mi->removeOperand(1);
1985 mi->setDesc(
TII->get(TargetOpcode::COPY));
1995 LaneBitmask LaneMask =
1996 TRI->getSubRegIndexLaneMask(mi->getOperand(0).getSubReg());
1999 if ((S.LaneMask & LaneMask).none()) {
2000 LiveRange::iterator DefSeg = S.FindSegmentContaining(Idx);
2001 if (mi->getOperand(0).isUndef()) {
2002 S.removeValNo(DefSeg->valno);
2004 LiveRange::iterator UseSeg = std::prev(DefSeg);
2005 S.MergeValueNumberInto(DefSeg->valno, UseSeg->valno);
2023 TiedOperands.clear();
2024 removeClobberedSrcRegMap(&*mi);
2042void TwoAddressInstructionImpl::eliminateRegSequence(
2044 MachineInstr &
MI = *
MBBI;
2048 VNInfo *DefVN =
nullptr;
2051 for (
unsigned i = 1, e =
MI.getNumOperands(); i < e; i += 2)
2065 if (
unsigned SubReg =
Use.getSubReg())
2066 UsedLanes |=
TRI->getSubRegIndexLaneMask(SubReg);
2071 bool DefEmitted =
false;
2072 for (
unsigned i = 1, e =
MI.getNumOperands(); i < e; i += 2) {
2073 MachineOperand &UseMO =
MI.getOperand(i);
2075 unsigned SubIdx =
MI.getOperand(i+1).getImm();
2080 LaneBitmask LaneMask =
TRI->getSubRegIndexLaneMask(SubIdx);
2081 if (LIS || (UsedLanes & LaneMask).
none()) {
2082 UndefLanes |= LaneMask;
2089 bool isKill = UseMO.
isKill();
2091 for (
unsigned j = i + 2;
j <
e;
j += 2)
2092 if (
MI.getOperand(j).getReg() == SrcReg) {
2093 MI.getOperand(j).setIsKill();
2100 MachineInstr *CopyMI =
BuildMI(*
MI.getParent(),
MI,
MI.getDebugLoc(),
2101 TII->get(TargetOpcode::COPY))
2102 .
addReg(DstReg, RegState::Define, SubIdx)
2126 MI.setDesc(
TII->get(TargetOpcode::IMPLICIT_DEF));
2127 for (
int j =
MI.getNumOperands() - 1, ee = 0; j > ee; --j)
2128 MI.removeOperand(j);
2136 for (MachineOperand &UseOp : MRI->
use_operands(DstReg)) {
2138 if (UseOp.
isUndef() || !SubReg)
2144 LaneBitmask LaneMask =
TRI->getSubRegIndexLaneMask(SubReg);
2145 if ((UndefLanes & LaneMask).
any())
2154 MI.eraseFromParent();
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file defines the DenseMap class.
const HexagonInstrInfo * TII
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Remove Loads Into Fake Uses
SI Optimize VGPR LiveRange
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static bool isTwoAddrUse(MachineInstr &MI, Register Reg, Register &DstReg)
Return true if the specified MI uses the specified register as a two-address use.
static bool getTiedUse(Register DefReg, MachineInstr *MI, const TargetRegisterInfo *TRI, unsigned &TiedOpIdx)
static MCRegister getMappedReg(Register Reg, DenseMap< Register, Register > &RegMap)
Return the physical register the specified virtual register might be mapped to.
static cl::opt< bool > EnableRescheduling("twoaddr-reschedule", cl::desc("Coalesce copies by rescheduling (default=true)"), cl::init(true), cl::Hidden)
static cl::opt< bool > AnalyzeRevCopyTied("twoaddr-analyze-revcopy-tied", cl::desc("Analyze tied operands when looking for reversed copy chain"), cl::init(true), cl::Hidden)
static cl::opt< unsigned > MaxDataFlowEdge("dataflow-edge-limit", cl::Hidden, cl::init(10), cl::desc("Maximum number of dataflow edges to traverse when evaluating " "the benefit of commuting operands"))
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
AnalysisUsage & addPreservedID(const void *ID)
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Represents analyses that only rely on functions' control flow.
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
bool hasOptNone() const
Do not optimize this function (-O0).
unsigned getInstrLatency(const InstrItineraryData *ItinData, const MachineInstr &MI, unsigned *PredCost=nullptr) const override
Compute the instruction latency of a given instruction.
Itinerary data supplied by a subtarget to be used by a target.
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
LLVM_ABI void repairIntervalsInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, ArrayRef< Register > OrigRegs)
Update live intervals for instructions in a range of iterators.
bool hasInterval(Register Reg) const
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LLVM_ABI void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
VNInfo::Allocator & getVNInfoAllocator()
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
void removeInterval(Register Reg)
Interval removal.
bool isNotInMIMap(const MachineInstr &Instr) const
Returns true if the specified machine instr has been removed or was never entered in the map.
LiveRange * getCachedRegUnit(MCRegUnit Unit)
Return the live range for register unit Unit if it has already been computed, or nullptr if it hasn't...
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses.
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
VNInfo * valueOut() const
Return the value leaving the instruction, if any.
This class represents the liveness of a register, stack slot, etc.
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
VNInfo * createValueCopy(const VNInfo *orig, VNInfo::Allocator &VNInfoAllocator)
Create a copy of the given value.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
bool hasAtLeastOneValue() const
VNInfo * getNextValue(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
LLVM_ABI iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
LLVM_ABI void replaceKillInstruction(Register Reg, MachineInstr &OldMI, MachineInstr &NewMI)
replaceKillInstruction - Update register kill info by replacing a kill instruction with a new one.
bool removeVirtualRegisterDead(Register Reg, MachineInstr &MI)
removeVirtualRegisterDead - Remove the specified kill of the virtual register from the live variable ...
bool removeVirtualRegisterKilled(Register Reg, MachineInstr &MI)
removeVirtualRegisterKilled - Remove the specified kill of the virtual register from the live variabl...
void addVirtualRegisterDead(Register IncomingReg, MachineInstr &MI, bool AddIfNotFound=false)
addVirtualRegisterDead - Add information about the fact that the specified register is dead after bei...
void addVirtualRegisterKilled(Register IncomingReg, MachineInstr &MI, bool AddIfNotFound=false)
addVirtualRegisterKilled - Add information about the fact that the specified register is killed after...
LLVM_ABI VarInfo & getVarInfo(Register Reg)
getVarInfo - Return the VarInfo structure for the specified VIRTUAL register.
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
Wrapper class representing physical registers. Should be passed by value.
An RAII based helper class to modify MachineFunctionProperties when running pass.
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
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 '...
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void makeDebugValueSubstitution(DebugInstrOperandPair, DebugInstrOperandPair, unsigned SubReg=0)
Create a substitution between one <instr,operand> value to a different, new value.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
Representation of each machine instruction.
mop_range defs()
Returns all explicit operands that are register definitions.
bool isTerminator(QueryType Type=AnyInBundle) const
Returns true if this instruction part of the terminator for a basic block.
bool isCopyLike() const
Return true if the instruction behaves like a copy.
bool isCall(QueryType Type=AnyInBundle) const
LLVM_ABI bool isSafeToMove(bool &SawStore) const
Return true if it is safe to move this instruction.
bool isBranch(QueryType Type=AnyInBundle) const
Returns true if this is a conditional, unconditional, or indirect branch.
LLVM_ABI bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore,...
LLVM_ABI unsigned getNumExplicitDefs() const
Returns the number of non-implicit definitions.
LLVM_ABI unsigned getDebugInstrNum()
Fetch the instruction number of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator_range< reg_iterator > reg_operands(Register Reg) const
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< def_instr_iterator > def_instructions(Register Reg) const
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
def_iterator def_begin(Register RegNo) const
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
bool hasOneUse(Register RegNo) const
hasOneUse - Return true if there is exactly one instruction using the specified register.
bool shouldTrackSubRegLiveness(const TargetRegisterClass &RC) const
Returns true if liveness for register class RC should be tracked at the subregister level.
defusechain_iterator< false, true, false, true, false > def_iterator
def_iterator/def_begin/def_end - Walk all defs of the specified register.
static def_iterator def_end()
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
iterator_range< use_iterator > use_operands(Register Reg) const
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Wrapper class representing virtual and physical registers.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
static const unsigned CommuteAnyOperandIndex
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
BumpPtrAllocator Allocator
unsigned id
The ID number of this value.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
constexpr bool any(E Val)
initializer< Ty > init(const Ty &Val)
DXILDebugInfoMap run(Module &M)
NodeAddr< DefNode * > Def
NodeAddr< UseNode * > Use
NodeAddr< FuncNode * > Func
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
LLVM_ABI char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
IterT skipDebugInstructionsForward(IterT It, IterT End, bool SkipPseudoOp=true)
Increment It until it points to a non-debug instruction or to End and return the resulting iterator.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
LLVM_ABI char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
CodeGenOptLevel
Code generation optimization level.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
iterator_range< MIBundleOperands > mi_bundle_ops(MachineInstr &MI)
LLVM_ABI char & TwoAddressInstructionPassID
TwoAddressInstruction - This pass reduces two-address instructions to use two operands.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
MCRegisterClass TargetRegisterClass
static constexpr LaneBitmask getAll()
constexpr bool none() const
constexpr bool any() const
static constexpr LaneBitmask getNone()
bool removeKill(MachineInstr &MI)
removeKill - Delete a kill corresponding to the specified machine instruction.
std::vector< MachineInstr * > Kills
Kills - List of MachineInstruction's which are the last use of this virtual register (kill it) in the...
SparseBitVector AliveBlocks
AliveBlocks - Set of blocks in which this value is alive completely through.
LLVM_ABI MachineInstr * findKill(const MachineBasicBlock *MBB) const
findKill - Find a kill instruction in MBB. Return NULL if none is found.