68#define DEBUG_TYPE "twoaddressinstruction"
70STATISTIC(NumTwoAddressInstrs,
"Number of two-address instructions");
71STATISTIC(NumCommuted ,
"Number of instructions commuted to coalesce");
72STATISTIC(NumAggrCommuted ,
"Number of instructions aggressively commuted");
73STATISTIC(NumConvertedTo3Addr,
"Number of instructions promoted to 3-address");
74STATISTIC(NumReSchedUps,
"Number of instructions re-scheduled up");
75STATISTIC(NumReSchedDowns,
"Number of instructions re-scheduled down");
80 cl::desc(
"Coalesce copies by rescheduling (default=true)"),
87 cl::desc(
"Maximum number of dataflow edges to traverse when evaluating "
88 "the benefit of commuting operands"));
92class TwoAddressInstructionImpl {
125 bool noUseAfterLastDef(
Register Reg,
unsigned Dist,
unsigned &LastDef);
128 bool &IsSrcPhys,
bool &IsDstPhys)
const;
138 bool &IsDstPhys)
const;
153 unsigned RegBIdx,
unsigned RegCIdx,
unsigned Dist);
170 unsigned SrcIdx,
unsigned DstIdx,
171 unsigned &Dist,
bool shouldOnlyCommute);
186 void processTiedPairs(
MachineInstr *
MI, TiedPairList&,
unsigned &Dist);
188 bool processStatepoint(
MachineInstr *
MI, TiedOperandMap &TiedOperands);
202 TwoAddressInstructionLegacyPass() : MachineFunctionPass(ID) {
208 bool runOnMachineFunction(MachineFunction &MF)
override {
209 TwoAddressInstructionImpl Impl(MF,
this);
213 Impl.setOptLevel(CodeGenOptLevel::None);
217 void getAnalysisUsage(AnalysisUsage &AU)
const override {
236 TwoAddressInstructionImpl Impl(MF, MFAM);
254char TwoAddressInstructionLegacyPass::ID = 0;
259 "Two-Address instruction pass",
false,
false)
261TwoAddressInstructionImpl::TwoAddressInstructionImpl(
263 : MF(&Func),
TII(Func.getSubtarget().getInstrInfo()),
264 TRI(Func.getSubtarget().getRegisterInfo()),
265 InstrItins(Func.getSubtarget().getInstrItineraryData()),
266 MRI(&Func.getRegInfo()),
269 OptLevel(Func.getTarget().getOptLevel()) {}
271TwoAddressInstructionImpl::TwoAddressInstructionImpl(
MachineFunction &Func,
273 : MF(&
Func),
TII(
Func.getSubtarget().getInstrInfo()),
274 TRI(
Func.getSubtarget().getRegisterInfo()),
275 InstrItins(
Func.getSubtarget().getInstrItineraryData()),
276 MRI(&
Func.getRegInfo()), OptLevel(
Func.getTarget().getOptLevel()) {
278 LV = LVWrapper ? &LVWrapper->
getLV() :
nullptr;
280 LIS = LISWrapper ? &LISWrapper->
getLIS() :
nullptr;
285TwoAddressInstructionImpl::getSingleDef(
Register Reg,
287 MachineInstr *Ret =
nullptr;
288 for (MachineInstr &
DefMI :
MRI->def_instructions(
Reg)) {
289 if (
DefMI.getParent() != BB ||
DefMI.isDebugValue())
293 else if (Ret != &
DefMI)
306bool TwoAddressInstructionImpl::isRevCopyChain(
Register FromReg,
Register ToReg,
309 for (
int i = 0; i < Maxlen; i++) {
310 MachineInstr *
Def = getSingleDef(TmpReg,
MBB);
311 if (!Def || !
Def->isCopy())
314 TmpReg =
Def->getOperand(1).getReg();
326bool TwoAddressInstructionImpl::noUseAfterLastDef(
Register Reg,
unsigned Dist,
329 unsigned LastUse = Dist;
330 for (MachineOperand &MO :
MRI->reg_operands(
Reg)) {
331 MachineInstr *
MI = MO.getParent();
332 if (
MI->getParent() !=
MBB ||
MI->isDebugValue())
334 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.
find(
MI);
335 if (DI == DistanceMap.
end())
337 if (MO.isUse() && DI->second < LastUse)
338 LastUse = DI->second;
339 if (MO.isDef() && DI->second > LastDef)
340 LastDef = DI->second;
343 return !(LastUse > LastDef && LastUse < Dist);
349bool TwoAddressInstructionImpl::isCopyToReg(MachineInstr &
MI,
Register &SrcReg,
351 bool &IsDstPhys)
const {
355 DstReg =
MI.getOperand(0).getReg();
356 SrcReg =
MI.getOperand(1).getReg();
357 }
else if (
MI.isInsertSubreg() ||
MI.isSubregToReg()) {
358 DstReg =
MI.getOperand(0).getReg();
359 SrcReg =
MI.getOperand(2).getReg();
369bool TwoAddressInstructionImpl::isPlainlyKilled(
const MachineInstr *
MI,
376 LiveInterval::const_iterator
I = LR.
find(useIdx);
377 assert(
I != LR.
end() &&
"Reg must be live-in to use.");
383bool TwoAddressInstructionImpl::isPlainlyKilled(
const MachineInstr *
MI,
398 return isPlainlyKilled(MI, LIS->getRegUnit(U));
402 return MI->killsRegister(
Reg,
nullptr);
407bool TwoAddressInstructionImpl::isPlainlyKilled(
408 const MachineOperand &MO)
const {
429bool TwoAddressInstructionImpl::isKilled(MachineInstr &
MI,
Register Reg,
430 bool allowFalsePositives)
const {
443 if (std::next(Begin) !=
MRI->def_end())
446 bool IsSrcPhys, IsDstPhys;
450 if (!isCopyToReg(*
DefMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
459 for (
unsigned i = 0,
NumOps =
MI.getNumOperands(); i !=
NumOps; ++i) {
464 if (
MI.isRegTiedToDefOperand(i, &ti)) {
465 DstReg =
MI.getOperand(ti).getReg();
474MachineInstr *TwoAddressInstructionImpl::findOnlyInterestingUse(
476 bool &IsDstPhys)
const {
477 MachineOperand *UseOp =
nullptr;
478 for (MachineOperand &MO :
MRI->use_nodbg_operands(
Reg)) {
483 if (
MI->getParent() !=
MBB)
485 if (isPlainlyKilled(
MI,
Reg))
494 if (isCopyToReg(
UseMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
503 if (
UseMI.isCommutable()) {
506 if (
TII->findCommutedOpIndices(
UseMI, Src1, Src2)) {
507 MachineOperand &MO =
UseMI.getOperand(Src1);
522 while (
Reg.isVirtual()) {
524 if (
SI == RegMap.
end())
528 if (
Reg.isPhysical())
534bool TwoAddressInstructionImpl::regsAreCompatible(
Register RegA,
540 return TRI->regsOverlap(RegA, RegB);
544void TwoAddressInstructionImpl::removeMapRegEntry(
545 const MachineOperand &MO, DenseMap<Register, Register> &RegMap)
const {
548 "removeMapRegEntry must be called with a register or regmask operand.");
551 for (
auto SI : RegMap) {
558 if (
TRI->regsOverlap(ToReg,
Reg))
564 for (
auto SrcReg : Srcs)
565 RegMap.erase(SrcReg);
576void TwoAddressInstructionImpl::removeClobberedSrcRegMap(MachineInstr *
MI) {
589 if (!Dst || Dst.isVirtual())
593 if (regsAreCompatible(Dst,
getMappedReg(Src, SrcRegMap)))
597 for (
const MachineOperand &MO :
MI->operands()) {
599 removeMapRegEntry(MO, SrcRegMap);
607 removeMapRegEntry(MO, SrcRegMap);
612bool TwoAddressInstructionImpl::regOverlapsSet(
613 const SmallVectorImpl<Register> &Set,
Register Reg)
const {
615 if (
TRI->regsOverlap(R,
Reg))
623bool TwoAddressInstructionImpl::isProfitableToCommute(
Register RegA,
628 if (OptLevel == CodeGenOptLevel::None)
649 if (!isPlainlyKilled(
MI, RegC))
666 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA);
667 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA);
673 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
679 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
685 unsigned LastDefC = 0;
686 if (!noUseAfterLastDef(RegC, Dist, LastDefC))
691 unsigned LastDefB = 0;
692 if (!noUseAfterLastDef(RegB, Dist, LastDefB))
718 if (
TII->hasCommutePreference(*
MI, Commute))
723 return LastDefB && LastDefC && LastDefC > LastDefB;
728bool TwoAddressInstructionImpl::commuteInstruction(MachineInstr *
MI,
733 Register RegC =
MI->getOperand(RegCIdx).getReg();
735 MachineInstr *NewMI =
TII->commuteInstruction(*
MI,
false, RegBIdx, RegCIdx);
737 if (NewMI ==
nullptr) {
744 "TargetInstrInfo::commuteInstruction() should not return a new "
745 "instruction unless it was requested.");
750 Register RegA =
MI->getOperand(DstIdx).getReg();
751 SrcRegMap[RegA] = FromRegC;
759bool TwoAddressInstructionImpl::isProfitableToConv3Addr(
Register RegA,
771 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA));
776bool TwoAddressInstructionImpl::convertInstTo3Addr(
779 MachineInstrSpan MIS(mi,
MBB);
780 MachineInstr *NewMI =
TII->convertToThreeAddress(*mi, LV, LIS);
784 for (MachineInstr &
MI : MIS)
785 DistanceMap.
insert(std::make_pair(&
MI, Dist++));
788 LLVM_DEBUG(
dbgs() <<
"2addr: CONVERTED IN-PLACE TO 3-ADDR: " << *mi);
791 dbgs() <<
"2addr: CONVERTING 2-ADDR: " << *mi;
792 dbgs() <<
"2addr: TO 3-ADDR: " << *NewMI;
796 if (
auto OldInstrNum = mi->peekDebugInstrNum()) {
797 assert(mi->getNumExplicitDefs() == 1);
801 unsigned OldIdx = mi->defs().begin()->getOperandNo();
802 unsigned NewIdx = NewMI->
defs().
begin()->getOperandNo();
807 std::make_pair(NewInstrNum, NewIdx));
818 SrcRegMap.
erase(RegA);
819 DstRegMap.
erase(RegB);
825void TwoAddressInstructionImpl::scanUses(
Register DstReg) {
831 while (MachineInstr *
UseMI =
832 findOnlyInterestingUse(
Reg,
MBB, IsCopy, NewReg, IsDstPhys)) {
833 if (IsCopy && !Processed.insert(
UseMI).second)
836 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.
find(
UseMI);
837 if (DI != DistanceMap.
end())
845 SrcRegMap[NewReg] =
Reg;
850 if (!VirtRegPairs.
empty()) {
852 while (!VirtRegPairs.
empty()) {
854 bool isNew = DstRegMap.
insert(std::make_pair(FromReg, ToReg)).second;
856 assert(DstRegMap[FromReg] == ToReg &&
"Can't map to two dst registers!");
859 bool isNew = DstRegMap.
insert(std::make_pair(DstReg, ToReg)).second;
861 assert(DstRegMap[DstReg] == ToReg &&
"Can't map to two dst registers!");
877void TwoAddressInstructionImpl::processCopy(MachineInstr *
MI) {
878 if (Processed.count(
MI))
881 bool IsSrcPhys, IsDstPhys;
883 if (!isCopyToReg(*
MI, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
886 if (IsDstPhys && !IsSrcPhys) {
887 DstRegMap.
insert(std::make_pair(SrcReg, DstReg));
888 }
else if (!IsDstPhys && IsSrcPhys) {
889 bool isNew = SrcRegMap.
insert(std::make_pair(DstReg, SrcReg)).second;
891 assert(SrcRegMap[DstReg] == SrcReg &&
892 "Can't map to two src physical registers!");
897 Processed.insert(
MI);
903bool TwoAddressInstructionImpl::rescheduleMIBelowKill(
911 MachineInstr *
MI = &*mi;
912 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.
find(
MI);
913 if (DI == DistanceMap.
end())
917 MachineInstr *KillMI =
nullptr;
921 "Reg should not have empty live interval.");
924 LiveInterval::const_iterator
I = LI.
find(MBBEndIdx);
925 if (
I != LI.
end() &&
I->start < MBBEndIdx)
946 bool SeenStore =
true;
947 if (!
MI->isSafeToMove(SeenStore))
957 for (
const MachineOperand &MO :
MI->operands()) {
966 Uses.push_back(MOReg);
967 if (MOReg !=
Reg && isPlainlyKilled(MO))
976 while (End !=
MBB->
end()) {
978 if (End->isCopy() && regOverlapsSet(Defs, End->getOperand(1).getReg()))
979 Defs.
push_back(End->getOperand(0).getReg());
986 unsigned NumVisited = 0;
989 for (MachineInstr &OtherMI :
make_range(End, KillPos)) {
991 if (OtherMI.isDebugOrPseudoInstr())
996 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
997 OtherMI.isBranch() || OtherMI.isTerminator())
1000 for (
const MachineOperand &MO : OtherMI.operands()) {
1007 if (regOverlapsSet(
Uses, MOReg))
1010 if (!MO.
isDead() && regOverlapsSet(Defs, MOReg))
1016 if (regOverlapsSet(Defs, MOReg))
1018 bool isKill = isPlainlyKilled(MO);
1019 if (MOReg !=
Reg && ((isKill && regOverlapsSet(
Uses, MOReg)) ||
1020 regOverlapsSet(Kills, MOReg)))
1023 if (MOReg ==
Reg && !isKill)
1027 assert((MOReg !=
Reg || &OtherMI == KillMI) &&
1028 "Found multiple kills of a register in a basic block");
1034 while (Begin !=
MBB->
begin() && std::prev(Begin)->isDebugInstr())
1043 auto CopyMI =
MBBI++;
1045 if (!CopyMI->isDebugOrPseudoInstr())
1054 DistanceMap.
erase(DI);
1070bool TwoAddressInstructionImpl::isDefTooClose(
Register Reg,
unsigned Dist,
1072 for (MachineInstr &
DefMI :
MRI->def_instructions(
Reg)) {
1077 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.
find(&
DefMI);
1078 if (DDI == DistanceMap.
end())
1080 unsigned DefDist = DDI->second;
1081 assert(Dist > DefDist &&
"Visited def already?");
1091bool TwoAddressInstructionImpl::rescheduleKillAboveMI(
1099 MachineInstr *
MI = &*mi;
1100 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.
find(
MI);
1101 if (DI == DistanceMap.
end())
1105 MachineInstr *KillMI =
nullptr;
1109 "Reg should not have empty live interval.");
1112 LiveInterval::const_iterator
I = LI.
find(MBBEndIdx);
1113 if (
I != LI.
end() &&
I->start < MBBEndIdx)
1129 bool SeenStore =
true;
1137 for (
const MachineOperand &MO : KillMI->
operands()) {
1144 if (isDefTooClose(MOReg, DI->second,
MI))
1146 bool isKill = isPlainlyKilled(MO);
1147 if (MOReg ==
Reg && !isKill)
1149 Uses.push_back(MOReg);
1150 if (isKill && MOReg !=
Reg)
1160 unsigned NumVisited = 0;
1161 for (MachineInstr &OtherMI :
1164 if (OtherMI.isDebugOrPseudoInstr())
1166 if (NumVisited > 10)
1169 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1170 OtherMI.isBranch() || OtherMI.isTerminator())
1174 for (
const MachineOperand &MO : OtherMI.operands()) {
1181 if (regOverlapsSet(Defs, MOReg))
1185 if (regOverlapsSet(Kills, MOReg))
1188 if (&OtherMI !=
MI && MOReg ==
Reg && !isPlainlyKilled(MO))
1197 if (regOverlapsSet(
Uses, MOReg))
1199 if (MOReg.
isPhysical() && regOverlapsSet(LiveDefs, MOReg))
1208 while (InsertPos !=
MBB->
begin() && std::prev(InsertPos)->isDebugInstr())
1212 while (std::prev(From)->isDebugInstr())
1216 nmi = std::prev(InsertPos);
1217 DistanceMap.
erase(DI);
1243bool TwoAddressInstructionImpl::tryInstructionCommute(MachineInstr *
MI,
1248 if (!
MI->isCommutable())
1251 bool MadeChange =
false;
1252 Register DstOpReg =
MI->getOperand(DstOpIdx).getReg();
1253 Register BaseOpReg =
MI->getOperand(BaseOpIdx).getReg();
1254 unsigned OpsNum =
MI->getDesc().getNumOperands();
1255 unsigned OtherOpIdx =
MI->getDesc().getNumDefs();
1256 for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1261 if (OtherOpIdx == BaseOpIdx || !
MI->getOperand(OtherOpIdx).isReg() ||
1262 !
TII->findCommutedOpIndices(*
MI, BaseOpIdx, OtherOpIdx))
1265 Register OtherOpReg =
MI->getOperand(OtherOpIdx).getReg();
1266 bool AggressiveCommute =
false;
1270 bool OtherOpKilled = isKilled(*
MI, OtherOpReg,
false);
1271 bool DoCommute = !BaseOpKilled && OtherOpKilled;
1274 isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg,
MI, Dist)) {
1276 AggressiveCommute =
true;
1280 if (DoCommute && commuteInstruction(
MI, DstOpIdx, BaseOpIdx, OtherOpIdx,
1284 if (AggressiveCommute)
1291 BaseOpReg = OtherOpReg;
1292 BaseOpKilled = OtherOpKilled;
1295 OpsNum =
MI->getDesc().getNumOperands();
1308bool TwoAddressInstructionImpl::tryInstructionTransform(
1310 unsigned SrcIdx,
unsigned DstIdx,
unsigned &Dist,
bool shouldOnlyCommute) {
1311 if (OptLevel == CodeGenOptLevel::None)
1314 MachineInstr &
MI = *mi;
1315 Register regA =
MI.getOperand(DstIdx).getReg();
1316 Register regB =
MI.getOperand(SrcIdx).getReg();
1318 assert(regB.
isVirtual() &&
"cannot make instruction into two-address form");
1319 bool regBKilled = isKilled(
MI, regB,
true);
1324 bool Commuted = tryInstructionCommute(&
MI, DstIdx, SrcIdx, regBKilled, Dist);
1337 if (Commuted && !ConvertibleTo3Addr)
1340 if (shouldOnlyCommute)
1353 regB =
MI.getOperand(SrcIdx).getReg();
1354 regBKilled = isKilled(
MI, regB,
true);
1357 if (ConvertibleTo3Addr) {
1360 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1362 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
1363 ++NumConvertedTo3Addr;
1388 if (
MI.mayLoad() && !regBKilled) {
1390 unsigned LoadRegIndex;
1392 TII->getOpcodeAfterMemoryUnfold(
MI.getOpcode(),
1397 const MCInstrDesc &UnfoldMCID =
TII->get(NewOpc);
1401 const TargetRegisterClass *RC =
TRI->getAllocatableClass(
1402 TII->getRegClass(UnfoldMCID, LoadRegIndex));
1404 SmallVector<MachineInstr *, 2> NewMIs;
1405 if (!
TII->unfoldMemoryOperand(*MF,
MI,
Reg,
1412 "Unfolded a load into multiple instructions!");
1414 NewMIs[1]->addRegisterKilled(
Reg,
TRI);
1420 DistanceMap.
insert(std::make_pair(NewMIs[0], Dist++));
1421 DistanceMap.
insert(std::make_pair(NewMIs[1], Dist));
1424 <<
"2addr: NEW INST: " << *NewMIs[1]);
1427 unsigned NewDstIdx =
1428 NewMIs[1]->findRegisterDefOperandIdx(regA,
nullptr);
1429 unsigned NewSrcIdx =
1430 NewMIs[1]->findRegisterUseOperandIdx(regB,
nullptr);
1432 bool TransformResult =
1433 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist,
true);
1434 (void)TransformResult;
1435 assert(!TransformResult &&
1436 "tryInstructionTransform() should return false.");
1437 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1441 for (
const MachineOperand &MO :
MI.operands()) {
1445 if (NewMIs[0]->killsRegister(MO.
getReg(),
nullptr))
1450 "Kill missing after load unfold!");
1455 if (NewMIs[1]->registerDefIsDead(MO.
getReg(),
1461 "Dead flag missing after load unfold!");
1472 for (
const MachineOperand &MO :
MI.operands()) {
1480 MI.eraseFromParent();
1496 NewMIs[0]->eraseFromParent();
1497 NewMIs[1]->eraseFromParent();
1498 DistanceMap.
erase(NewMIs[0]);
1499 DistanceMap.
erase(NewMIs[1]);
1512bool TwoAddressInstructionImpl::collectTiedOperands(
1513 MachineInstr *
MI, TiedOperandMap &TiedOperands) {
1514 bool AnyOps =
false;
1515 unsigned NumOps =
MI->getNumOperands();
1517 for (
unsigned SrcIdx = 0; SrcIdx <
NumOps; ++SrcIdx) {
1518 unsigned DstIdx = 0;
1519 if (!
MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1522 MachineOperand &SrcMO =
MI->getOperand(SrcIdx);
1523 MachineOperand &DstMO =
MI->getOperand(DstIdx);
1527 if (SrcReg == DstReg)
1530 assert(SrcReg && SrcMO.
isUse() &&
"two address instruction invalid");
1536 const TargetRegisterClass *RC =
MRI->getRegClass(SrcReg);
1537 MRI->constrainRegClass(DstReg, RC);
1544 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1551void TwoAddressInstructionImpl::processTiedPairs(MachineInstr *
MI,
1552 TiedPairList &TiedPairs,
1554 bool IsEarlyClobber =
llvm::any_of(TiedPairs, [
MI](
auto const &TP) {
1555 return MI->getOperand(TP.second).isEarlyClobber();
1558 bool RemovedKillFlag =
false;
1559 bool AllUsesCopied =
true;
1561 SlotIndex LastCopyIdx;
1563 unsigned SubRegB = 0;
1564 for (
auto &TP : TiedPairs) {
1565 unsigned SrcIdx = TP.first;
1566 unsigned DstIdx = TP.second;
1568 const MachineOperand &DstMO =
MI->getOperand(DstIdx);
1573 RegB =
MI->getOperand(SrcIdx).getReg();
1574 SubRegB =
MI->getOperand(SrcIdx).getSubReg();
1580 AllUsesCopied =
false;
1583 LastCopiedReg = RegA;
1585 assert(RegB.
isVirtual() &&
"cannot make instruction into two-address form");
1591 for (
unsigned i = 0; i !=
MI->getNumOperands(); ++i)
1593 !
MI->getOperand(i).isReg() ||
1594 MI->getOperand(i).getReg() != RegA);
1598 MachineInstrBuilder MIB =
BuildMI(*
MI->getParent(),
MI,
MI->getDebugLoc(),
1599 TII->get(TargetOpcode::COPY), RegA);
1602 MIB.
addReg(RegB, 0, SubRegB);
1603 const TargetRegisterClass *RC =
MRI->getRegClass(RegB);
1606 assert(
TRI->getMatchingSuperRegClass(RC,
MRI->getRegClass(RegA),
1608 "tied subregister must be a truncation");
1612 assert(
TRI->getMatchingSuperReg(RegA, SubRegB,
MRI->getRegClass(RegB))
1613 &&
"tied subregister must be a truncation");
1620 DistanceMap.
insert(std::make_pair(&*PrevMI, Dist));
1621 DistanceMap[
MI] = ++Dist;
1631 LI.
addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1634 S.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1637 for (MCRegUnit Unit :
TRI->regunits(RegA)) {
1641 LR->
addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1649 MachineOperand &MO =
MI->getOperand(SrcIdx);
1651 "inconsistent operand info for 2-reg pass");
1652 if (isPlainlyKilled(MO)) {
1654 RemovedKillFlag =
true;
1659 MRI->constrainRegClass(RegA, RC);
1667 if (
MI->isBundle()) {
1671 "tied subregister uses in bundled instructions not supported");
1678 if (AllUsesCopied) {
1681 for (MachineOperand &MO :
MI->all_uses()) {
1682 if (MO.
getReg() == RegB) {
1683 if (MO.
getSubReg() == SubRegB && !IsEarlyClobber) {
1684 if (isPlainlyKilled(MO)) {
1686 RemovedKillFlag =
true;
1688 MO.
setReg(LastCopiedReg);
1691 RemainingUses |=
TRI->getSubRegIndexLaneMask(MO.
getSubReg());
1697 if (RemovedKillFlag && RemainingUses.
none() && LV &&
1704 if (RemovedKillFlag && RemainingUses.
none())
1705 SrcRegMap[LastCopiedReg] = RegB;
1710 auto Shrink = [=](
LiveRange &LR, LaneBitmask LaneMask) {
1714 if ((LaneMask & RemainingUses).
any())
1718 S->
end = LastCopyIdx;
1723 bool ShrinkLI =
true;
1725 ShrinkLI &= Shrink(S, S.LaneMask);
1729 }
else if (RemovedKillFlag) {
1734 for (MachineOperand &MO :
MI->all_uses()) {
1735 if (MO.
getReg() == RegB) {
1750bool TwoAddressInstructionImpl::processStatepoint(
1751 MachineInstr *
MI, TiedOperandMap &TiedOperands) {
1753 bool NeedCopy =
false;
1754 for (
auto &TO : TiedOperands) {
1756 if (TO.second.size() != 1) {
1761 unsigned SrcIdx = TO.second[0].first;
1762 unsigned DstIdx = TO.second[0].second;
1764 MachineOperand &DstMO =
MI->getOperand(DstIdx);
1767 assert(RegB ==
MI->getOperand(SrcIdx).getReg());
1780 if (DefLI.overlaps(UseLI)) {
1782 <<
" UseLI overlaps with DefLI\n");
1791 <<
" not killed by statepoint\n");
1796 if (!
MRI->constrainRegClass(RegB,
MRI->getRegClass(RegA))) {
1798 <<
" to register class of " <<
printReg(RegA,
TRI, 0)
1803 MRI->replaceRegWith(RegA, RegB);
1810 for (
const VNInfo *VNI :
Other.valnos) {
1814 for (
auto &S :
Other) {
1815 VNInfo *VNI = NewVNIs[S.
valno->
id];
1816 LiveRange::Segment NewSeg(S.
start, S.
end, VNI);
1823 if (
MI->getOperand(SrcIdx).isKill())
1825 LiveVariables::VarInfo &SrcInfo = LV->
getVarInfo(RegB);
1826 LiveVariables::VarInfo &DstInfo = LV->
getVarInfo(RegA);
1829 for (
auto *KillMI : DstInfo.
Kills)
1837bool TwoAddressInstructionImpl::run() {
1838 bool MadeChange =
false;
1840 LLVM_DEBUG(
dbgs() <<
"********** REWRITING TWO-ADDR INSTRS **********\n");
1849 TiedOperandMap TiedOperands;
1850 for (MachineBasicBlock &
MBBI : *MF) {
1853 DistanceMap.
clear();
1861 if (mi->isDebugInstr()) {
1868 if (mi->isRegSequence())
1869 eliminateRegSequence(mi);
1871 DistanceMap.
insert(std::make_pair(&*mi, ++Dist));
1877 if (!collectTiedOperands(&*mi, TiedOperands)) {
1878 removeClobberedSrcRegMap(&*mi);
1883 ++NumTwoAddressInstrs;
1890 if (TiedOperands.size() == 1) {
1891 SmallVectorImpl<std::pair<unsigned, unsigned>> &TiedPairs
1892 = TiedOperands.begin()->second;
1893 if (TiedPairs.
size() == 1) {
1894 unsigned SrcIdx = TiedPairs[0].first;
1895 unsigned DstIdx = TiedPairs[0].second;
1896 Register SrcReg = mi->getOperand(SrcIdx).getReg();
1897 Register DstReg = mi->getOperand(DstIdx).getReg();
1898 if (SrcReg != DstReg &&
1899 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist,
false)) {
1902 TiedOperands.clear();
1903 removeClobberedSrcRegMap(&*mi);
1910 if (mi->getOpcode() == TargetOpcode::STATEPOINT &&
1911 processStatepoint(&*mi, TiedOperands)) {
1912 TiedOperands.clear();
1919 for (
auto &TO : TiedOperands) {
1920 processTiedPairs(&*mi, TO.second, Dist);
1925 if (mi->isInsertSubreg()) {
1928 unsigned SubIdx = mi->getOperand(3).getImm();
1929 mi->removeOperand(3);
1930 assert(mi->getOperand(0).getSubReg() == 0 &&
"Unexpected subreg idx");
1931 mi->getOperand(0).setSubReg(SubIdx);
1932 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1933 mi->removeOperand(1);
1934 mi->setDesc(
TII->get(TargetOpcode::COPY));
1944 LaneBitmask LaneMask =
1945 TRI->getSubRegIndexLaneMask(mi->getOperand(0).getSubReg());
1948 if ((S.LaneMask & LaneMask).none()) {
1949 LiveRange::iterator DefSeg = S.FindSegmentContaining(Idx);
1950 if (mi->getOperand(0).isUndef()) {
1951 S.removeValNo(DefSeg->valno);
1953 LiveRange::iterator UseSeg = std::prev(DefSeg);
1954 S.MergeValueNumberInto(DefSeg->valno, UseSeg->valno);
1972 TiedOperands.clear();
1973 removeClobberedSrcRegMap(&*mi);
1991void TwoAddressInstructionImpl::eliminateRegSequence(
1993 MachineInstr &
MI = *
MBBI;
1997 VNInfo *DefVN =
nullptr;
2000 for (
unsigned i = 1, e =
MI.getNumOperands(); i < e; i += 2)
2010 bool DefEmitted =
false;
2011 for (
unsigned i = 1, e =
MI.getNumOperands(); i < e; i += 2) {
2012 MachineOperand &UseMO =
MI.getOperand(i);
2014 unsigned SubIdx =
MI.getOperand(i+1).getImm();
2017 UndefLanes |=
TRI->getSubRegIndexLaneMask(SubIdx);
2023 bool isKill = UseMO.
isKill();
2025 for (
unsigned j = i + 2;
j <
e;
j += 2)
2026 if (
MI.getOperand(j).getReg() == SrcReg) {
2027 MI.getOperand(j).setIsKill();
2034 MachineInstr *CopyMI =
BuildMI(*
MI.getParent(),
MI,
MI.getDebugLoc(),
2035 TII->get(TargetOpcode::COPY))
2060 MI.setDesc(
TII->get(TargetOpcode::IMPLICIT_DEF));
2061 for (
int j =
MI.getNumOperands() - 1, ee = 0; j > ee; --j)
2062 MI.removeOperand(j);
2068 if (UndefLanes.
any() && DefVN &&
MRI->shouldTrackSubRegLiveness(DstReg)) {
2070 for (MachineOperand &UseOp :
MRI->use_operands(DstReg)) {
2078 LaneBitmask LaneMask =
TRI->getSubRegIndexLaneMask(
SubReg);
2079 if ((UndefLanes & LaneMask).
any())
2088 MI.eraseFromParent();
unsigned const MachineRegisterInfo * MRI
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 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< unsigned > MaxDataFlowEdge("dataflow-edge-limit", cl::Hidden, cl::init(3), cl::desc("Maximum number of dataflow edges to traverse when evaluating " "the benefit of commuting operands"))
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 & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
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,...
defusechain_iterator< false, true, false, true, false > def_iterator
def_iterator/def_begin/def_end - Walk all defs of the specified register.
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
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...
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)
@ Define
Register definition.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
NodeAddr< DefNode * > Def
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 void initializeTwoAddressInstructionLegacyPassPass(PassRegistry &)
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.
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.