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);
203 TwoAddressInstructionLegacyPass() : MachineFunctionPass(ID) {
209 bool runOnMachineFunction(MachineFunction &MF)
override {
210 TwoAddressInstructionImpl Impl(MF,
this);
214 Impl.setOptLevel(CodeGenOptLevel::None);
218 void getAnalysisUsage(AnalysisUsage &AU)
const override {
239 TwoAddressInstructionImpl Impl(MF, MFAM, LIS);
262char TwoAddressInstructionLegacyPass::ID = 0;
267 "Two-Address instruction pass",
false,
false)
269TwoAddressInstructionImpl::TwoAddressInstructionImpl(
272 : MF(&Func),
TII(Func.getSubtarget().getInstrInfo()),
273 TRI(Func.getSubtarget().getRegisterInfo()),
274 InstrItins(Func.getSubtarget().getInstrItineraryData()),
275 MRI(&Func.getRegInfo()),
277 OptLevel(Func.getTarget().getOptLevel()) {}
279TwoAddressInstructionImpl::TwoAddressInstructionImpl(
MachineFunction &Func,
281 : MF(&
Func),
TII(
Func.getSubtarget().getInstrInfo()),
282 TRI(
Func.getSubtarget().getRegisterInfo()),
283 InstrItins(
Func.getSubtarget().getInstrItineraryData()),
284 MRI(&
Func.getRegInfo()), OptLevel(
Func.getTarget().getOptLevel()) {
286 LV = LVWrapper ? &LVWrapper->
getLV() :
nullptr;
288 LIS = LISWrapper ? &LISWrapper->
getLIS() :
nullptr;
293TwoAddressInstructionImpl::getSingleDef(
Register Reg,
295 MachineInstr *Ret =
nullptr;
296 for (MachineInstr &
DefMI :
MRI->def_instructions(
Reg)) {
297 if (
DefMI.getParent() != BB ||
DefMI.isDebugValue())
301 else if (Ret != &
DefMI)
314bool TwoAddressInstructionImpl::isRevCopyChain(
Register FromReg,
Register ToReg,
317 for (
int i = 0; i < Maxlen; i++) {
318 MachineInstr *
Def = getSingleDef(TmpReg,
MBB);
319 if (!Def || !
Def->isCopy())
322 TmpReg =
Def->getOperand(1).getReg();
334bool TwoAddressInstructionImpl::noUseAfterLastDef(
Register Reg,
unsigned Dist,
337 unsigned LastUse = Dist;
338 for (MachineOperand &MO :
MRI->reg_operands(
Reg)) {
339 MachineInstr *
MI = MO.getParent();
340 if (
MI->getParent() !=
MBB ||
MI->isDebugValue())
342 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.
find(
MI);
343 if (DI == DistanceMap.
end())
345 if (MO.isUse() && DI->second < LastUse)
346 LastUse = DI->second;
347 if (MO.isDef() && DI->second > LastDef)
348 LastDef = DI->second;
351 return !(LastUse > LastDef && LastUse < Dist);
357bool TwoAddressInstructionImpl::isCopyToReg(MachineInstr &
MI,
Register &SrcReg,
359 bool &IsDstPhys)
const {
363 DstReg =
MI.getOperand(0).getReg();
364 SrcReg =
MI.getOperand(1).getReg();
365 }
else if (
MI.isInsertSubreg() ||
MI.isSubregToReg()) {
366 DstReg =
MI.getOperand(0).getReg();
367 SrcReg =
MI.getOperand(2).getReg();
377bool TwoAddressInstructionImpl::isPlainlyKilled(
const MachineInstr *
MI,
384 LiveInterval::const_iterator
I = LR.
find(useIdx);
385 assert(
I != LR.
end() &&
"Reg must be live-in to use.");
391bool TwoAddressInstructionImpl::isPlainlyKilled(
const MachineInstr *
MI,
406 return isPlainlyKilled(MI, LIS->getRegUnit(U));
410 return MI->killsRegister(
Reg,
nullptr);
415bool TwoAddressInstructionImpl::isPlainlyKilled(
416 const MachineOperand &MO)
const {
437bool TwoAddressInstructionImpl::isKilled(MachineInstr &
MI,
Register Reg,
438 bool allowFalsePositives)
const {
451 if (std::next(Begin) !=
MRI->def_end())
454 bool IsSrcPhys, IsDstPhys;
458 if (!isCopyToReg(*
DefMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
467 for (
unsigned i = 0,
NumOps =
MI.getNumOperands(); i !=
NumOps; ++i) {
472 if (
MI.isRegTiedToDefOperand(i, &ti)) {
473 DstReg =
MI.getOperand(ti).getReg();
482MachineInstr *TwoAddressInstructionImpl::findOnlyInterestingUse(
484 bool &IsDstPhys)
const {
485 MachineOperand *UseOp =
nullptr;
486 for (MachineOperand &MO :
MRI->use_nodbg_operands(
Reg)) {
491 if (
MI->getParent() !=
MBB)
493 if (isPlainlyKilled(
MI,
Reg))
502 if (isCopyToReg(
UseMI, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
511 if (
UseMI.isCommutable()) {
514 if (
TII->findCommutedOpIndices(
UseMI, Src1, Src2)) {
515 MachineOperand &MO =
UseMI.getOperand(Src1);
530 while (
Reg.isVirtual()) {
532 if (
SI == RegMap.
end())
536 if (
Reg.isPhysical())
542bool TwoAddressInstructionImpl::regsAreCompatible(
Register RegA,
548 return TRI->regsOverlap(RegA, RegB);
552void TwoAddressInstructionImpl::removeMapRegEntry(
553 const MachineOperand &MO, DenseMap<Register, Register> &RegMap)
const {
556 "removeMapRegEntry must be called with a register or regmask operand.");
559 for (
auto SI : RegMap) {
566 if (
TRI->regsOverlap(ToReg,
Reg))
572 for (
auto SrcReg : Srcs)
573 RegMap.erase(SrcReg);
584void TwoAddressInstructionImpl::removeClobberedSrcRegMap(MachineInstr *
MI) {
597 if (!Dst || Dst.isVirtual())
601 if (regsAreCompatible(Dst,
getMappedReg(Src, SrcRegMap)))
605 for (
const MachineOperand &MO :
MI->operands()) {
607 removeMapRegEntry(MO, SrcRegMap);
615 removeMapRegEntry(MO, SrcRegMap);
620bool TwoAddressInstructionImpl::regOverlapsSet(
621 const SmallVectorImpl<Register> &Set,
Register Reg)
const {
623 if (
TRI->regsOverlap(R,
Reg))
631bool TwoAddressInstructionImpl::isProfitableToCommute(
Register RegA,
636 if (OptLevel == CodeGenOptLevel::None)
657 if (!isPlainlyKilled(
MI, RegC))
674 bool CompB = FromRegB && regsAreCompatible(FromRegB, ToRegA);
675 bool CompC = FromRegC && regsAreCompatible(FromRegC, ToRegA);
681 if ((!FromRegB && CompC) || (FromRegB && !CompB && (!FromRegC || CompC)))
687 if ((!FromRegC && CompB) || (FromRegC && !CompC && (!FromRegB || CompB)))
693 unsigned LastDefC = 0;
694 if (!noUseAfterLastDef(RegC, Dist, LastDefC))
699 unsigned LastDefB = 0;
700 if (!noUseAfterLastDef(RegB, Dist, LastDefB))
726 if (
TII->hasCommutePreference(*
MI, Commute))
731 return LastDefB && LastDefC && LastDefC > LastDefB;
736bool TwoAddressInstructionImpl::commuteInstruction(MachineInstr *
MI,
741 Register RegC =
MI->getOperand(RegCIdx).getReg();
743 MachineInstr *NewMI =
TII->commuteInstruction(*
MI,
false, RegBIdx, RegCIdx);
745 if (NewMI ==
nullptr) {
752 "TargetInstrInfo::commuteInstruction() should not return a new "
753 "instruction unless it was requested.");
758 Register RegA =
MI->getOperand(DstIdx).getReg();
759 SrcRegMap[RegA] = FromRegC;
767bool TwoAddressInstructionImpl::isProfitableToConv3Addr(
Register RegA,
779 return (ToRegA && !regsAreCompatible(FromRegB, ToRegA));
784bool TwoAddressInstructionImpl::convertInstTo3Addr(
787 MachineInstrSpan MIS(mi,
MBB);
788 MachineInstr *NewMI =
TII->convertToThreeAddress(*mi, LV, LIS);
792 for (MachineInstr &
MI : MIS)
793 DistanceMap.
insert(std::make_pair(&
MI, Dist++));
796 LLVM_DEBUG(
dbgs() <<
"2addr: CONVERTED IN-PLACE TO 3-ADDR: " << *mi);
799 dbgs() <<
"2addr: CONVERTING 2-ADDR: " << *mi;
800 dbgs() <<
"2addr: TO 3-ADDR: " << *NewMI;
804 if (
auto OldInstrNum = mi->peekDebugInstrNum()) {
805 assert(mi->getNumExplicitDefs() == 1);
809 unsigned OldIdx = mi->defs().begin()->getOperandNo();
810 unsigned NewIdx = NewMI->
defs().
begin()->getOperandNo();
815 std::make_pair(NewInstrNum, NewIdx));
826 SrcRegMap.
erase(RegA);
827 DstRegMap.
erase(RegB);
833void TwoAddressInstructionImpl::scanUses(
Register DstReg) {
839 while (MachineInstr *
UseMI =
840 findOnlyInterestingUse(
Reg,
MBB, IsCopy, NewReg, IsDstPhys)) {
841 if (IsCopy && !Processed.insert(
UseMI).second)
844 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.
find(
UseMI);
845 if (DI != DistanceMap.
end())
853 SrcRegMap[NewReg] =
Reg;
858 if (!VirtRegPairs.
empty()) {
860 while (!VirtRegPairs.
empty()) {
862 bool isNew = DstRegMap.
insert(std::make_pair(FromReg, ToReg)).second;
864 assert(DstRegMap[FromReg] == ToReg &&
"Can't map to two dst registers!");
867 bool isNew = DstRegMap.
insert(std::make_pair(DstReg, ToReg)).second;
869 assert(DstRegMap[DstReg] == ToReg &&
"Can't map to two dst registers!");
885void TwoAddressInstructionImpl::processCopy(MachineInstr *
MI) {
886 if (Processed.count(
MI))
889 bool IsSrcPhys, IsDstPhys;
891 if (!isCopyToReg(*
MI, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
894 if (IsDstPhys && !IsSrcPhys) {
895 DstRegMap.
insert(std::make_pair(SrcReg, DstReg));
896 }
else if (!IsDstPhys && IsSrcPhys) {
897 bool isNew = SrcRegMap.
insert(std::make_pair(DstReg, SrcReg)).second;
899 assert(SrcRegMap[DstReg] == SrcReg &&
900 "Can't map to two src physical registers!");
905 Processed.insert(
MI);
911bool TwoAddressInstructionImpl::rescheduleMIBelowKill(
919 MachineInstr *
MI = &*mi;
920 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.
find(
MI);
921 if (DI == DistanceMap.
end())
925 MachineInstr *KillMI =
nullptr;
929 "Reg should not have empty live interval.");
932 LiveInterval::const_iterator
I = LI.
find(MBBEndIdx);
933 if (
I != LI.
end() &&
I->start < MBBEndIdx)
954 bool SeenStore =
true;
955 if (!
MI->isSafeToMove(SeenStore))
965 for (
const MachineOperand &MO :
MI->operands()) {
974 Uses.push_back(MOReg);
975 if (MOReg !=
Reg && isPlainlyKilled(MO))
984 while (End !=
MBB->
end()) {
986 if (End->isCopy() && regOverlapsSet(Defs, End->getOperand(1).getReg()))
987 Defs.
push_back(End->getOperand(0).getReg());
994 unsigned NumVisited = 0;
997 for (MachineInstr &OtherMI :
make_range(End, KillPos)) {
999 if (OtherMI.isDebugOrPseudoInstr())
1001 if (NumVisited > 10)
1004 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1005 OtherMI.isBranch() || OtherMI.isTerminator())
1008 for (
const MachineOperand &MO : OtherMI.operands()) {
1015 if (regOverlapsSet(
Uses, MOReg))
1018 if (!MO.
isDead() && regOverlapsSet(Defs, MOReg))
1024 if (regOverlapsSet(Defs, MOReg))
1026 bool isKill = isPlainlyKilled(MO);
1027 if (MOReg !=
Reg && ((isKill && regOverlapsSet(
Uses, MOReg)) ||
1028 regOverlapsSet(Kills, MOReg)))
1031 if (MOReg ==
Reg && !isKill)
1035 assert((MOReg !=
Reg || &OtherMI == KillMI) &&
1036 "Found multiple kills of a register in a basic block");
1042 while (Begin !=
MBB->
begin() && std::prev(Begin)->isDebugInstr())
1051 auto CopyMI =
MBBI++;
1053 if (!CopyMI->isDebugOrPseudoInstr())
1062 DistanceMap.
erase(DI);
1078bool TwoAddressInstructionImpl::isDefTooClose(
Register Reg,
unsigned Dist,
1080 for (MachineInstr &
DefMI :
MRI->def_instructions(
Reg)) {
1085 DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.
find(&
DefMI);
1086 if (DDI == DistanceMap.
end())
1088 unsigned DefDist = DDI->second;
1089 assert(Dist > DefDist &&
"Visited def already?");
1099bool TwoAddressInstructionImpl::rescheduleKillAboveMI(
1107 MachineInstr *
MI = &*mi;
1108 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.
find(
MI);
1109 if (DI == DistanceMap.
end())
1113 MachineInstr *KillMI =
nullptr;
1117 "Reg should not have empty live interval.");
1120 LiveInterval::const_iterator
I = LI.
find(MBBEndIdx);
1121 if (
I != LI.
end() &&
I->start < MBBEndIdx)
1137 bool SeenStore =
true;
1145 for (
const MachineOperand &MO : KillMI->
operands()) {
1152 if (isDefTooClose(MOReg, DI->second,
MI))
1154 bool isKill = isPlainlyKilled(MO);
1155 if (MOReg ==
Reg && !isKill)
1157 Uses.push_back(MOReg);
1158 if (isKill && MOReg !=
Reg)
1168 unsigned NumVisited = 0;
1169 for (MachineInstr &OtherMI :
1172 if (OtherMI.isDebugOrPseudoInstr())
1174 if (NumVisited > 10)
1177 if (OtherMI.hasUnmodeledSideEffects() || OtherMI.isCall() ||
1178 OtherMI.isBranch() || OtherMI.isTerminator())
1182 for (
const MachineOperand &MO : OtherMI.operands()) {
1189 if (regOverlapsSet(Defs, MOReg))
1193 if (regOverlapsSet(Kills, MOReg))
1196 if (&OtherMI !=
MI && MOReg ==
Reg && !isPlainlyKilled(MO))
1205 if (regOverlapsSet(
Uses, MOReg))
1207 if (MOReg.
isPhysical() && regOverlapsSet(LiveDefs, MOReg))
1216 while (InsertPos !=
MBB->
begin() && std::prev(InsertPos)->isDebugInstr())
1220 while (std::prev(From)->isDebugInstr())
1224 nmi = std::prev(InsertPos);
1225 DistanceMap.
erase(DI);
1251bool TwoAddressInstructionImpl::tryInstructionCommute(MachineInstr *
MI,
1256 if (!
MI->isCommutable())
1259 bool MadeChange =
false;
1260 Register DstOpReg =
MI->getOperand(DstOpIdx).getReg();
1261 Register BaseOpReg =
MI->getOperand(BaseOpIdx).getReg();
1262 unsigned OpsNum =
MI->getDesc().getNumOperands();
1263 unsigned OtherOpIdx =
MI->getDesc().getNumDefs();
1264 for (; OtherOpIdx < OpsNum; OtherOpIdx++) {
1269 if (OtherOpIdx == BaseOpIdx || !
MI->getOperand(OtherOpIdx).isReg() ||
1270 !
TII->findCommutedOpIndices(*
MI, BaseOpIdx, OtherOpIdx))
1273 Register OtherOpReg =
MI->getOperand(OtherOpIdx).getReg();
1274 bool AggressiveCommute =
false;
1278 bool OtherOpKilled = isKilled(*
MI, OtherOpReg,
false);
1279 bool DoCommute = !BaseOpKilled && OtherOpKilled;
1282 isProfitableToCommute(DstOpReg, BaseOpReg, OtherOpReg,
MI, Dist)) {
1284 AggressiveCommute =
true;
1288 if (DoCommute && commuteInstruction(
MI, DstOpIdx, BaseOpIdx, OtherOpIdx,
1292 if (AggressiveCommute)
1299 BaseOpReg = OtherOpReg;
1300 BaseOpKilled = OtherOpKilled;
1303 OpsNum =
MI->getDesc().getNumOperands();
1316bool TwoAddressInstructionImpl::tryInstructionTransform(
1318 unsigned SrcIdx,
unsigned DstIdx,
unsigned &Dist,
bool shouldOnlyCommute) {
1319 if (OptLevel == CodeGenOptLevel::None)
1322 MachineInstr &
MI = *mi;
1323 Register regA =
MI.getOperand(DstIdx).getReg();
1324 Register regB =
MI.getOperand(SrcIdx).getReg();
1326 assert(regB.
isVirtual() &&
"cannot make instruction into two-address form");
1327 bool regBKilled = isKilled(
MI, regB,
true);
1332 bool Commuted = tryInstructionCommute(&
MI, DstIdx, SrcIdx, regBKilled, Dist);
1345 if (Commuted && !ConvertibleTo3Addr)
1348 if (shouldOnlyCommute)
1361 regB =
MI.getOperand(SrcIdx).getReg();
1362 regBKilled = isKilled(
MI, regB,
true);
1365 if (ConvertibleTo3Addr) {
1368 if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1370 if (convertInstTo3Addr(mi, nmi, regA, regB, Dist)) {
1371 ++NumConvertedTo3Addr;
1396 if (
MI.mayLoad() && !regBKilled) {
1398 unsigned LoadRegIndex;
1400 TII->getOpcodeAfterMemoryUnfold(
MI.getOpcode(),
1405 const MCInstrDesc &UnfoldMCID =
TII->get(NewOpc);
1409 const TargetRegisterClass *RC =
TRI->getAllocatableClass(
1410 TII->getRegClass(UnfoldMCID, LoadRegIndex));
1412 SmallVector<MachineInstr *, 2> NewMIs;
1413 if (!
TII->unfoldMemoryOperand(*MF,
MI,
Reg,
1420 "Unfolded a load into multiple instructions!");
1422 NewMIs[1]->addRegisterKilled(
Reg,
TRI);
1428 DistanceMap.
insert(std::make_pair(NewMIs[0], Dist++));
1429 DistanceMap.
insert(std::make_pair(NewMIs[1], Dist));
1432 <<
"2addr: NEW INST: " << *NewMIs[1]);
1435 unsigned NewDstIdx =
1436 NewMIs[1]->findRegisterDefOperandIdx(regA,
nullptr);
1437 unsigned NewSrcIdx =
1438 NewMIs[1]->findRegisterUseOperandIdx(regB,
nullptr);
1440 bool TransformResult =
1441 tryInstructionTransform(NewMI, mi, NewSrcIdx, NewDstIdx, Dist,
true);
1442 (void)TransformResult;
1443 assert(!TransformResult &&
1444 "tryInstructionTransform() should return false.");
1445 if (NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1449 for (
const MachineOperand &MO :
MI.operands()) {
1453 if (NewMIs[0]->killsRegister(MO.
getReg(),
nullptr))
1458 "Kill missing after load unfold!");
1463 if (NewMIs[1]->registerDefIsDead(MO.
getReg(),
1469 "Dead flag missing after load unfold!");
1480 for (
const MachineOperand &MO :
MI.operands()) {
1488 MI.eraseFromParent();
1504 NewMIs[0]->eraseFromParent();
1505 NewMIs[1]->eraseFromParent();
1506 DistanceMap.
erase(NewMIs[0]);
1507 DistanceMap.
erase(NewMIs[1]);
1520bool TwoAddressInstructionImpl::collectTiedOperands(
1521 MachineInstr *
MI, TiedOperandMap &TiedOperands) {
1522 bool AnyOps =
false;
1523 unsigned NumOps =
MI->getNumOperands();
1525 for (
unsigned SrcIdx = 0; SrcIdx <
NumOps; ++SrcIdx) {
1526 unsigned DstIdx = 0;
1527 if (!
MI->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1530 MachineOperand &SrcMO =
MI->getOperand(SrcIdx);
1531 MachineOperand &DstMO =
MI->getOperand(DstIdx);
1535 if (SrcReg == DstReg)
1538 assert(SrcReg && SrcMO.
isUse() &&
"two address instruction invalid");
1544 const TargetRegisterClass *RC =
MRI->getRegClass(SrcReg);
1545 MRI->constrainRegClass(DstReg, RC);
1552 TiedOperands[SrcReg].push_back(std::make_pair(SrcIdx, DstIdx));
1559void TwoAddressInstructionImpl::processTiedPairs(MachineInstr *
MI,
1560 TiedPairList &TiedPairs,
1562 bool IsEarlyClobber =
llvm::any_of(TiedPairs, [
MI](
auto const &TP) {
1563 return MI->getOperand(TP.second).isEarlyClobber();
1566 bool RemovedKillFlag =
false;
1567 bool AllUsesCopied =
true;
1569 SlotIndex LastCopyIdx;
1571 unsigned SubRegB = 0;
1572 for (
auto &TP : TiedPairs) {
1573 unsigned SrcIdx = TP.first;
1574 unsigned DstIdx = TP.second;
1576 const MachineOperand &DstMO =
MI->getOperand(DstIdx);
1581 RegB =
MI->getOperand(SrcIdx).getReg();
1582 SubRegB =
MI->getOperand(SrcIdx).getSubReg();
1588 AllUsesCopied =
false;
1591 LastCopiedReg = RegA;
1593 assert(RegB.
isVirtual() &&
"cannot make instruction into two-address form");
1599 for (
unsigned i = 0; i !=
MI->getNumOperands(); ++i)
1601 !
MI->getOperand(i).isReg() ||
1602 MI->getOperand(i).getReg() != RegA);
1606 MachineInstrBuilder MIB =
BuildMI(*
MI->getParent(),
MI,
MI->getDebugLoc(),
1607 TII->get(TargetOpcode::COPY), RegA);
1610 MIB.
addReg(RegB, 0, SubRegB);
1611 const TargetRegisterClass *RC =
MRI->getRegClass(RegB);
1614 assert(
TRI->getMatchingSuperRegClass(RC,
MRI->getRegClass(RegA),
1616 "tied subregister must be a truncation");
1620 assert(
TRI->getMatchingSuperReg(RegA, SubRegB,
MRI->getRegClass(RegB))
1621 &&
"tied subregister must be a truncation");
1628 DistanceMap.
insert(std::make_pair(&*PrevMI, Dist));
1629 DistanceMap[
MI] = ++Dist;
1639 LI.
addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1642 S.addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1645 for (MCRegUnit Unit :
TRI->regunits(RegA)) {
1649 LR->
addSegment(LiveRange::Segment(LastCopyIdx, endIdx, VNI));
1657 MachineOperand &MO =
MI->getOperand(SrcIdx);
1659 "inconsistent operand info for 2-reg pass");
1660 if (isPlainlyKilled(MO)) {
1662 RemovedKillFlag =
true;
1667 MRI->constrainRegClass(RegA, RC);
1675 if (
MI->isBundle()) {
1679 "tied subregister uses in bundled instructions not supported");
1686 if (AllUsesCopied) {
1689 for (MachineOperand &MO :
MI->all_uses()) {
1690 if (MO.
getReg() == RegB) {
1691 if (MO.
getSubReg() == SubRegB && !IsEarlyClobber) {
1692 if (isPlainlyKilled(MO)) {
1694 RemovedKillFlag =
true;
1696 MO.
setReg(LastCopiedReg);
1699 RemainingUses |=
TRI->getSubRegIndexLaneMask(MO.
getSubReg());
1705 if (RemovedKillFlag && RemainingUses.
none() && LV &&
1712 if (RemovedKillFlag && RemainingUses.
none())
1713 SrcRegMap[LastCopiedReg] = RegB;
1718 auto Shrink = [=](
LiveRange &LR, LaneBitmask LaneMask) {
1722 if ((LaneMask & RemainingUses).
any())
1726 S->
end = LastCopyIdx;
1731 bool ShrinkLI =
true;
1733 ShrinkLI &= Shrink(S, S.LaneMask);
1737 }
else if (RemovedKillFlag) {
1742 for (MachineOperand &MO :
MI->all_uses()) {
1743 if (MO.
getReg() == RegB) {
1758bool TwoAddressInstructionImpl::processStatepoint(
1759 MachineInstr *
MI, TiedOperandMap &TiedOperands) {
1761 bool NeedCopy =
false;
1762 for (
auto &TO : TiedOperands) {
1764 if (TO.second.size() != 1) {
1769 unsigned SrcIdx = TO.second[0].first;
1770 unsigned DstIdx = TO.second[0].second;
1772 MachineOperand &DstMO =
MI->getOperand(DstIdx);
1775 assert(RegB ==
MI->getOperand(SrcIdx).getReg());
1788 if (DefLI.overlaps(UseLI)) {
1790 <<
" UseLI overlaps with DefLI\n");
1799 <<
" not killed by statepoint\n");
1804 if (!
MRI->constrainRegClass(RegB,
MRI->getRegClass(RegA))) {
1806 <<
" to register class of " <<
printReg(RegA,
TRI, 0)
1811 MRI->replaceRegWith(RegA, RegB);
1818 for (
const VNInfo *VNI :
Other.valnos) {
1822 for (
auto &S :
Other) {
1823 VNInfo *VNI = NewVNIs[S.
valno->
id];
1824 LiveRange::Segment NewSeg(S.
start, S.
end, VNI);
1831 if (
MI->getOperand(SrcIdx).isKill())
1833 LiveVariables::VarInfo &SrcInfo = LV->
getVarInfo(RegB);
1834 LiveVariables::VarInfo &DstInfo = LV->
getVarInfo(RegA);
1837 for (
auto *KillMI : DstInfo.
Kills)
1845bool TwoAddressInstructionImpl::run() {
1846 bool MadeChange =
false;
1848 LLVM_DEBUG(
dbgs() <<
"********** REWRITING TWO-ADDR INSTRS **********\n");
1857 TiedOperandMap TiedOperands;
1858 for (MachineBasicBlock &
MBBI : *MF) {
1861 DistanceMap.
clear();
1869 if (mi->isDebugInstr()) {
1876 if (mi->isRegSequence()) {
1877 eliminateRegSequence(mi);
1881 DistanceMap.
insert(std::make_pair(&*mi, ++Dist));
1887 if (!collectTiedOperands(&*mi, TiedOperands)) {
1888 removeClobberedSrcRegMap(&*mi);
1893 ++NumTwoAddressInstrs;
1900 if (TiedOperands.size() == 1) {
1901 SmallVectorImpl<std::pair<unsigned, unsigned>> &TiedPairs
1902 = TiedOperands.begin()->second;
1903 if (TiedPairs.
size() == 1) {
1904 unsigned SrcIdx = TiedPairs[0].first;
1905 unsigned DstIdx = TiedPairs[0].second;
1906 Register SrcReg = mi->getOperand(SrcIdx).getReg();
1907 Register DstReg = mi->getOperand(DstIdx).getReg();
1908 if (SrcReg != DstReg &&
1909 tryInstructionTransform(mi, nmi, SrcIdx, DstIdx, Dist,
false)) {
1912 TiedOperands.clear();
1913 removeClobberedSrcRegMap(&*mi);
1920 if (mi->getOpcode() == TargetOpcode::STATEPOINT &&
1921 processStatepoint(&*mi, TiedOperands)) {
1922 TiedOperands.clear();
1929 for (
auto &TO : TiedOperands) {
1930 processTiedPairs(&*mi, TO.second, Dist);
1935 if (mi->isInsertSubreg()) {
1938 unsigned SubIdx = mi->getOperand(3).getImm();
1939 mi->removeOperand(3);
1940 assert(mi->getOperand(0).getSubReg() == 0 &&
"Unexpected subreg idx");
1941 mi->getOperand(0).setSubReg(SubIdx);
1942 mi->getOperand(0).setIsUndef(mi->getOperand(1).isUndef());
1943 mi->removeOperand(1);
1944 mi->setDesc(
TII->get(TargetOpcode::COPY));
1954 LaneBitmask LaneMask =
1955 TRI->getSubRegIndexLaneMask(mi->getOperand(0).getSubReg());
1958 if ((S.LaneMask & LaneMask).none()) {
1959 LiveRange::iterator DefSeg = S.FindSegmentContaining(Idx);
1960 if (mi->getOperand(0).isUndef()) {
1961 S.removeValNo(DefSeg->valno);
1963 LiveRange::iterator UseSeg = std::prev(DefSeg);
1964 S.MergeValueNumberInto(DefSeg->valno, UseSeg->valno);
1982 TiedOperands.clear();
1983 removeClobberedSrcRegMap(&*mi);
2001void TwoAddressInstructionImpl::eliminateRegSequence(
2003 MachineInstr &
MI = *
MBBI;
2007 VNInfo *DefVN =
nullptr;
2010 for (
unsigned i = 1, e =
MI.getNumOperands(); i < e; i += 2)
2020 bool DefEmitted =
false;
2021 for (
unsigned i = 1, e =
MI.getNumOperands(); i < e; i += 2) {
2022 MachineOperand &UseMO =
MI.getOperand(i);
2024 unsigned SubIdx =
MI.getOperand(i+1).getImm();
2027 UndefLanes |=
TRI->getSubRegIndexLaneMask(SubIdx);
2033 bool isKill = UseMO.
isKill();
2035 for (
unsigned j = i + 2;
j <
e;
j += 2)
2036 if (
MI.getOperand(j).getReg() == SrcReg) {
2037 MI.getOperand(j).setIsKill();
2044 MachineInstr *CopyMI =
BuildMI(*
MI.getParent(),
MI,
MI.getDebugLoc(),
2045 TII->get(TargetOpcode::COPY))
2070 MI.setDesc(
TII->get(TargetOpcode::IMPLICIT_DEF));
2071 for (
int j =
MI.getNumOperands() - 1, ee = 0; j > ee; --j)
2072 MI.removeOperand(j);
2078 if (UndefLanes.
any() && DefVN &&
MRI->shouldTrackSubRegLiveness(DstReg)) {
2080 for (MachineOperand &UseOp :
MRI->use_operands(DstReg)) {
2088 LaneBitmask LaneMask =
TRI->getSubRegIndexLaneMask(
SubReg);
2089 if ((UndefLanes & LaneMask).
any())
2098 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"))
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 & 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.