45 #define DEBUG_TYPE "regalloc"
47 STATISTIC(numJoins ,
"Number of interval joins performed");
48 STATISTIC(numCrossRCs ,
"Number of cross class joins performed");
49 STATISTIC(numCommutes ,
"Number of instruction commuting performed");
50 STATISTIC(numExtends ,
"Number of copies extended");
51 STATISTIC(NumReMats ,
"Number of instructions re-materialized");
52 STATISTIC(NumInflated ,
"Number of register classes inflated");
53 STATISTIC(NumLaneConflicts,
"Number of dead lane conflicts tested");
54 STATISTIC(NumLaneResolves,
"Number of dead lane conflicts resolved");
58 cl::desc(
"Coalesce copies (default=true)"),
73 cl::desc(
"Coalesce copies that span blocks (default=subtarget)"),
78 cl::desc(
"Verify machine instrs before and after register coalescing"),
100 bool ShrinkMainRange;
104 bool JoinGlobalCopies;
125 void eliminateDeadDefs();
131 void coalesceLocals();
134 void joinAllIntervals();
208 void updateRegDefsUses(
unsigned SrcReg,
unsigned DstReg,
unsigned SubIdx);
243 if (LIS->shrinkToUses(LI,
Dead)) {
247 LIS->splitSeparateComponents(*LI, SplitLIs);
259 void releaseMemory()
override;
272 "Simple Register Coalescing",
false,
false)
280 char RegisterCoalescer::
ID = 0;
283 unsigned &Src,
unsigned &Dst,
284 unsigned &SrcSub,
unsigned &DstSub) {
286 Dst = MI->getOperand(0).getReg();
287 DstSub = MI->getOperand(0).getSubReg();
288 Src = MI->getOperand(1).getReg();
289 SrcSub = MI->getOperand(1).getSubReg();
290 }
else if (MI->isSubregToReg()) {
291 Dst = MI->getOperand(0).getReg();
292 DstSub = tri.composeSubRegIndices(MI->getOperand(0).getSubReg(),
293 MI->getOperand(3).getImm());
294 Src = MI->getOperand(2).getReg();
295 SrcSub = MI->getOperand(2).getSubReg();
310 for (
const auto &
MI : *MBB) {
311 if (!
MI.isCopyLike() && !
MI.isUnconditionalBranch())
321 Flipped = CrossClass =
false;
323 unsigned Src, Dst, SrcSub, DstSub;
324 if (!
isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
326 Partial = SrcSub || DstSub;
343 if (!Dst)
return false;
350 if (!Dst)
return false;
360 if (SrcSub && DstSub) {
362 if (Src == Dst && SrcSub != DstSub)
388 if (DstIdx && !SrcIdx) {
394 CrossClass = NewRC != DstRC || NewRC != SrcRC;
399 "Cannot have a physical SubIdx");
417 unsigned Src, Dst, SrcSub, DstSub;
418 if (!
isMoveInstr(TRI, MI, Src, Dst, SrcSub, DstSub))
425 }
else if (Src != SrcReg) {
433 assert(!DstIdx && !SrcIdx &&
"Inconsistent CoalescerPair state.");
439 return DstReg == Dst;
441 return TRI.
getSubReg(DstReg, SrcSub) == Dst;
452 void RegisterCoalescer::getAnalysisUsage(
AnalysisUsage &AU)
const {
464 void RegisterCoalescer::eliminateDeadDefs() {
470 void RegisterCoalescer::LRE_WillEraseInstruction(
MachineInstr *
MI) {
472 ErasedInstrs.insert(MI);
478 assert(!CP.
isPhys() &&
"This doesn't work for physreg copies.");
503 if (BS == IntB.
end())
return false;
504 VNInfo *BValNo = BS->valno;
509 if (BValNo->
def != CopyIdx)
return false;
515 if (AS == IntA.end())
return false;
516 VNInfo *AValNo = AS->valno;
528 if (ValS == IntB.
end())
534 LIS->getInstructionFromIndex(ValS->end.getPrevSlot());
541 if (ValS+1 != BS)
return false;
545 SlotIndex FillerStart = ValS->end, FillerEnd = BS->start;
549 BValNo->
def = FillerStart;
554 IntB.
addSegment(LiveInterval::Segment(FillerStart, FillerEnd, BValNo));
557 if (BValNo != ValS->valno)
562 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
563 S.addSegment(LiveInterval::Segment(FillerStart, FillerEnd, SubBValNo));
565 if (SubBValNo != SubValSNo)
566 S.MergeValueNumberInto(SubBValNo, SubValSNo);
569 DEBUG(
dbgs() <<
" result = " << IntB <<
'\n');
582 if (AS->end == CopyIdx)
589 bool RegisterCoalescer::hasOtherReachingDefs(
LiveInterval &IntA,
595 if (LIS->hasPHIKill(IntA, AValNo))
599 if (ASeg.
valno != AValNo)
continue;
602 if (BI != IntB.
begin())
604 for (; BI != IntB.
end() && ASeg.
end >= BI->start; ++BI) {
605 if (BI->valno == BValNo)
607 if (BI->start <= ASeg.
start && BI->end > ASeg.
start)
609 if (BI->start > ASeg.
start && BI->start < ASeg.
end)
622 if (S.
valno != SrcValNo)
628 bool RegisterCoalescer::removeCopyByCommutingDef(
const CoalescerPair &CP,
661 assert(BValNo !=
nullptr && BValNo->
def == CopyIdx);
691 if (!
TII->findCommutedOpIndices(*DefMI, UseOpIdx, NewDstIdx))
695 unsigned NewReg = NewDstMO.
getReg();
701 if (hasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
709 SlotIndex UseIdx = LIS->getInstructionIndex(*UseMI);
711 if (US == IntA.end() || US->valno != AValNo)
718 DEBUG(
dbgs() <<
"\tremoveCopyByCommutingDef: " << AValNo->
def <<
'\t'
725 TII->commuteInstruction(*DefMI,
false, UseOpIdx, NewDstIdx);
730 !
MRI->constrainRegClass(IntB.
reg,
MRI->getRegClass(IntA.reg)))
732 if (NewMI != DefMI) {
733 LIS->ReplaceMachineInstrInMaps(*DefMI, *NewMI);
765 assert(US != IntA.end() &&
"Use must be live");
766 if (US->valno != AValNo)
788 DEBUG(
dbgs() <<
"\t\tnoop: " << DefIdx <<
'\t' << *UseMI);
792 VNInfo *SubDVNI = S.getVNInfoAt(DefIdx);
795 VNInfo *SubBValNo = S.getVNInfoAt(CopyIdx);
797 S.MergeValueNumberInto(SubDVNI, SubBValNo);
800 ErasedInstrs.insert(UseMI);
801 LIS->RemoveMachineInstrFromMaps(*UseMI);
809 if (!IntA.hasSubRanges()) {
811 IntA.createSubRangeFrom(Allocator, Mask, IntA);
815 VNInfo *ASubValNo = SA.getVNInfoAt(AIdx);
816 assert(ASubValNo !=
nullptr);
823 assert(BSubValNo !=
nullptr);
829 BValNo->
def = AValNo->
def;
831 DEBUG(
dbgs() <<
"\t\textended: " << IntB <<
'\n');
833 LIS->removeVRegDefAt(IntA, AValNo->
def);
835 DEBUG(
dbgs() <<
"\t\ttrimmed: " << IntA <<
'\n');
887 bool RegisterCoalescer::removePartialRedundancy(
const CoalescerPair &CP,
913 if (IntB.
overlaps(LIS->getMBBStartIdx(&MBB), CopyIdx))
918 bool FoundReverseCopy =
false;
937 bool ValB_Changed =
false;
938 for (
auto VNI : IntB.
valnos) {
941 if (PVal->
def < VNI->def && VNI->def < LIS->getMBBEndIdx(Pred)) {
950 FoundReverseCopy =
true;
954 if (!FoundReverseCopy)
964 if (CopyLeftBB && CopyLeftBB->
succ_size() > 1)
969 DEBUG(
dbgs() <<
"\tremovePartialRedundancy: Move the copy to BB#"
970 << CopyLeftBB->
getNumber() <<
'\t' << CopyMI);
975 TII->get(TargetOpcode::COPY), IntB.
reg)
978 LIS->InsertMachineInstrInMaps(*NewCopyMI).
getRegSlot();
981 SR.createDeadDef(NewCopyIdx, LIS->getVNInfoAllocator());
986 ErasedInstrs.erase(NewCopyMI);
988 DEBUG(
dbgs() <<
"\tremovePartialRedundancy: Remove the copy from BB#"
996 LIS->RemoveMachineInstrFromMaps(CopyMI);
998 ErasedInstrs.insert(&CopyMI);
1004 LIS->pruneValue(*static_cast<LiveRange *>(&IntB), CopyIdx.
getRegSlot(),
1008 LIS->extendToIndices(IntB, EndPoints);
1013 VNInfo *BValNo = SR.Query(CopyIdx).valueOutOrDead();
1014 assert(BValNo &&
"All sublanes should be live");
1015 LIS->pruneValue(SR, CopyIdx.
getRegSlot(), &EndPoints);
1017 LIS->extendToIndices(SR, EndPoints);
1021 shrinkToUses(&IntA);
1028 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) &&
1029 "This code cannot handle physreg aliasing");
1031 if (!
Op.isReg() || !
Op.isDef() ||
Op.getReg() !=
Reg)
1035 if (
Op.getSubReg() == 0 ||
Op.isUndef())
1041 bool RegisterCoalescer::reMaterializeTrivialDef(
const CoalescerPair &CP,
1049 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
1053 SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
1055 assert(ValNo &&
"CopyMI input register not live");
1065 if (!
TII->isAsCheapAsAMove(*DefMI))
1067 if (!
TII->isTriviallyReMaterializable(*DefMI, AA))
1079 unsigned CopyDstReg = DstOperand.
getReg();
1088 if (SrcIdx && DstIdx)
1093 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
1094 unsigned NewDstReg = DstReg;
1096 unsigned NewDstIdx = TRI->composeSubRegIndices(CP.
getSrcIdx(),
1099 NewDstReg = TRI->getSubReg(DstReg, NewDstIdx);
1108 assert(TargetRegisterInfo::isVirtualRegister(DstReg) &&
1109 "Only expect to deal with virtual or physical registers");
1117 TII->reMaterialize(*MBB, MII, DstReg, SrcIdx, *DefMI, *TRI);
1131 &&
"Shouldn't have SrcIdx+DstIdx at this point");
1134 TRI->getCommonSubClass(DefRC, DstRC);
1135 if (CommonRC !=
nullptr) {
1156 if (TargetRegisterInfo::isPhysicalRegister(MO.
getReg()))
1161 LIS->ReplaceMachineInstrInMaps(*CopyMI, NewMI);
1163 ErasedInstrs.insert(CopyMI);
1175 TargetRegisterInfo::isPhysicalRegister(MO.
getReg()));
1180 if (TargetRegisterInfo::isVirtualRegister(DstReg)) {
1183 if (DefRC !=
nullptr) {
1185 NewRC = TRI->getMatchingSuperRegClass(NewRC, DefRC, NewIdx);
1187 NewRC = TRI->getCommonSubClass(NewRC, DefRC);
1188 assert(NewRC &&
"subreg chosen for remat incompatible with instruction");
1193 SR.LaneMask = TRI->composeSubRegIndexLaneMask(DstIdx, SR.LaneMask);
1195 MRI->setRegClass(DstReg, NewRC);
1198 updateRegDefsUses(DstReg, DstReg, DstIdx);
1215 SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
1221 if (!SR.liveAt(DefIndex))
1222 SR.createDeadDef(DefIndex, Alloc);
1223 MaxMask &= ~SR.LaneMask;
1225 if (MaxMask.
any()) {
1241 SlotIndex CurrIdx = LIS->getInstructionIndex(NewMI);
1242 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(NewIdx);
1243 bool UpdatedSubRanges =
false;
1245 if ((SR.
LaneMask & DstMask).none()) {
1246 DEBUG(
dbgs() <<
"Removing undefined SubRange "
1251 UpdatedSubRanges =
true;
1255 if (UpdatedSubRanges)
1261 assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
1262 "Only expect virtual or physical registers in remat");
1265 CopyDstReg,
true ,
true ,
false ));
1282 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1285 if (
LiveRange *LR = LIS->getCachedRegUnit(*Units))
1286 LR->createDeadDef(NewMIIdx.
getRegSlot(), LIS->getVNInfoAllocator());
1296 SlotIndex NewMIIdx = LIS->getInstructionIndex(NewMI);
1297 for (
unsigned i = 0, e = NewMIImplDefs.
size(); i != e; ++i) {
1298 unsigned Reg = NewMIImplDefs[i];
1300 if (
LiveRange *LR = LIS->getCachedRegUnit(*Units))
1301 LR->createDeadDef(NewMIIdx.
getRegSlot(), LIS->getVNInfoAllocator());
1308 shrinkToUses(&SrcInt, &DeadDefs);
1309 if (!DeadDefs.empty()) {
1316 DEBUG(
dbgs() <<
"\t\tupdated: " << *UseMI);
1319 eliminateDeadDefs();
1325 bool RegisterCoalescer::eliminateUndefCopy(
MachineInstr *CopyMI) {
1337 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
1338 isMoveInstr(*TRI, CopyMI, SrcReg, DstReg, SrcSubIdx, DstSubIdx);
1340 SlotIndex Idx = LIS->getInstructionIndex(*CopyMI);
1344 LaneBitmask SrcMask = TRI->getSubRegIndexLaneMask(SrcSubIdx);
1346 if ((SR.
LaneMask & SrcMask).none())
1351 }
else if (SrcLI.
liveAt(Idx))
1354 DEBUG(
dbgs() <<
"\tEliminating copy of <undef> value\n");
1365 LaneBitmask DstMask = TRI->getSubRegIndexLaneMask(DstSubIdx);
1367 if ((SR.
LaneMask & DstMask).none())
1371 assert(SVNI !=
nullptr && SlotIndex::isSameInstr(SVNI->
def, RegIndex));
1376 LIS->removeVRegDefAt(DstLI, RegIndex);
1383 SlotIndex UseIdx = LIS->getInstructionIndex(MI);
1389 if ((SR.
LaneMask & UseMask).none())
1397 isLive = DstLI.
liveAt(UseIdx);
1401 DEBUG(
dbgs() <<
"\tnew undef: " << UseIdx <<
'\t' << MI);
1412 LIS->shrinkToUses(&DstLI);
1419 LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubRegIdx);
1422 bool IsUndef =
true;
1424 if ((S.LaneMask & Mask).none())
1426 if (S.liveAt(UseIdx)) {
1439 ShrinkMainRange =
true;
1443 void RegisterCoalescer::updateRegDefsUses(
unsigned SrcReg,
1446 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
1447 LiveInterval *DstInt = DstIsPhys ?
nullptr : &LIS->getInterval(DstReg);
1449 if (DstInt && DstInt->
hasSubRanges() && DstReg != SrcReg) {
1452 if (SubReg == 0 || MO.
isUndef())
1458 addUndefFlag(*DstInt, UseIdx, MO, SubReg);
1464 I =
MRI->reg_instr_begin(SrcReg),
E =
MRI->reg_instr_end();
1473 if (SrcReg == DstReg && !Visited.
insert(UseMI).second)
1482 if (DstInt && !Reads && SubIdx && !UseMI->
isDebugValue())
1483 Reads = DstInt->
liveAt(LIS->getInstructionIndex(*UseMI));
1486 for (
unsigned i = 0, e = Ops.
size(); i != e; ++i) {
1492 if (SubIdx && MO.
isDef())
1497 if (SubIdx != 0 && MO.
isUse() &&
MRI->shouldTrackSubRegLiveness(DstReg)) {
1504 ? LIS->getSlotIndexes()->getIndexBefore(*UseMI)
1505 : LIS->getInstructionIndex(*UseMI);
1507 addUndefFlag(*DstInt, UseIdx, MO, SubIdx);
1517 dbgs() <<
"\t\tupdated: ";
1519 dbgs() << LIS->getInstructionIndex(*UseMI) <<
"\t";
1525 bool RegisterCoalescer::canJoinPhys(
const CoalescerPair &CP) {
1530 DEBUG(
dbgs() <<
"\tCan only merge into reserved registers.\n");
1538 DEBUG(
dbgs() <<
"\tCannot join complex intervals into reserved register.\n");
1542 bool RegisterCoalescer::joinCopy(
MachineInstr *CopyMI,
bool &Again) {
1545 DEBUG(
dbgs() << LIS->getInstructionIndex(*CopyMI) <<
'\t' << *CopyMI);
1549 DEBUG(
dbgs() <<
"\tNot coalescable.\n");
1562 if (!TRI->shouldCoalesce(CopyMI, SrcRC, SrcIdx, DstRC, DstIdx,
1564 DEBUG(
dbgs() <<
"\tSubtarget bailed on coalescing.\n");
1574 DeadDefs.push_back(CopyMI);
1575 eliminateDeadDefs();
1580 if (!CP.
isPhys() && eliminateUndefCopy(CopyMI)) {
1581 LIS->RemoveMachineInstrFromMaps(*CopyMI);
1591 DEBUG(
dbgs() <<
"\tCopy already coalesced: " << LI <<
'\n');
1592 const SlotIndex CopyIdx = LIS->getInstructionIndex(*CopyMI);
1596 assert(ReadVNI &&
"No value before copy and no <undef> flag.");
1597 assert(ReadVNI != DefVNI &&
"Cannot read and define the same value.");
1605 S.MergeValueNumberInto(SDefVNI, SReadVNI);
1608 DEBUG(
dbgs() <<
"\tMerged values: " << LI <<
'\n');
1610 LIS->RemoveMachineInstrFromMaps(*CopyMI);
1620 if (!canJoinPhys(CP)) {
1624 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1633 LIS->getInterval(CP.
getDstReg()).size())
1637 dbgs() <<
"\tConsidering merging to "
1638 << TRI->getRegClassName(CP.
getNewRC()) <<
" with ";
1641 << TRI->getSubRegIndexName(CP.
getDstIdx()) <<
" and "
1643 << TRI->getSubRegIndexName(CP.
getSrcIdx()) <<
'\n';
1650 ShrinkMask = LaneBitmask::getNone();
1651 ShrinkMainRange =
false;
1657 if (!joinIntervals(CP)) {
1663 if (reMaterializeTrivialDef(CP, CopyMI, IsDefCopy))
1669 if (adjustCopiesBackFrom(CP, CopyMI) ||
1670 removeCopyByCommutingDef(CP, CopyMI)) {
1671 LIS->RemoveMachineInstrFromMaps(*CopyMI);
1681 if (removePartialRedundancy(CP, *CopyMI))
1699 if (!CP.
isPhys() && RegClassInfo.isProperSubClass(CP.
getNewRC()))
1705 ErasedInstrs.erase(CopyMI);
1714 if (ShrinkMask.any()) {
1717 if ((S.LaneMask & ShrinkMask).none())
1721 LIS->shrinkToUses(S, LI.
reg);
1725 if (ShrinkMainRange) {
1740 dbgs() <<
"\tResult = ";
1752 bool RegisterCoalescer::joinReservedPhysReg(
CoalescerPair &CP) {
1756 assert(
MRI->isReserved(DstReg) &&
"Not a reserved register");
1758 DEBUG(
dbgs() <<
"\t\tRHS = " << RHS <<
'\n');
1760 assert(RHS.containsOneValue() &&
"Invalid join with reserved register");
1769 if (!
MRI->isConstantPhysReg(DstReg)) {
1773 if (!
MRI->isReserved(*RI))
1776 if (RHS.overlaps(LIS->getRegUnit(*UI))) {
1784 if (LIS->checkRegMaskInterference(RHS, RegMaskUsable) &&
1785 !RegMaskUsable.
test(DstReg)) {
1786 DEBUG(
dbgs() <<
"\t\tRegMask interference\n");
1806 CopyMI =
MRI->getVRegDef(SrcReg);
1815 if (!
MRI->hasOneNonDBGUse(SrcReg)) {
1816 DEBUG(
dbgs() <<
"\t\tMultiple vreg uses!\n");
1820 if (!LIS->intervalIsInOneMBB(RHS)) {
1821 DEBUG(
dbgs() <<
"\t\tComplex control flow!\n");
1826 CopyMI = &*
MRI->use_instr_nodbg_begin(SrcReg);
1830 if (!
MRI->isConstantPhysReg(DstReg)) {
1839 DEBUG(
dbgs() <<
"\t\tInterference (read): " << *MI);
1848 <<
" at " << CopyRegIdx <<
"\n");
1850 LIS->removePhysRegDefAt(DstReg, CopyRegIdx);
1858 LIS->RemoveMachineInstrFromMaps(*CopyMI);
1945 const unsigned SubIdx;
1952 const bool SubRangeJoin;
1954 const bool TrackSubRegLiveness;
1969 enum ConflictResolution {
2000 ConflictResolution Resolution;
2026 bool ErasableImplicitDef;
2033 bool PrunedComputed;
2035 Val() : Resolution(CR_Keep), WriteLanes(), ValidLanes(),
2036 RedefVNI(nullptr), OtherVNI(nullptr), ErasableImplicitDef(
false),
2039 bool isAnalyzed()
const {
return WriteLanes.any(); }
2051 std::pair<const VNInfo*,unsigned> followCopyChain(
const VNInfo *VNI)
const;
2062 ConflictResolution analyzeValue(
unsigned ValNo, JoinVals &
Other);
2067 void computeAssignment(
unsigned ValNo, JoinVals &
Other);
2084 bool taintExtent(
unsigned,
LaneBitmask, JoinVals&,
2097 bool isPrunedValue(
unsigned ValNo, JoinVals &
Other);
2103 bool TrackSubRegLiveness)
2104 : LR(LR), Reg(Reg), SubIdx(SubIdx), LaneMask(LaneMask),
2105 SubRangeJoin(SubRangeJoin), TrackSubRegLiveness(TrackSubRegLiveness),
2106 NewVNInfo(newVNInfo), CP(cp), LIS(lis), Indexes(LIS->getSlotIndexes()),
2107 TRI(TRI), Assignments(LR.getNumValNums(), -1), Vals(LR.getNumValNums())
2112 bool mapValues(JoinVals &
Other);
2116 bool resolveConflicts(JoinVals &
Other);
2136 void pruneMainSegments(
LiveInterval &LI,
bool &ShrinkMainRange);
2147 void removeImplicitDefs();
2150 const int *getAssignments()
const {
return Assignments.data(); }
2160 L |= TRI->getSubRegIndexLaneMask(
2161 TRI->composeSubRegIndices(SubIdx, MO.
getSubReg()));
2168 std::pair<const VNInfo*, unsigned> JoinVals::followCopyChain(
2169 const VNInfo *VNI)
const {
2170 unsigned Reg = this->
Reg;
2175 assert(MI &&
"No defining instruction");
2177 return std::make_pair(VNI, Reg);
2179 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
2180 return std::make_pair(VNI, Reg);
2193 LaneBitmask SMask = TRI->composeSubRegIndexLaneMask(SubIdx, S.LaneMask);
2194 if ((SMask & LaneMask).none())
2201 if (ValueIn ==
nullptr)
2206 return std::make_pair(VNI, Reg);
2209 bool JoinVals::valuesIdentical(
VNInfo *Value0,
VNInfo *Value1,
2210 const JoinVals &
Other)
const {
2213 std::tie(Orig0, Reg0) = followCopyChain(Value0);
2214 if (Orig0 == Value1)
2219 std::tie(Orig1, Reg1) = Other.followCopyChain(Value1);
2225 return Orig0->
def == Orig1->
def && Reg0 == Reg1;
2228 JoinVals::ConflictResolution
2229 JoinVals::analyzeValue(
unsigned ValNo, JoinVals &Other) {
2230 Val &V = Vals[ValNo];
2231 assert(!V.isAnalyzed() &&
"Value has already been analyzed!");
2233 if (VNI->isUnused()) {
2234 V.WriteLanes = LaneBitmask::getAll();
2240 if (VNI->isPHIDef()) {
2243 : TRI->getSubRegIndexLaneMask(SubIdx);
2244 V.ValidLanes = V.WriteLanes = Lanes;
2247 assert(DefMI !=
nullptr);
2252 V.ValidLanes = LaneBitmask::getNone();
2253 V.ErasableImplicitDef =
true;
2257 V.ValidLanes = V.WriteLanes = computeWriteLanes(DefMI, Redef);
2276 assert((TrackSubRegLiveness || V.RedefVNI) &&
2277 "Instruction is reading nonexistent value");
2278 if (V.RedefVNI !=
nullptr) {
2279 computeAssignment(V.RedefVNI->id, Other);
2280 V.ValidLanes |= Vals[V.RedefVNI->id].ValidLanes;
2289 V.ErasableImplicitDef =
true;
2290 V.ValidLanes &= ~V.WriteLanes;
2303 assert(SlotIndex::isSameInstr(VNI->def, OtherVNI->def) &&
"Broken LRQ");
2307 if (OtherVNI->def < VNI->def)
2308 Other.computeAssignment(OtherVNI->id, *
this);
2309 else if (VNI->def < OtherVNI->def && OtherLRQ.
valueIn()) {
2312 V.OtherVNI = OtherLRQ.
valueIn();
2313 return CR_Impossible;
2315 V.OtherVNI = OtherVNI;
2316 Val &OtherV = Other.Vals[OtherVNI->id];
2318 if (!OtherV.isAnalyzed())
2323 if (VNI->isPHIDef())
2325 if ((V.ValidLanes & OtherV.ValidLanes).any())
2327 return CR_Impossible;
2333 V.OtherVNI = OtherLRQ.
valueIn();
2338 assert(!SlotIndex::isSameInstr(VNI->def, V.OtherVNI->def) &&
"Broken LRQ");
2342 Other.computeAssignment(V.OtherVNI->id, *
this);
2343 Val &OtherV = Other.Vals[V.OtherVNI->id];
2352 if (OtherV.ErasableImplicitDef && DefMI &&
2354 DEBUG(
dbgs() <<
"IMPLICIT_DEF defined at " << V.OtherVNI->def
2356 <<
", keeping it.\n");
2357 OtherV.ErasableImplicitDef =
false;
2362 if (VNI->isPHIDef())
2369 if (TrackSubRegLiveness
2370 && (V.WriteLanes & (OtherV.ValidLanes | OtherV.WriteLanes)).none())
2380 V.ValidLanes &= ~V.WriteLanes | OtherV.ValidLanes;
2395 && valuesIdentical(VNI, V.OtherVNI, Other))
2410 if ((V.WriteLanes & OtherV.ValidLanes).none())
2422 assert(VNI->def.isEarlyClobber() &&
2423 "Only early clobber defs can overlap a kill");
2424 return CR_Impossible;
2431 if ((TRI->getSubRegIndexLaneMask(Other.SubIdx) & ~V.WriteLanes).none())
2432 return CR_Impossible;
2439 return CR_Impossible;
2448 return CR_Unresolved;
2451 void JoinVals::computeAssignment(
unsigned ValNo, JoinVals &Other) {
2452 Val &V = Vals[ValNo];
2453 if (V.isAnalyzed()) {
2456 assert(Assignments[ValNo] != -1 &&
"Bad recursion?");
2459 switch ((V.Resolution = analyzeValue(ValNo, Other))) {
2463 assert(V.OtherVNI &&
"OtherVNI not assigned, can't merge.");
2464 assert(Other.Vals[V.OtherVNI->id].isAnalyzed() &&
"Missing recursion");
2465 Assignments[ValNo] = Other.Assignments[V.OtherVNI->id];
2468 <<
PrintReg(Other.Reg) <<
':' << V.OtherVNI->id <<
'@'
2469 << V.OtherVNI->def <<
" --> @"
2470 << NewVNInfo[Assignments[ValNo]]->def <<
'\n');
2473 case CR_Unresolved: {
2475 assert(V.OtherVNI &&
"OtherVNI not assigned, can't prune");
2476 Val &OtherV = Other.Vals[V.OtherVNI->id];
2479 if ((OtherV.WriteLanes & ~V.ValidLanes).any() && TrackSubRegLiveness)
2480 OtherV.ErasableImplicitDef =
false;
2481 OtherV.Pruned =
true;
2486 Assignments[ValNo] = NewVNInfo.size();
2492 bool JoinVals::mapValues(JoinVals &Other) {
2494 computeAssignment(i, Other);
2495 if (Vals[i].Resolution == CR_Impossible) {
2505 taintExtent(
unsigned ValNo,
LaneBitmask TaintedLanes, JoinVals &Other,
2512 LiveInterval::iterator OtherI = Other.LR.find(VNI->
def);
2513 assert(OtherI != Other.LR.end() &&
"No conflict?");
2518 if (End >= MBBEnd) {
2520 << OtherI->valno->id <<
'@' << OtherI->start <<
'\n');
2524 << OtherI->valno->id <<
'@' << OtherI->start
2525 <<
" to " << End <<
'\n');
2529 TaintExtent.push_back(std::make_pair(End, TaintedLanes));
2532 if (++OtherI == Other.LR.end() || OtherI->start >= MBBEnd)
2536 const Val &OV = Other.Vals[OtherI->valno->id];
2537 TaintedLanes &= ~OV.WriteLanes;
2540 }
while (TaintedLanes.
any());
2544 bool JoinVals::usesLanes(
const MachineInstr &MI,
unsigned Reg,
unsigned SubIdx,
2553 unsigned S = TRI->composeSubRegIndices(SubIdx, MO.
getSubReg());
2554 if ((Lanes & TRI->getSubRegIndexLaneMask(S)).any())
2560 bool JoinVals::resolveConflicts(JoinVals &Other) {
2563 assert (V.Resolution != CR_Impossible &&
"Unresolvable conflict");
2564 if (V.Resolution != CR_Unresolved)
2572 assert(V.OtherVNI &&
"Inconsistent conflict resolution.");
2574 const Val &OtherV = Other.Vals[V.OtherVNI->id];
2579 LaneBitmask TaintedLanes = V.WriteLanes & OtherV.ValidLanes;
2581 if (!taintExtent(i, TaintedLanes, Other, TaintExtent))
2585 assert(!TaintExtent.
empty() &&
"There should be at least one conflict.");
2595 assert(!SlotIndex::isSameInstr(VNI->
def, TaintExtent.
front().first) &&
2596 "Interference ends on VNI->def. Should have been handled earlier");
2599 assert(LastMI &&
"Range must end at a proper instruction");
2600 unsigned TaintNum = 0;
2602 assert(MI != MBB->end() &&
"Bad LastMI");
2603 if (usesLanes(*MI, Other.Reg, Other.SubIdx, TaintedLanes)) {
2604 DEBUG(
dbgs() <<
"\t\ttainted lanes used by: " << *MI);
2608 if (&*MI == LastMI) {
2609 if (++TaintNum == TaintExtent.
size())
2612 assert(LastMI &&
"Range must end at a proper instruction");
2613 TaintedLanes = TaintExtent[TaintNum].second;
2619 V.Resolution = CR_Replace;
2625 bool JoinVals::isPrunedValue(
unsigned ValNo, JoinVals &Other) {
2626 Val &V = Vals[ValNo];
2627 if (V.Pruned || V.PrunedComputed)
2630 if (V.Resolution != CR_Erase && V.Resolution != CR_Merge)
2635 V.PrunedComputed =
true;
2636 V.Pruned = Other.isPrunedValue(V.OtherVNI->id, *
this);
2640 void JoinVals::pruneValues(JoinVals &Other,
2642 bool changeInstrs) {
2645 switch (Vals[i].Resolution) {
2650 LIS->pruneValue(Other.LR, Def, &EndPoints);
2655 Val &OtherV = Other.Vals[Vals[i].OtherVNI->id];
2656 bool EraseImpDef = OtherV.ErasableImplicitDef &&
2657 OtherV.Resolution == CR_Keep;
2678 <<
": " << Other.LR <<
'\n');
2683 if (isPrunedValue(i, Other)) {
2688 LIS->pruneValue(LR, Def, &EndPoints);
2690 << Def <<
": " << LR <<
'\n');
2702 bool DidPrune =
false;
2706 if (Vals[i].Resolution != CR_Erase &&
2707 (Vals[i].Resolution != CR_Keep || !Vals[i].ErasableImplicitDef ||
2714 DEBUG(
dbgs() <<
"\t\tExpecting instruction removal at " << Def <<
'\n');
2721 if (ValueOut !=
nullptr && Q.
valueIn() ==
nullptr) {
2723 <<
" at " << Def <<
"\n");
2724 LIS->pruneValue(S, Def,
nullptr);
2734 <<
" at " << Def <<
"\n");
2735 ShrinkMask |= S.LaneMask;
2747 if (VNI->
def == Def)
2753 void JoinVals::pruneMainSegments(
LiveInterval &LI,
bool &ShrinkMainRange) {
2754 assert(&static_cast<LiveRange&>(LI) == &LR);
2757 if (Vals[i].Resolution != CR_Keep)
2762 Vals[i].Pruned =
true;
2763 ShrinkMainRange =
true;
2767 void JoinVals::removeImplicitDefs() {
2770 if (V.Resolution != CR_Keep || !V.ErasableImplicitDef || !V.Pruned)
2785 switch (Vals[i].Resolution) {
2790 if (!Vals[i].ErasableImplicitDef || !Vals[i].Pruned)
2804 if (LI !=
nullptr) {
2819 assert(static_cast<LiveRange*>(LI) == &LR);
2842 if (S != LR.
begin())
2843 std::prev(S)->end = NewEnd;
2847 dbgs() <<
"\t\tremoved " << i <<
'@' << Def <<
": " << LR <<
'\n';
2849 dbgs() <<
"\t\t LHS = " << *LI <<
'\n';
2856 assert(MI &&
"No instruction to erase");
2859 if (TargetRegisterInfo::isVirtualRegister(Reg) &&
2864 DEBUG(
dbgs() <<
"\t\terased:\t" << Def <<
'\t' << *MI);
2865 LIS->RemoveMachineInstrFromMaps(*MI);
2880 NewVNInfo,
CP, LIS, TRI,
true,
true);
2881 JoinVals LHSVals(LRange, CP.getDstReg(), CP.getDstIdx(), LaneMask,
2882 NewVNInfo,
CP, LIS, TRI,
true,
true);
2889 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals)) {
2894 if (!LHSVals.resolveConflicts(RHSVals) ||
2895 !RHSVals.resolveConflicts(LHSVals)) {
2906 LHSVals.pruneValues(RHSVals, EndPoints,
false);
2907 RHSVals.pruneValues(LHSVals, EndPoints,
false);
2909 LHSVals.removeImplicitDefs();
2910 RHSVals.removeImplicitDefs();
2916 LRange.
join(RRange, LHSVals.getAssignments(), RHSVals.getAssignments(),
2919 DEBUG(
dbgs() <<
"\t\tjoined lanes: " << LRange <<
"\n");
2920 if (EndPoints.
empty())
2926 dbgs() <<
"\t\trestoring liveness to " << EndPoints.
size() <<
" points: ";
2927 for (
unsigned i = 0, n = EndPoints.
size(); i != n; ++i) {
2928 dbgs() << EndPoints[i];
2932 dbgs() <<
": " << LRange <<
'\n';
2934 LIS->extendToIndices(LRange, EndPoints);
2937 void RegisterCoalescer::mergeSubRangeInto(
LiveInterval &LI,
2945 SR.
assign(ToMerge, Allocator);
2948 LiveRange RangeCopy(ToMerge, Allocator);
2949 joinSubRegRanges(SR, RangeCopy, SR.
LaneMask, CP);
2958 bool TrackSubRegLiveness =
MRI->shouldTrackSubRegLiveness(*CP.
getNewRC());
2960 NewVNInfo,
CP, LIS, TRI,
false, TrackSubRegLiveness);
2961 JoinVals LHSVals(LHS, CP.getDstReg(), CP.getDstIdx(), LaneBitmask::getNone(),
2962 NewVNInfo,
CP, LIS, TRI,
false, TrackSubRegLiveness);
2965 <<
"\n\t\tLHS = " << LHS
2970 if (!LHSVals.mapValues(RHSVals) || !RHSVals.mapValues(LHSVals))
2974 if (!LHSVals.resolveConflicts(RHSVals) || !RHSVals.resolveConflicts(LHSVals))
2983 unsigned DstIdx = CP.getDstIdx();
2985 LaneBitmask Mask = DstIdx == 0 ? CP.getNewRC()->getLaneMask()
2986 : TRI->getSubRegIndexLaneMask(DstIdx);
2990 }
else if (DstIdx != 0) {
2993 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(DstIdx, R.LaneMask);
2998 <<
' ' << LHS <<
'\n');
3001 unsigned SrcIdx = CP.getSrcIdx();
3003 LaneBitmask Mask = SrcIdx == 0 ? CP.getNewRC()->getLaneMask()
3004 : TRI->getSubRegIndexLaneMask(SrcIdx);
3005 mergeSubRangeInto(LHS, RHS, Mask, CP);
3009 LaneBitmask Mask = TRI->composeSubRegIndexLaneMask(SrcIdx, R.LaneMask);
3010 mergeSubRangeInto(LHS, R, Mask, CP);
3013 DEBUG(
dbgs() <<
"\tJoined SubRanges " << LHS <<
"\n");
3017 LHSVals.pruneMainSegments(LHS, ShrinkMainRange);
3019 LHSVals.pruneSubRegValues(LHS, ShrinkMask);
3020 RHSVals.pruneSubRegValues(LHS, ShrinkMask);
3028 LHSVals.pruneValues(RHSVals, EndPoints,
true);
3029 RHSVals.pruneValues(LHSVals, EndPoints,
true);
3034 LHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs, &LHS);
3035 RHSVals.eraseInstrs(ErasedInstrs, ShrinkRegs);
3036 while (!ShrinkRegs.
empty())
3037 shrinkToUses(&LIS->getInterval(ShrinkRegs.
pop_back_val()));
3040 LHS.
join(RHS, LHSVals.getAssignments(), RHSVals.getAssignments(), NewVNInfo);
3045 MRI->clearKillFlags(LHS.
reg);
3046 MRI->clearKillFlags(RHS.
reg);
3048 if (!EndPoints.
empty()) {
3052 dbgs() <<
"\t\trestoring liveness to " << EndPoints.
size() <<
" points: ";
3053 for (
unsigned i = 0, n = EndPoints.
size(); i != n; ++i) {
3054 dbgs() << EndPoints[i];
3058 dbgs() <<
": " << LHS <<
'\n';
3060 LIS->extendToIndices((
LiveRange&)LHS, EndPoints);
3067 return CP.
isPhys() ? joinReservedPhysReg(CP) : joinVirtRegs(CP);
3072 struct MBBPriorityInfo {
3078 : MBB(mbb),
Depth(depth), IsSplit(issplit) {}
3087 const MBBPriorityInfo *RHS) {
3089 if (LHS->Depth != RHS->Depth)
3090 return LHS->Depth > RHS->Depth ? -1 : 1;
3093 if (LHS->IsSplit != RHS->IsSplit)
3094 return LHS->IsSplit ? -1 : 1;
3098 unsigned cl = LHS->MBB->pred_size() + LHS->MBB->succ_size();
3099 unsigned cr = RHS->MBB->pred_size() + RHS->MBB->succ_size();
3101 return cl > cr ? -1 : 1;
3104 return LHS->MBB->getNumber() < RHS->MBB->getNumber() ? -1 : 1;
3117 if (TargetRegisterInfo::isPhysicalRegister(SrcReg)
3118 || TargetRegisterInfo::isPhysicalRegister(DstReg))
3125 bool RegisterCoalescer::
3127 bool Progress =
false;
3128 for (
unsigned i = 0, e = CurrList.
size(); i != e; ++i) {
3133 if (ErasedInstrs.
count(CurrList[i])) {
3134 CurrList[i] =
nullptr;
3138 bool Success = joinCopy(CurrList[i], Again);
3140 if (Success || !Again)
3141 CurrList[i] =
nullptr;
3158 bool RegisterCoalescer::applyTerminalRule(
const MachineInstr &Copy)
const {
3162 unsigned DstReg, DstSubReg, SrcReg, SrcSubReg;
3163 isMoveInstr(*TRI, &Copy, SrcReg, DstReg, SrcSubReg, DstSubReg);
3165 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
3169 TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
3186 unsigned OtherReg, OtherSubReg, OtherSrcReg, OtherSrcSubReg;
3187 isMoveInstr(*TRI, &Copy, OtherSrcReg, OtherReg, OtherSrcSubReg,
3189 if (OtherReg == SrcReg)
3190 OtherReg = OtherSrcReg;
3192 if (TargetRegisterInfo::isPhysicalRegister(OtherReg) ||
3196 if (LIS->getInterval(OtherReg).overlaps(DstLI)) {
3210 const unsigned PrevSize = WorkList.size();
3211 if (JoinGlobalCopies) {
3220 if (!MII->isCopyLike())
3222 bool ApplyTerminalRule = applyTerminalRule(*MII);
3224 if (ApplyTerminalRule)
3227 LocalWorkList.push_back(&(*MII));
3229 if (ApplyTerminalRule)
3232 WorkList.push_back(&(*MII));
3236 LocalWorkList.append(LocalTerminals.
begin(), LocalTerminals.
end());
3237 WorkList.append(GlobalTerminals.
begin(), GlobalTerminals.
end());
3242 if (MII.isCopyLike()) {
3243 if (applyTerminalRule(MII))
3246 WorkList.push_back(&MII);
3249 WorkList.append(Terminals.
begin(), Terminals.
end());
3255 CurrList(WorkList.begin() + PrevSize, WorkList.end());
3256 if (copyCoalesceWorkList(CurrList))
3257 WorkList.erase(
std::remove(WorkList.begin() + PrevSize, WorkList.end(),
3258 nullptr), WorkList.end());
3261 void RegisterCoalescer::coalesceLocals() {
3262 copyCoalesceWorkList(LocalWorkList);
3263 for (
unsigned j = 0, je = LocalWorkList.size(); j != je; ++j) {
3264 if (LocalWorkList[j])
3265 WorkList.push_back(LocalWorkList[j]);
3267 LocalWorkList.clear();
3270 void RegisterCoalescer::joinAllIntervals() {
3271 DEBUG(
dbgs() <<
"********** JOINING INTERVALS ***********\n");
3272 assert(WorkList.empty() && LocalWorkList.empty() &&
"Old data still around.");
3274 std::vector<MBBPriorityInfo> MBBs;
3275 MBBs.reserve(MF->size());
3278 MBBs.push_back(MBBPriorityInfo(MBB,
Loops->getLoopDepth(MBB),
3284 unsigned CurrDepth = UINT_MAX;
3285 for (
unsigned i = 0, e = MBBs.size(); i != e; ++i) {
3287 if (JoinGlobalCopies && MBBs[i].
Depth < CurrDepth) {
3289 CurrDepth = MBBs[i].Depth;
3291 copyCoalesceInMBB(MBBs[i].MBB);
3297 while (copyCoalesceWorkList(WorkList))
3301 void RegisterCoalescer::releaseMemory() {
3302 ErasedInstrs.
clear();
3305 InflateRegs.clear();
3315 LIS = &getAnalysis<LiveIntervals>();
3316 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3317 Loops = &getAnalysis<MachineLoopInfo>();
3328 DEBUG(
dbgs() <<
"********** SIMPLE REGISTER COALESCING **********\n"
3329 <<
"********** Function: " << MF->getName() <<
'\n');
3332 MF->verify(
this,
"Before register coalescing");
3334 RegClassInfo.runOnMachineFunction(fn);
3344 InflateRegs.erase(std::unique(InflateRegs.begin(), InflateRegs.end()),
3346 DEBUG(
dbgs() <<
"Trying to inflate " << InflateRegs.size() <<
" regs.\n");
3347 for (
unsigned i = 0, e = InflateRegs.size(); i != e; ++i) {
3348 unsigned Reg = InflateRegs[i];
3349 if (
MRI->reg_nodbg_empty(Reg))
3351 if (
MRI->recomputeRegClass(Reg)) {
3353 << TRI->getRegClassName(
MRI->getRegClass(Reg)) <<
'\n');
3360 if (!
MRI->shouldTrackSubRegLiveness(Reg)) {
3368 assert((S.LaneMask & ~MaxMask).none());
3378 MF->verify(
this,
"After register coalescing");
unsigned succ_size() const
static bool isSplitEdge(const MachineBasicBlock *MBB)
Return true if this block should be vacated by the coalescer to eliminate branches.
void push_back(const T &Elt)
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
bool isEHPad() const
Returns true if the block is a landing pad.
const_iterator end(StringRef path)
Get end iterator over path.
bool isValid() const
Check if the iterator is at the end of the list.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
void refineSubRanges(BumpPtrAllocator &Allocator, LaneBitmask LaneMask, std::function< void(LiveInterval::SubRange &)> Mod)
Refines the subranges to support LaneMask.
SlotIndex def
The index of the defining instruction.
unsigned getDstReg() const
Return the register (virtual or physical) that will remain after coalescing.
STATISTIC(NumFunctions,"Total number of functions")
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
A Module instance is used to store all the information related to an LLVM module. ...
INITIALIZE_PASS_BEGIN(RegisterCoalescer,"simple-register-coalescing","Simple Register Coalescing", false, false) INITIALIZE_PASS_END(RegisterCoalescer
static cl::opt< bool > VerifyCoalescing("verify-coalescing", cl::desc("Verify machine instrs before and after register coalescing"), cl::Hidden)
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
Segments::iterator iterator
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
LiveInterval - This class represents the liveness of a register, or stack slot.
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Describe properties that are true of each instruction in the target description file.
void setIsUndef(bool Val=true)
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
static bool isMoveInstr(const TargetRegisterInfo &tri, const MachineInstr *MI, unsigned &Src, unsigned &Dst, unsigned &SrcSub, unsigned &DstSub)
static bool isLocalCopy(MachineInstr *Copy, const LiveIntervals *LIS)
static bool definesFullReg(const MachineInstr &MI, unsigned Reg)
Returns true if MI defines the full vreg Reg, as opposed to just defining a subregister.
char & RegisterCoalescerID
RegisterCoalescer - This pass merges live ranges to eliminate copies.
bool isKill() const
Return true if the live-in value is killed by this instruction.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
A live range for subregisters.
static void dump(StringRef Title, SpillInfo const &Spills)
This represents a simple continuous liveness interval for a value.
void setIsDead(bool Val=true)
SlotIndex endPoint() const
Return the end point of the last live range segment to interact with the instruction, if any.
void markUnused()
Mark this value as unused.
void reserve(size_type N)
SubRange * createSubRangeFrom(BumpPtrAllocator &Allocator, LaneBitmask LaneMask, const LiveRange &CopyFrom)
Like createSubRange() but the new range is filled with a copy of the liveness information in CopyFrom...
VNInfo - Value Number Information.
iterator_range< mop_iterator > operands()
void substVirtReg(unsigned Reg, unsigned SubIdx, const TargetRegisterInfo &)
substVirtReg - Substitute the current register with the virtual subregister Reg:SubReg.
unsigned getNumValNums() const
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
Callback methods for LiveRangeEdit owners.
void initializeRegisterCoalescerPass(PassRegistry &)
bool allDefsAreDead() const
Return true if all the defs of this instruction are dead.
This class represents the liveness of a register, stack slot, etc.
static bool isDefInSubRange(LiveInterval &LI, SlotIndex Def)
Check if any of the subranges of LI contain a definition at Def.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
void removeEmptySubRanges()
Removes all subranges without any segments (subranges without segments are not considered valid and s...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isCrossClass() const
Return true if DstReg is virtual and NewRC is a smaller register class than DstReg's.
MachineBasicBlock * intervalIsInOneMBB(const LiveInterval &LI) const
If LI is confined to a single basic block, return a pointer to that block.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
bool isFlipped() const
Return true when getSrcReg is the register being defined by the original copy instruction.
A helper class for register coalescers.
std::pair< bool, bool > readsWritesVirtualRegister(unsigned Reg, SmallVectorImpl< unsigned > *Ops=nullptr) const
Return a pair of bools (reads, writes) indicating if this instruction reads or writes Reg...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
iterator_range< subrange_iterator > subranges()
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Result of a LiveRange query.
static cl::opt< bool > EnableJoinSplits("join-splitedges", cl::desc("Coalesce copies on split edges (default=subtarget)"), cl::Hidden)
Temporary flag to test critical edge unsplitting.
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
Reg
All possible values of the reg field in the ModR/M byte.
iterator_range< reg_instr_nodbg_iterator > reg_nodbg_instructions(unsigned Reg) const
bool isBlock() const
isBlock - Returns true if this is a block boundary slot.
constexpr bool any() const
LLVM_NODISCARD bool empty() const
unsigned getNumOperands() const
Access to explicit operands of the instruction.
bool isUnused() const
Returns true if this value is unused.
SlotIndex getNextNonNullIndex(SlotIndex Index)
Returns the next non-null index, if one exists.
defusechain_iterator - This class provides iterator support for machine operands in the function that...
virtual bool enableJoinGlobalCopies() const
True if the subtarget should enable joining global copies.
bool isDead() const
isDead - Returns true if this is a dead def kill slot.
iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
MCRegUnitRootIterator enumerates the root registers of a register unit.
VNInfo * MergeValueNumberInto(VNInfo *V1, VNInfo *V2)
MergeValueNumberInto - This method is called when two value numbers are found to be equivalent...
unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx, const TargetRegisterClass *RC) const
Return a super-register of the specified register Reg so its sub-register of index SubIdx is Reg...
VNInfo * valueOutOrDead() const
Returns the value alive at the end of the instruction, if any.
bool isCopyLike() const
Return true if the instruction behaves like a copy.
virtual const TargetRegisterClass * getMatchingSuperRegClass(const TargetRegisterClass *A, const TargetRegisterClass *B, unsigned Idx) const
Return a subclass of the specified register class A so that each register in it has a sub-register of...
AnalysisUsage & addPreservedID(const void *ID)
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
Printable PrintReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubRegIdx=0)
Prints virtual and physical registers with or without a TRI instance.
size_t size() const
size - Get the array size.
bool setRegisters(const MachineInstr *)
Set registers to match the copy instruction MI.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
const MachineBasicBlock * getParent() const
TargetInstrInfo - Interface to description of machine instruction set.
bool isDebugValue() const
bool isImplicitDef() const
const TargetRegisterClass * getCommonSuperRegClass(const TargetRegisterClass *RCA, unsigned SubA, const TargetRegisterClass *RCB, unsigned SubB, unsigned &PreA, unsigned &PreB) const
Find a common super-register class if it exists.
bool isEarlyClobber() const
static const unsigned CommuteAnyOperandIndex
void removeValNo(VNInfo *ValNo)
removeValNo - Remove all the segments defined by the specified value#.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
const TargetRegisterClass * getNewRC() const
Return the register class of the coalesced register.
initializer< Ty > init(const Ty &Val)
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
bool isValid() const
Returns true if this is a valid index.
SubRange * createSubRange(BumpPtrAllocator &Allocator, LaneBitmask LaneMask)
Creates a new empty subregister live range.
unsigned const MachineRegisterInfo * MRI
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
static int compareMBBPriority(const MBBPriorityInfo *LHS, const MBBPriorityInfo *RHS)
C-style comparator that sorts first based on the loop depth of the basic block (the unsigned)...
Allocate memory in an ever growing pool, as if by bump-pointer.
MachineInstrBuilder & UseMI
static void addSegmentsWithValNo(LiveRange &Dst, VNInfo *DstValNo, const LiveRange &Src, const VNInfo *SrcValNo)
Copy segements with value number SrcValNo from liverange Src to live range and use value number DstV...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
int findRegisterDefOperandIdx(unsigned Reg, bool isDead=false, bool Overlap=false, const TargetRegisterInfo *TRI=nullptr) const
Returns the operand index that is a def of the specified register or -1 if it is not found...
const MachineOperand & getOperand(unsigned i) const
unsigned getSubReg(unsigned Reg, unsigned Idx) const
Returns the physical register number of sub-register "Index" for physical register RegNo...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx=nullptr) const
Given the index of a register def operand, check if the register def is tied to a source operand...
void eliminateDeadDefs(SmallVectorImpl< MachineInstr * > &Dead, ArrayRef< unsigned > RegsBeingSpilled=None, AliasAnalysis *AA=nullptr)
eliminateDeadDefs - Try to delete machine instructions that are now dead (allDefsAreDead returns true...
bool overlaps(const LiveRange &other) const
overlaps - Return true if the intersection of the two live ranges is not empty.
Represent the analysis usage information of a pass.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static const unsigned End
void substPhysReg(unsigned Reg, const TargetRegisterInfo &)
substPhysReg - Substitute the current register with the physical register Reg, taking any existing Su...
VNInfo * valueDefined() const
Return the value defined by this instruction, if any.
static bool isTerminalReg(unsigned DstReg, const MachineInstr &Copy, const MachineRegisterInfo *MRI)
Check if DstReg is a terminal node.
iterator_range< pred_iterator > predecessors()
void verify() const
Walk the range and assert if any invariants fail to hold.
unsigned getSubReg() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool liveAt(SlotIndex index) const
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction for the given index, or null if the given index has no instruction associated...
static cl::opt< cl::boolOrDefault > EnableGlobalCopies("join-globalcopies", cl::desc("Coalesce copies that span blocks (default=subtarget)"), cl::init(cl::BOU_UNSET), cl::Hidden)
Temporary flag to test global copy optimization.
void setIsKill(bool Val=true)
static cl::opt< bool > EnableJoining("join-liveintervals", cl::desc("Coalesce copies (default=true)"), cl::init(true))
iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
VNInfo * valueOut() const
Return the value leaving the instruction, if any.
bool isSafeToMove(AliasAnalysis *AA, bool &SawStore) const
Return true if it is safe to move this instruction.
bool readsRegister(unsigned Reg, const TargetRegisterInfo *TRI=nullptr) const
Return true if the MachineInstr reads the specified register.
int findRegisterUseOperandIdx(unsigned Reg, bool isKill=false, const TargetRegisterInfo *TRI=nullptr) const
Returns the operand index that is a use of the specific register or -1 if it is not found...
Iterator for intrusive lists based on ilist_node.
Printable PrintRegUnit(unsigned Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
bool isPhys() const
Return true if DstReg is a physical register.
void substituteRegister(unsigned FromReg, unsigned ToReg, unsigned SubIdx, const TargetRegisterInfo &RegInfo)
Replace all occurrences of FromReg with ToReg:SubIdx, properly composing subreg indices where necessa...
void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
simple register Simple Register false
simple register coalescing
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool test(unsigned Idx) const
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
Returns the basic block which the given index falls in.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Promote Memory to Register
LLVM_NODISCARD T pop_back_val()
void setPreservesCFG()
This function should be called by the pass, iff they do not:
LiveInterval & getInterval(unsigned Reg)
bool isCoalescable(const MachineInstr *) const
Return true if MI is a copy instruction that will become an identity copy after coalescing.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void clearSubRanges()
Removes all subregister liveness information.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
SlotIndex getMBBEndIdx(unsigned Num) const
Returns the last index in the given basic block number.
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
void setDebugLoc(DebugLoc dl)
Replace current source information with new such.
unsigned getDstIdx() const
Return the subregister index that DstReg will be coalesced into, or 0.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
VNInfo * getValNumInfo(unsigned ValNo)
getValNumInfo - Returns pointer to the specified val#.
bool containsOneValue() const
llvm_unreachable("Unknown RegBank!")
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
TargetSubtargetInfo - Generic base class for all target subtargets.
unsigned getSrcIdx() const
Return the subregister index that SrcReg will be coalesced into, or 0.
Representation of each machine instruction.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
static cl::opt< bool > UseTerminalRule("terminal-rule", cl::desc("Apply the terminal rule"), cl::init(false), cl::Hidden)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void assign(const LiveRange &Other, BumpPtrAllocator &Allocator)
Copies values numbers and live segments from Other into this range.
VNInfo * createDeadDef(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
createDeadDef - Make sure the range has a value defined at Def.
void setReg(unsigned Reg)
Change the register this operand corresponds to.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
void setSubReg(unsigned subReg)
const TargetRegisterClass * getCommonSubClass(const TargetRegisterClass *A, const TargetRegisterClass *B, const MVT::SimpleValueType SVT=MVT::SimpleValueType::Any) const
Find the largest common subclass of A and B.
constexpr bool all() const
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
bool flip()
Swap SrcReg and DstReg.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def...
unsigned getReg() const
getReg - Returns the register number.
VNInfo * getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
bool isCommutable(QueryType Type=IgnoreBundle) const
Return true if this may be a 2- or 3-address instruction (of the form "X = op Y, Z, ..."), which produces the same result if Y and Z are exchanged.
bool isPartial() const
Return true if the original copy instruction did not copy the full register, but was a subreg operati...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
virtual const TargetInstrInfo * getInstrInfo() const
static LLVM_ATTRIBUTE_UNUSED Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
simple register Simple Register Coalescing
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
unsigned getSrcReg() const
Return the virtual register that will be coalesced away.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
This class implements an extremely fast bulk output stream that can only output to a stream...
Primary interface to the complete machine description for the target machine.
bool isRegTiedToDefOperand(unsigned UseOpIdx, unsigned *DefOpIdx=nullptr) const
Return true if the use operand of the specified index is tied to a def operand.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
unsigned composeSubRegIndices(unsigned a, unsigned b) const
Return the subregister index you get from composing two subregister indices.
void join(LiveRange &Other, const int *ValNoAssignments, const int *RHSValNoAssignments, SmallVectorImpl< VNInfo * > &NewVNInfo)
join - Join two live ranges (this, and other) together.
iterator FindSegmentContaining(SlotIndex Idx)
Return an iterator to the segment that contains the specified index, or end() if there is none...
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register. ...
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
bool hasSubRanges() const
Returns true if subregister liveness information is available.
SlotIndex - An opaque wrapper around machine indexes.
reg_begin/reg_end - Provide iteration support to walk over all definitions and uses of a register wit...
unsigned pred_size() const
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarilly including Idx...
bool contains(unsigned Reg) const
Return true if the specified register is included in this register class.