50 #include "llvm/Config/llvm-config.h" 73 #define DEBUG_TYPE "machine-scheduler" 78 cl::desc(
"Force top-down list scheduling"));
80 cl::desc(
"Force bottom-up list scheduling"));
83 cl::desc(
"Print critical path length to stdout"));
89 cl::desc(
"Pop up a window to show MISched dags after they are processed"));
94 cl::desc(
"Hide nodes with more predecessor/successor than cutoff"));
100 cl::desc(
"Only schedule this function"));
102 cl::desc(
"Only schedule this MBB#"));
104 static bool ViewMISchedDAGs =
false;
119 cl::desc(
"Enable memop clustering."),
123 cl::desc(
"Verify machine instrs before and after machine scheduling"));
129 void MachineSchedStrategy::anchor() {}
131 void ScheduleDAGMutation::anchor() {}
160 class MachineScheduler :
public MachineSchedulerBase {
175 class PostMachineScheduler :
public MachineSchedulerBase {
177 PostMachineScheduler();
196 "Machine Instruction Scheduler",
false,
false)
204 MachineScheduler::MachineScheduler() : MachineSchedulerBase(
ID) {
208 void MachineScheduler::getAnalysisUsage(
AnalysisUsage &AU)
const {
226 "PostRA Machine Instruction Scheduler",
false,
false)
228 PostMachineScheduler::PostMachineScheduler() : MachineSchedulerBase(
ID) {
232 void PostMachineScheduler::getAnalysisUsage(
AnalysisUsage &AU)
const {
253 cl::desc(
"Machine instruction scheduler to use"));
261 cl::desc(
"Enable the machine instruction scheduling pass."),
cl::init(
true),
265 "enable-post-misched",
266 cl::desc(
"Enable the post-ra machine instruction scheduling pass."),
273 assert(I != Beg &&
"reached the top of the region, cannot decrement");
275 if (!I->isDebugInstr())
294 for(; I != End; ++
I) {
295 if (!I->isDebugInstr())
359 if (!EnableMachineSched)
368 MLI = &getAnalysis<MachineLoopInfo>();
369 MDT = &getAnalysis<MachineDominatorTree>();
370 PassConfig = &getAnalysis<TargetPassConfig>();
371 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
373 LIS = &getAnalysis<LiveIntervals>();
375 if (VerifyScheduling) {
377 MF->verify(
this,
"Before machine scheduling.");
379 RegClassInfo->runOnMachineFunction(*MF);
383 std::unique_ptr<ScheduleDAGInstrs>
Scheduler(createMachineScheduler());
384 scheduleRegions(*Scheduler,
false);
387 if (VerifyScheduling)
388 MF->verify(
this,
"After machine scheduling.");
397 if (!EnablePostRAMachineSched)
407 MLI = &getAnalysis<MachineLoopInfo>();
408 PassConfig = &getAnalysis<TargetPassConfig>();
410 if (VerifyScheduling)
411 MF->
verify(
this,
"Before post machine scheduling.");
415 std::unique_ptr<ScheduleDAGInstrs>
Scheduler(createPostMachineScheduler());
416 scheduleRegions(*Scheduler,
true);
418 if (VerifyScheduling)
419 MF->verify(
this,
"After post machine scheduling.");
450 unsigned NumRegionInstrs;
454 RegionBegin(B), RegionEnd(E), NumRegionInstrs(N) {}
463 bool RegionsTopDown) {
469 RegionEnd != MBB->
begin(); RegionEnd =
I) {
472 if (RegionEnd != MBB->
end() ||
479 unsigned NumRegionInstrs = 0;
481 for (;I != MBB->
begin(); --
I) {
491 Regions.
push_back(SchedRegion(I, RegionEnd, NumRegionInstrs));
506 MBB != MBBEnd; ++MBB) {
514 && (int)SchedOnlyBlock != MBB->getNumber())
535 R != MBBRegions.
end(); ++R) {
538 unsigned NumRegionInstrs = R->NumRegionInstrs;
542 Scheduler.
enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
545 if (I == RegionEnd || I == std::prev(RegionEnd)) {
553 <<
" " << MBB->getName() <<
"\n From: " << *I
555 if (RegionEnd != MBB->end())
dbgs() << *RegionEnd;
556 else dbgs() <<
"End";
557 dbgs() <<
" RegionInstrs: " << NumRegionInstrs <<
'\n');
559 errs() << MF->getName();
560 errs() <<
":%bb. " << MBB->getNumber();
561 errs() <<
" " << MBB->getName() <<
" \n";
585 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 588 for (
const SUnit *SU : Queue)
589 dbgs() << SU->NodeNum <<
" ";
604 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
608 if (SuccSU != &ExitSU) {
611 if (Topo.IsReachable(PredDep.
getSUnit(), SuccSU))
613 Topo.AddPred(SuccSU, PredDep.
getSUnit());
630 NextClusterSucc = SuccSU;
635 dbgs() <<
"*** Scheduling failed! ***\n";
637 dbgs() <<
" has been released too many times!\n";
648 SchedImpl->releaseTopNode(SuccSU);
654 releaseSucc(SU, &Succ);
667 NextClusterPred = PredSU;
672 dbgs() <<
"*** Scheduling failed! ***\n";
674 dbgs() <<
" has been released too many times!\n";
685 SchedImpl->releaseBottomNode(PredSU);
691 releasePred(SU, &Pred);
696 SchedImpl->enterMBB(bb);
700 SchedImpl->leaveMBB();
711 unsigned regioninstrs)
715 SchedImpl->initPolicy(begin, end, regioninstrs);
723 if (&*RegionBegin == MI)
727 BB->splice(InsertPos, BB, MI);
731 LIS->handleMove(*MI,
true);
734 if (RegionBegin == InsertPos)
740 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
741 CurrentTop = CurrentBottom;
744 ++NumInstrsScheduled;
760 Topo.InitDAGTopologicalSorting();
765 findRootsAndBiasEdges(TopRoots, BotRoots);
767 LLVM_DEBUG(
if (EntrySU.getInstr() !=
nullptr) EntrySU.dumpAll(
this);
769 : SUnits) SU.dumpAll(
this);
770 if (ExitSU.getInstr() !=
nullptr) ExitSU.dumpAll(
this););
771 if (ViewMISchedDAGs) viewGraph();
775 SchedImpl->initialize(
this);
778 initQueues(TopRoots, BotRoots);
780 bool IsTopNode =
false;
782 LLVM_DEBUG(
dbgs() <<
"** ScheduleDAGMI::schedule picking next node\n");
783 SUnit *SU = SchedImpl->pickNode(IsTopNode);
787 if (!checkSchedLimit())
793 if (&*CurrentTop == MI)
794 CurrentTop =
nextIfDebug(++CurrentTop, CurrentBottom);
796 moveInstruction(MI, CurrentTop);
802 CurrentBottom = priorII;
804 if (&*CurrentTop == MI)
806 moveInstruction(MI, CurrentBottom);
814 SchedImpl->schedNode(SU, IsTopNode);
816 updateQueues(SU, IsTopNode);
818 assert(CurrentTop == CurrentBottom &&
"Nonempty unscheduled zone.");
823 dbgs() <<
"*** Final schedule for " 832 for (
auto &m : Mutations)
839 for (
SUnit &SU : SUnits) {
840 assert(!SU.isBoundaryNode() &&
"Boundary node should not be in SUnits");
843 SU.biasCriticalPath();
846 if (!SU.NumPredsLeft)
849 if (!SU.NumSuccsLeft)
852 ExitSU.biasCriticalPath();
858 NextClusterSucc =
nullptr;
859 NextClusterPred =
nullptr;
865 for (
SUnit *SU : TopRoots)
866 SchedImpl->releaseTopNode(SU);
872 SchedImpl->releaseBottomNode(*
I);
875 releaseSuccessors(&EntrySU);
876 releasePredecessors(&ExitSU);
878 SchedImpl->registerRoots();
882 CurrentBottom = RegionEnd;
889 releaseSuccessors(SU);
891 releasePredecessors(SU);
900 BB->splice(RegionBegin, BB, FirstDbgValue);
901 RegionBegin = FirstDbgValue;
904 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
905 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
906 std::pair<MachineInstr *, MachineInstr *>
P = *std::prev(DI);
909 if (&*RegionBegin == DbgValue)
911 BB->splice(++OrigPrevMI, BB, DbgValue);
912 if (OrigPrevMI == std::prev(RegionEnd))
913 RegionEnd = DbgValue;
916 FirstDbgValue =
nullptr;
919 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 922 if (
SUnit *SU = getSUnit(&(*
MI)))
925 dbgs() <<
"Missing SUnit\n";
946 if (TrackLaneMasks && !MO.isUse())
949 unsigned Reg = MO.getReg();
954 if (TrackLaneMasks) {
955 bool FoundDef =
false;
957 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
968 for (; UI != VRegUses.end(); ++UI) {
972 if (UI == VRegUses.end())
984 unsigned regioninstrs)
990 LiveRegionEnd = (RegionEnd == bb->
end()) ? RegionEnd : std::next(RegionEnd);
992 SUPressureDiffs.clear();
994 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
995 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
997 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
998 "ShouldTrackLaneMasks requires ShouldTrackPressure");
1005 VRegUses.setUniverse(
MRI.getNumVirtRegs());
1006 for (
SUnit &SU : SUnits)
1007 collectVRegUses(SU);
1009 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
1010 ShouldTrackLaneMasks,
false);
1011 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1012 ShouldTrackLaneMasks,
false);
1015 RPTracker.closeRegion();
1020 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
1021 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
1026 TopRPTracker.closeTop();
1027 BotRPTracker.closeBottom();
1029 BotRPTracker.initLiveThru(RPTracker);
1030 if (!BotRPTracker.getLiveThru().empty()) {
1031 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
1038 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
1041 if (LiveRegionEnd != RegionEnd) {
1043 BotRPTracker.recede(&LiveUses);
1044 updatePressureDiffs(LiveUses);
1049 dbgs() <<
"Bottom Pressure:\n";
1052 assert((BotRPTracker.getPos() == RegionEnd ||
1053 (RegionEnd->isDebugInstr() &&
1054 BotRPTracker.getPos() ==
priorNonDebug(RegionEnd, RegionBegin))) &&
1055 "Can't find the region bottom");
1059 RegionCriticalPSets.clear();
1062 for (
unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
1063 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
1064 if (RegionPressure[i] > Limit) {
1066 <<
" Actual " << RegionPressure[i] <<
"\n");
1072 : RegionCriticalPSets)
dbgs()
1073 <<
TRI->getRegPressureSetName(RCPS.getPSet()) <<
" ";
1079 const std::vector<unsigned> &NewMaxPressure) {
1081 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
1085 unsigned ID = PC.getPSet();
1086 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1088 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1089 if ((
int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
1091 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1093 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1094 if (NewMaxPressure[ID] >= Limit - 2) {
1096 << NewMaxPressure[
ID]
1097 << ((NewMaxPressure[
ID] > Limit) ?
" > " :
" <= ")
1098 << Limit <<
"(+ " << BotRPTracker.getLiveThru()[
ID]
1109 unsigned Reg =
P.RegUnit;
1111 if (!
TRI->isVirtualRegister(Reg))
1114 if (ShouldTrackLaneMasks) {
1119 bool Decrement =
P.LaneMask.any();
1122 :
make_range(VRegUses.find(Reg), VRegUses.end())) {
1123 SUnit &SU = *V2SU.SU;
1152 assert(VNI &&
"No live value at use.");
1154 :
make_range(VRegUses.find(Reg), VRegUses.end())) {
1155 SUnit *SU = V2SU.SU;
1187 buildDAGWithRegPressure();
1189 Topo.InitDAGTopologicalSorting();
1194 findRootsAndBiasEdges(TopRoots, BotRoots);
1198 SchedImpl->initialize(
this);
1200 LLVM_DEBUG(
if (EntrySU.getInstr() !=
nullptr) EntrySU.dumpAll(
this);
1201 for (
const SUnit &SU
1204 if (ShouldTrackPressure) {
1205 dbgs() <<
" Pressure Diff : ";
1206 getPressureDiff(&SU).dump(*
TRI);
1208 dbgs() <<
" Single Issue : ";
1209 if (SchedModel.mustBeginGroup(SU.getInstr()) &&
1210 SchedModel.mustEndGroup(SU.getInstr()))
1215 }
if (ExitSU.getInstr() !=
nullptr) ExitSU.dumpAll(
this););
1216 if (ViewMISchedDAGs) viewGraph();
1219 initQueues(TopRoots, BotRoots);
1221 bool IsTopNode =
false;
1223 LLVM_DEBUG(
dbgs() <<
"** ScheduleDAGMILive::schedule picking next node\n");
1224 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1228 if (!checkSchedLimit())
1231 scheduleMI(SU, IsTopNode);
1234 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1235 if (!ScheduledTrees.test(SubtreeID)) {
1236 ScheduledTrees.set(SubtreeID);
1237 DFSResult->scheduleTree(SubtreeID);
1238 SchedImpl->scheduleTree(SubtreeID);
1243 SchedImpl->schedNode(SU, IsTopNode);
1245 updateQueues(SU, IsTopNode);
1247 assert(CurrentTop == CurrentBottom &&
"Nonempty unscheduled zone.");
1252 dbgs() <<
"*** Final schedule for " 1261 if (!ShouldTrackPressure) {
1263 RegionCriticalPSets.clear();
1264 buildSchedGraph(AA);
1269 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1270 ShouldTrackLaneMasks,
true);
1273 if (LiveRegionEnd != RegionEnd)
1277 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
1287 ScheduledTrees.clear();
1288 DFSResult->resize(SUnits.size());
1289 DFSResult->compute(SUnits);
1290 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1321 if (!BB->isSuccessor(BB))
1324 unsigned MaxCyclicLatency = 0;
1327 unsigned Reg =
P.RegUnit;
1328 if (!
TRI->isVirtualRegister(Reg))
1336 const SUnit *DefSU = getSUnit(DefMI);
1340 unsigned LiveOutHeight = DefSU->
getHeight();
1344 :
make_range(VRegUses.find(Reg), VRegUses.end())) {
1345 SUnit *SU = V2SU.SU;
1357 unsigned CyclicLatency = 0;
1359 CyclicLatency = LiveOutDepth - SU->
getDepth();
1362 if (LiveInHeight > LiveOutHeight) {
1363 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1364 CyclicLatency = LiveInHeight - LiveOutHeight;
1369 << SU->
NodeNum <<
") = " << CyclicLatency <<
"c\n");
1370 if (CyclicLatency > MaxCyclicLatency)
1371 MaxCyclicLatency = CyclicLatency;
1374 LLVM_DEBUG(
dbgs() <<
"Cyclic Critical Path: " << MaxCyclicLatency <<
"c\n");
1375 return MaxCyclicLatency;
1383 if (ShouldTrackPressure) {
1384 assert(TopRPTracker.getPos() == RegionBegin &&
"bad initial Top tracker");
1385 TopRPTracker.setPos(CurrentTop);
1396 if (&*CurrentTop == MI)
1397 CurrentTop =
nextIfDebug(++CurrentTop, CurrentBottom);
1399 moveInstruction(MI, CurrentTop);
1400 TopRPTracker.setPos(MI);
1403 if (ShouldTrackPressure) {
1406 RegOpers.
collect(*MI, *
TRI,
MRI, ShouldTrackLaneMasks,
false);
1407 if (ShouldTrackLaneMasks) {
1416 TopRPTracker.advance(RegOpers);
1417 assert(TopRPTracker.getPos() == CurrentTop &&
"out of sync");
1419 TopRPTracker.getRegSetPressureAtPos(),
TRI););
1421 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
1427 if (&*priorII == MI)
1428 CurrentBottom = priorII;
1430 if (&*CurrentTop == MI) {
1432 TopRPTracker.setPos(CurrentTop);
1434 moveInstruction(MI, CurrentBottom);
1436 BotRPTracker.setPos(CurrentBottom);
1438 if (ShouldTrackPressure) {
1440 RegOpers.
collect(*MI, *
TRI,
MRI, ShouldTrackLaneMasks,
false);
1441 if (ShouldTrackLaneMasks) {
1450 if (BotRPTracker.getPos() != CurrentBottom)
1451 BotRPTracker.recedeSkipDebugValues();
1453 BotRPTracker.recede(RegOpers, &LiveUses);
1454 assert(BotRPTracker.getPos() == CurrentBottom &&
"out of sync");
1456 BotRPTracker.getRegSetPressureAtPos(),
TRI););
1458 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
1459 updatePressureDiffs(LiveUses);
1478 MemOpInfo(
SUnit *su,
unsigned reg, int64_t ofs)
1479 : SU(su), BaseReg(reg),
Offset(ofs) {}
1481 bool operator<(
const MemOpInfo&RHS)
const {
1482 return std::tie(BaseReg, Offset, SU->
NodeNum) <
1483 std::tie(RHS.BaseReg, RHS.Offset, RHS.SU->NodeNum);
1494 :
TII(tii),
TRI(tri), IsLoad(IsLoad) {}
1502 class StoreClusterMutation :
public BaseMemOpClusterMutation {
1506 : BaseMemOpClusterMutation(tii, tri,
false) {}
1509 class LoadClusterMutation :
public BaseMemOpClusterMutation {
1512 : BaseMemOpClusterMutation(tii, tri,
true) {}
1519 std::unique_ptr<ScheduleDAGMutation>
1522 return EnableMemOpCluster ? llvm::make_unique<LoadClusterMutation>(
TII,
TRI)
1526 std::unique_ptr<ScheduleDAGMutation>
1529 return EnableMemOpCluster ? llvm::make_unique<StoreClusterMutation>(
TII,
TRI)
1535 void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1538 for (
SUnit *SU : MemOps) {
1542 MemOpRecords.
push_back(MemOpInfo(SU, BaseReg, Offset));
1544 if (MemOpRecords.
size() < 2)
1548 unsigned ClusterLength = 1;
1549 for (
unsigned Idx = 0, End = MemOpRecords.
size(); Idx < (End - 1); ++Idx) {
1550 SUnit *SUa = MemOpRecords[Idx].SU;
1551 SUnit *SUb = MemOpRecords[Idx+1].SU;
1552 if (
TII->shouldClusterMemOps(*SUa->
getInstr(), MemOpRecords[Idx].BaseReg,
1553 *SUb->
getInstr(), MemOpRecords[Idx+1].BaseReg,
1588 unsigned ChainPredID = DAG->
SUnits.size();
1597 unsigned NumChains = StoreChainDependents.
size();
1598 std::pair<DenseMap<unsigned, unsigned>::iterator,
bool>
Result =
1599 StoreChainIDs.
insert(std::make_pair(ChainPredID, NumChains));
1601 StoreChainDependents.
resize(NumChains + 1);
1602 StoreChainDependents[Result.first->second].
push_back(&SU);
1606 for (
auto &SCD : StoreChainDependents)
1607 clusterNeighboringMemOps(SCD, DAG);
1640 std::unique_ptr<ScheduleDAGMutation>
1643 return llvm::make_unique<CopyConstrain>(
TII,
TRI);
1673 unsigned SrcReg = SrcOp.
getReg();
1678 unsigned DstReg = DstOp.
getReg();
1688 unsigned LocalReg = SrcReg;
1689 unsigned GlobalReg = DstReg;
1691 if (!LocalLI->
isLocal(RegionBeginIdx, RegionEndIdx)) {
1695 if (!LocalLI->
isLocal(RegionBeginIdx, RegionEndIdx))
1706 if (GlobalSegment == GlobalLI->
end())
1713 if (GlobalSegment->contains(LocalLI->
beginIndex()))
1716 if (GlobalSegment == GlobalLI->
end())
1720 if (GlobalSegment != GlobalLI->
begin()) {
1723 GlobalSegment->start)) {
1734 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
1735 "Disconnected LRG within the scheduling region.");
1751 for (
const SDep &Succ : LastLocalSU->
Succs) {
1766 for (
const SDep &Pred : GlobalSU->
Preds) {
1769 if (Pred.
getSUnit() == FirstLocalSU)
1779 LLVM_DEBUG(
dbgs() <<
" Local use SU(" << (*I)->NodeNum <<
") -> SU(" 1780 << GlobalSU->
NodeNum <<
")\n");
1784 I = GlobalUses.
begin(),
E = GlobalUses.
end();
I !=
E; ++
I) {
1785 LLVM_DEBUG(
dbgs() <<
" Global use SU(" << (*I)->NodeNum <<
") -> SU(" 1786 << FirstLocalSU->
NodeNum <<
")\n");
1798 if (FirstPos == DAG->
end())
1808 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
1825 return (
int)(Count - (Latency * LFactor)) > (int)LFactor;
1832 if (HazardRec && HazardRec->isEnabled()) {
1834 HazardRec =
nullptr;
1838 CheckPending =
false;
1842 ExpectedLatency = 0;
1843 DependentLatency = 0;
1845 MaxExecutedResCount = 0;
1847 IsResourceLimited =
false;
1848 ReservedCycles.clear();
1853 MaxObservedStall = 0;
1856 ExecutedResCounts.resize(1);
1857 assert(!ExecutedResCounts[0] &&
"nonzero count for bad resource");
1873 unsigned PIdx = PI->ProcResourceIdx;
1875 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1884 SchedModel = smodel;
1886 if (SchedModel->hasInstrSchedModel()) {
1887 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
1888 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(),
InvalidCycle);
1904 if (ReadyCycle > CurrCycle)
1905 return ReadyCycle - CurrCycle;
1913 unsigned NextUnreserved = ReservedCycles[PIdx];
1915 if (NextUnreserved == InvalidCycle)
1919 NextUnreserved += Cycles;
1920 return NextUnreserved;
1937 if (HazardRec->isEnabled()
1942 unsigned uops = SchedModel->getNumMicroOps(SU->
getInstr());
1943 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
1945 << SchedModel->getNumMicroOps(SU->
getInstr()) <<
'\n');
1950 ((isTop() && SchedModel->mustBeginGroup(SU->
getInstr())) ||
1951 (!isTop() && SchedModel->mustEndGroup(SU->
getInstr())))) {
1953 << (isTop() ?
"begin" :
"end") <<
" group\n");
1960 make_range(SchedModel->getWriteProcResBegin(SC),
1961 SchedModel->getWriteProcResEnd(SC))) {
1962 unsigned ResIdx = PE.ProcResourceIdx;
1963 unsigned Cycles = PE.Cycles;
1964 unsigned NRCycle = getNextResourceCycle(ResIdx, Cycles);
1965 if (NRCycle > CurrCycle) {
1967 MaxObservedStall =
std::max(Cycles, MaxObservedStall);
1970 << SchedModel->getResourceName(ResIdx) <<
"=" 1971 << NRCycle <<
"c\n");
1982 SUnit *LateSU =
nullptr;
1983 unsigned RemLatency = 0;
1984 for (
SUnit *SU : ReadySUs) {
1985 unsigned L = getUnscheduledLatency(SU);
1986 if (L > RemLatency) {
1993 << LateSU->
NodeNum <<
") " << RemLatency <<
"c\n");
2004 if (!SchedModel->hasInstrSchedModel())
2007 unsigned OtherCritCount = Rem->RemIssueCount
2008 + (RetiredMOps * SchedModel->getMicroOpFactor());
2009 LLVM_DEBUG(
dbgs() <<
" " << Available.getName() <<
" + Remain MOps: " 2010 << OtherCritCount / SchedModel->getMicroOpFactor() <<
'\n');
2011 for (
unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
2012 PIdx != PEnd; ++PIdx) {
2013 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
2014 if (OtherCount > OtherCritCount) {
2015 OtherCritCount = OtherCount;
2016 OtherCritIdx = PIdx;
2021 dbgs() <<
" " << Available.getName() <<
" + Remain CritRes: " 2022 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
2023 <<
" " << SchedModel->getResourceName(OtherCritIdx) <<
"\n");
2025 return OtherCritCount;
2035 if (ReadyCycle > CurrCycle)
2036 MaxObservedStall =
std::max(ReadyCycle - CurrCycle, MaxObservedStall);
2039 if (ReadyCycle < MinReadyCycle)
2040 MinReadyCycle = ReadyCycle;
2044 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2045 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
2054 if (SchedModel->getMicroOpBufferSize() == 0) {
2056 "MinReadyCycle uninitialized");
2057 if (MinReadyCycle > NextCycle)
2058 NextCycle = MinReadyCycle;
2061 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2062 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2065 if ((NextCycle - CurrCycle) > DependentLatency)
2066 DependentLatency = 0;
2068 DependentLatency -= (NextCycle - CurrCycle);
2070 if (!HazardRec->isEnabled()) {
2072 CurrCycle = NextCycle;
2075 for (; CurrCycle != NextCycle; ++CurrCycle) {
2077 HazardRec->AdvanceCycle();
2079 HazardRec->RecedeCycle();
2082 CheckPending =
true;
2085 getScheduledLatency());
2087 LLVM_DEBUG(
dbgs() <<
"Cycle: " << CurrCycle <<
' ' << Available.getName()
2092 ExecutedResCounts[PIdx] += Count;
2093 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2094 MaxExecutedResCount = ExecutedResCounts[PIdx];
2106 unsigned Factor = SchedModel->getResourceFactor(PIdx);
2107 unsigned Count = Factor * Cycles;
2108 LLVM_DEBUG(
dbgs() <<
" " << SchedModel->getResourceName(PIdx) <<
" +" 2109 << Cycles <<
"x" << Factor <<
"u\n");
2112 incExecutedResources(PIdx, Count);
2113 assert(Rem->RemainingCounts[PIdx] >= Count &&
"resource double counted");
2114 Rem->RemainingCounts[PIdx] -= Count;
2118 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
2119 ZoneCritResIdx = PIdx;
2121 << SchedModel->getResourceName(PIdx) <<
": " 2122 << getResourceCount(PIdx) / SchedModel->getLatencyFactor()
2126 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2127 if (NextAvailable > CurrCycle) {
2129 << SchedModel->getProcResource(PIdx)->Name
2130 <<
" reserved until @" << NextAvailable <<
"\n");
2132 return NextAvailable;
2138 if (HazardRec->isEnabled()) {
2139 if (!isTop() && SU->
isCall) {
2144 HazardRec->EmitInstruction(SU);
2149 unsigned IncMOps = SchedModel->getNumMicroOps(SU->
getInstr());
2151 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
2152 "Cannot schedule this instruction's MicroOps in the current cycle.");
2157 unsigned NextCycle = CurrCycle;
2158 switch (SchedModel->getMicroOpBufferSize()) {
2160 assert(ReadyCycle <= CurrCycle &&
"Broken PendingQueue");
2163 if (ReadyCycle > NextCycle) {
2164 NextCycle = ReadyCycle;
2165 LLVM_DEBUG(
dbgs() <<
" *** Stall until: " << ReadyCycle <<
"\n");
2174 NextCycle = ReadyCycle;
2177 RetiredMOps += IncMOps;
2180 if (SchedModel->hasInstrSchedModel()) {
2181 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2182 assert(Rem->RemIssueCount >= DecRemIssue &&
"MOps double counted");
2183 Rem->RemIssueCount -= DecRemIssue;
2184 if (ZoneCritResIdx) {
2186 unsigned ScaledMOps =
2187 RetiredMOps * SchedModel->getMicroOpFactor();
2191 if ((
int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2192 >= (
int)SchedModel->getLatencyFactor()) {
2195 << ScaledMOps / SchedModel->getLatencyFactor()
2200 PI = SchedModel->getWriteProcResBegin(SC),
2201 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2203 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
2204 if (RCycle > NextCycle)
2213 PI = SchedModel->getWriteProcResBegin(SC),
2214 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2215 unsigned PIdx = PI->ProcResourceIdx;
2216 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
2218 ReservedCycles[PIdx] =
2219 std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2222 ReservedCycles[PIdx] = NextCycle;
2228 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2229 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2232 LLVM_DEBUG(
dbgs() <<
" " << Available.getName() <<
" TopLatency SU(" 2233 << SU->
NodeNum <<
") " << TopLatency <<
"c\n");
2237 LLVM_DEBUG(
dbgs() <<
" " << Available.getName() <<
" BotLatency SU(" 2238 << SU->
NodeNum <<
") " << BotLatency <<
"c\n");
2241 if (NextCycle > CurrCycle)
2242 bumpCycle(NextCycle);
2248 getScheduledLatency());
2254 CurrMOps += IncMOps;
2260 if ((isTop() && SchedModel->mustEndGroup(SU->
getInstr())) ||
2261 (!isTop() && SchedModel->mustBeginGroup(SU->
getInstr()))) {
2262 LLVM_DEBUG(
dbgs() <<
" Bump cycle to " << (isTop() ?
"end" :
"begin")
2264 bumpCycle(++NextCycle);
2267 while (CurrMOps >= SchedModel->getIssueWidth()) {
2268 LLVM_DEBUG(
dbgs() <<
" *** Max MOps " << CurrMOps <<
" at cycle " 2269 << CurrCycle <<
'\n');
2270 bumpCycle(++NextCycle);
2279 if (Available.empty())
2284 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2285 for (
unsigned i = 0, e = Pending.size(); i != e; ++i) {
2286 SUnit *SU = *(Pending.begin()+i);
2289 if (ReadyCycle < MinReadyCycle)
2290 MinReadyCycle = ReadyCycle;
2292 if (!IsBuffered && ReadyCycle > CurrCycle)
2295 if (checkHazard(SU))
2302 Pending.remove(Pending.begin()+i);
2305 CheckPending =
false;
2310 if (Available.isInQueue(SU))
2311 Available.remove(Available.find(SU));
2313 assert(Pending.isInQueue(SU) &&
"bad ready count");
2314 Pending.remove(Pending.find(SU));
2328 if (checkHazard(*
I)) {
2330 I = Available.remove(
I);
2336 for (
unsigned i = 0; Available.empty(); ++i) {
2341 bumpCycle(CurrCycle + 1);
2348 if (Available.size() == 1)
2349 return *Available.begin();
2353 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2359 if (ZoneCritResIdx) {
2360 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2361 ResCount = getResourceCount(ZoneCritResIdx);
2363 ResFactor = SchedModel->getMicroOpFactor();
2364 ResCount = RetiredMOps * ResFactor;
2366 unsigned LFactor = SchedModel->getLatencyFactor();
2367 dbgs() << Available.getName() <<
" @" << CurrCycle <<
"c\n" 2368 <<
" Retired: " << RetiredMOps;
2369 dbgs() <<
"\n Executed: " << getExecutedCount() / LFactor <<
"c";
2370 dbgs() <<
"\n Critical: " << ResCount / LFactor <<
"c, " 2371 << ResCount / ResFactor <<
" " 2372 << SchedModel->getResourceName(ZoneCritResIdx)
2373 <<
"\n ExpectedLatency: " << ExpectedLatency <<
"c\n" 2374 << (IsResourceLimited ?
" - Resource" :
" - Latency")
2386 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2393 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2394 ResDelta.CritResources += PI->Cycles;
2395 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2396 ResDelta.DemandedResources += PI->Cycles;
2429 unsigned OtherCritIdx = 0;
2430 unsigned OtherCount =
2433 bool OtherResLimited =
false;
2434 if (SchedModel->hasInstrSchedModel())
2436 OtherCount, RemLatency);
2441 if (!OtherResLimited) {
2442 if (IsPostRA || (RemLatency + CurrZone.
getCurrCycle() > Rem.CriticalPath)) {
2445 <<
" RemainingLatency " << RemLatency <<
" + " 2447 << Rem.CriticalPath <<
"\n");
2457 }
if (OtherResLimited)
dbgs()
2458 <<
" RemainingLimit: " 2459 << SchedModel->getResourceName(OtherCritIdx) <<
"\n";
2461 <<
" Latency limited both directions.\n");
2466 if (OtherResLimited)
2474 case NoCand:
return "NOCAND ";
2475 case Only1:
return "ONLY1 ";
2476 case PhysRegCopy:
return "PREG-COPY ";
2477 case RegExcess:
return "REG-EXCESS";
2478 case RegCritical:
return "REG-CRIT ";
2479 case Stall:
return "STALL ";
2480 case Cluster:
return "CLUSTER ";
2481 case Weak:
return "WEAK ";
2482 case RegMax:
return "REG-MAX ";
2483 case ResourceReduce:
return "RES-REDUCE";
2484 case ResourceDemand:
return "RES-DEMAND";
2485 case TopDepthReduce:
return "TOP-DEPTH ";
2486 case TopPathReduce:
return "TOP-PATH ";
2487 case BotHeightReduce:
return "BOT-HEIGHT";
2488 case BotPathReduce:
return "BOT-PATH ";
2489 case NextDefUse:
return "DEF-USE ";
2497 unsigned ResIdx = 0;
2511 case ResourceReduce:
2514 case ResourceDemand:
2517 case TopDepthReduce:
2523 case BotHeightReduce:
2537 dbgs() <<
" " << SchedModel->getProcResource(ResIdx)->Name <<
" ";
2541 dbgs() <<
" " << Latency <<
" cycles ";
2554 if (TryVal < CandVal) {
2558 if (TryVal > CandVal) {
2559 if (Cand.
Reason > Reason)
2570 if (TryVal > CandVal) {
2574 if (TryVal < CandVal) {
2575 if (Cand.
Reason > Reason)
2619 "(PreRA)GenericScheduler needs vreg liveness");
2624 Rem.init(DAG, SchedModel);
2625 Top.init(DAG, SchedModel, &Rem);
2626 Bot.init(DAG, SchedModel, &Rem);
2633 if (!Top.HazardRec) {
2635 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
2638 if (!Bot.HazardRec) {
2640 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
2643 TopCand.SU =
nullptr;
2644 BotCand.SU =
nullptr;
2650 unsigned NumRegionInstrs) {
2657 RegionPolicy.ShouldTrackPressure =
true;
2661 unsigned NIntRegs =
Context->RegClassInfo->getNumAllocatableRegs(
2663 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2669 RegionPolicy.OnlyBottomUp =
true;
2675 if (!EnableRegPressure)
2676 RegionPolicy.ShouldTrackPressure =
false;
2681 "-misched-topdown incompatible with -misched-bottomup");
2684 if (RegionPolicy.OnlyBottomUp)
2685 RegionPolicy.OnlyTopDown =
false;
2689 if (RegionPolicy.OnlyTopDown)
2690 RegionPolicy.OnlyBottomUp =
false;
2696 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2697 dbgs() <<
"GenericScheduler RegionPolicy: " 2698 <<
" ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2699 <<
" OnlyTopDown=" << RegionPolicy.OnlyTopDown
2700 <<
" OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2715 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2719 unsigned IterCount =
2720 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2723 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2725 unsigned InFlightCount =
2726 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2727 unsigned BufferLimit =
2728 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2730 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2733 dbgs() <<
"IssueCycles=" 2734 << Rem.RemIssueCount / SchedModel->getLatencyFactor() <<
"c " 2735 <<
"IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2736 <<
"c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount
2737 <<
" InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2738 <<
"m BufferLim=" << SchedModel->getMicroOpBufferSize() <<
"m\n";
2739 if (Rem.IsAcyclicLatencyLimited)
dbgs() <<
" ACYCLIC LATENCY LIMIT\n");
2746 for (
const SUnit *SU : Bot.Available) {
2747 if (SU->
getDepth() > Rem.CriticalPath)
2750 LLVM_DEBUG(
dbgs() <<
"Critical Path(GS-RR ): " << Rem.CriticalPath <<
'\n');
2752 errs() <<
"Critical Path(GS-RR ): " << Rem.CriticalPath <<
" \n";
2755 if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
2757 checkAcyclicLatency();
2777 if (Cand.AtTop != TryCand.
AtTop)
2784 if (TryPSet == CandPSet) {
2798 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2817 unsigned ScheduledOper = isTop ? 1 : 0;
2818 unsigned UnscheduledOper = isTop ? 0 : 1;
2829 return AtBoundary ? -1 : 1;
2848 if (VerifyScheduling) {
2866 <<
" Try SU(" << Cand.
SU->
NodeNum <<
") " 2892 TryCand, Cand, PhysRegCopy))
2898 TryCand, Cand, RegExcess,
TRI,
2905 TryCand, Cand, RegCritical,
TRI,
2914 bool SameBoundary = Zone !=
nullptr;
2919 if (Rem.IsAcyclicLatencyLimited && !Zone->
getCurrMOps() &&
2935 const SUnit *CandNextClusterSU =
2937 const SUnit *TryCandNextClusterSU =
2940 Cand.
SU == CandNextClusterSU,
2941 TryCand, Cand, Cluster))
2948 TryCand, Cand, Weak))
2955 TryCand, Cand, RegMax,
TRI,
2963 TryCand, Cand, ResourceReduce))
2967 TryCand, Cand, ResourceDemand))
2973 !Rem.IsAcyclicLatencyLimited &&
tryLatency(TryCand, Cand, *Zone))
2997 for (
SUnit *SU : Q) {
3000 initCandidate(TryCand, SU, Zone.
isTop(), RPTracker, TempTracker);
3003 tryCandidate(Cand, TryCand, ZoneArg);
3018 if (
SUnit *SU = Bot.pickOnlyChoice()) {
3023 if (
SUnit *SU = Top.pickOnlyChoice()) {
3031 setPolicy(BotPolicy,
false, Bot, &Top);
3035 setPolicy(TopPolicy,
false, Top, &Bot);
3039 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
3040 BotCand.Policy != BotPolicy) {
3043 assert(BotCand.Reason !=
NoCand &&
"failed to find the first candidate");
3047 if (VerifyScheduling) {
3052 "Last pick result should correspond to re-picking right now");
3059 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3060 TopCand.Policy != TopPolicy) {
3063 assert(TopCand.Reason !=
NoCand &&
"failed to find the first candidate");
3067 if (VerifyScheduling) {
3072 "Last pick result should correspond to re-picking right now");
3078 assert(BotCand.isValid());
3079 assert(TopCand.isValid());
3082 tryCandidate(Cand, TopCand,
nullptr);
3083 if (TopCand.Reason !=
NoCand) {
3084 Cand.setBest(TopCand);
3088 IsTopNode = Cand.AtTop;
3096 assert(Top.Available.empty() && Top.Pending.empty() &&
3097 Bot.Available.empty() && Bot.Pending.empty() &&
"ReadyQ garbage");
3102 if (RegionPolicy.OnlyTopDown) {
3103 SU = Top.pickOnlyChoice();
3106 TopCand.reset(NoPolicy);
3108 assert(TopCand.Reason !=
NoCand &&
"failed to find a candidate");
3113 }
else if (RegionPolicy.OnlyBottomUp) {
3114 SU = Bot.pickOnlyChoice();
3117 BotCand.reset(NoPolicy);
3119 assert(BotCand.Reason !=
NoCand &&
"failed to find a candidate");
3125 SU = pickNodeBidirectional(IsTopNode);
3130 Top.removeReady(SU);
3132 Bot.removeReady(SU);
3147 for (
SDep &Dep : Deps) {
3148 if (Dep.getKind() !=
SDep::Data || !
TRI->isPhysicalRegister(Dep.getReg()))
3150 SUnit *DepSU = Dep.getSUnit();
3151 if (isTop ? DepSU->
Succs.size() > 1 : DepSU->
Preds.size() > 1)
3157 Dep.getSUnit()->dump(DAG));
3174 reschedulePhysRegCopies(SU,
true);
3179 reschedulePhysRegCopies(SU,
false);
3214 Rem.init(DAG, SchedModel);
3215 Top.init(DAG, SchedModel, &Rem);
3221 if (!Top.HazardRec) {
3232 for (
const SUnit *SU : BotRoots) {
3233 if (SU->getDepth() > Rem.CriticalPath)
3234 Rem.CriticalPath = SU->getDepth();
3236 LLVM_DEBUG(
dbgs() <<
"Critical Path: (PGS-RR) " << Rem.CriticalPath <<
'\n');
3238 errs() <<
"Critical Path(PGS-RR ): " << Rem.CriticalPath <<
" \n";
3255 if (
tryLess(Top.getLatencyStallCycles(TryCand.
SU),
3256 Top.getLatencyStallCycles(Cand.
SU), TryCand, Cand, Stall))
3262 TryCand, Cand, Cluster))
3267 TryCand, Cand, ResourceReduce))
3270 Cand.ResDelta.DemandedResources,
3271 TryCand, Cand, ResourceDemand))
3275 if (Cand.Policy.ReduceLatency &&
tryLatency(TryCand, Cand, Top)) {
3280 if (TryCand.
SU->
NodeNum < Cand.SU->NodeNum)
3286 for (
SUnit *SU : Q) {
3289 TryCand.
AtTop =
true;
3291 tryCandidate(Cand, TryCand);
3302 assert(Top.Available.empty() && Top.Pending.empty() &&
"ReadyQ garbage");
3307 SU = Top.pickOnlyChoice();
3315 setPolicy(TopCand.
Policy,
true, Top,
nullptr);
3316 pickNodeFromQueue(TopCand);
3324 Top.removeReady(SU);
3339 return new ScheduleDAGMI(C, llvm::make_unique<PostGenericScheduler>(C),
3352 const BitVector *ScheduledTrees =
nullptr;
3355 ILPOrder(
bool MaxILP) : MaximizeILP(MaxILP) {}
3360 bool operator()(
const SUnit *A,
const SUnit *
B)
const {
3363 if (SchedTreeA != SchedTreeB) {
3365 if (ScheduledTrees->
test(SchedTreeA) != ScheduledTrees->
test(SchedTreeB))
3366 return ScheduledTrees->
test(SchedTreeB);
3387 std::vector<SUnit*> ReadyQ;
3390 ILPScheduler(
bool MaximizeILP) : Cmp(MaximizeILP) {}
3396 Cmp.DFSResult = DAG->getDFSResult();
3397 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
3403 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3411 if (ReadyQ.empty())
return nullptr;
3412 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3413 SUnit *SU = ReadyQ.back();
3417 <<
"SU(" << SU->NodeNum <<
") " 3424 <<
"Scheduling " << *SU->getInstr());
3430 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3436 assert(!IsTopNode &&
"SchedDFSResult needs bottom-up");
3442 ReadyQ.push_back(SU);
3443 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3470 template<
bool IsReverse>
3496 InstructionShuffler(
bool alternate,
bool topdown)
3497 : IsAlternating(alternate), IsTopDown(topdown) {}
3511 if (TopQ.empty())
return nullptr;
3518 if (BottomQ.empty())
return nullptr;
3525 IsTopDown = !IsTopDown;
3545 "-misched-topdown incompatible with -misched-bottomup");
3547 C, llvm::make_unique<InstructionShuffler>(Alternate, TopDown));
3551 "shuffle",
"Shuffle machine instructions alternating directions",
3578 if (ViewMISchedCutoff == 0)
3580 return (Node->
Preds.size() > ViewMISchedCutoff
3590 return "color=cyan,style=dashed";
3592 return "color=blue,style=dashed";
3613 std::string Str(
"shape=Mrecord");
3618 Str +=
",style=filled,fillcolor=\"#";
3635 errs() <<
"ScheduleDAGMI::viewGraph is only available in debug builds on " 3636 <<
"systems with Graphviz or gv!\n";
3642 viewGraph(getDAGName(),
"Scheduling-Units Graph for " + getDAGName());
void computeDFSResult()
Compute a DFSResult after DAG building is complete, and before any queue comparisons.
std::reverse_iterator< const_iterator > const_reverse_iterator
unsigned findMaxLatency(ArrayRef< SUnit *> ReadySUs)
void releaseSucc(SUnit *SU, SDep *SuccEdge)
ReleaseSucc - Decrement the NumPredsLeft count of a successor.
Weak DAG edge linking a chain of clustered instrs.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
unsigned getNumInstrs(const SUnit *SU) const
Get the number of instructions in the given subtree and its children.
void push_back(const T &Elt)
void schedNode(SUnit *SU, bool IsTopNode) override
Called after ScheduleDAGMI has scheduled an instruction and updated scheduled/remaining flags in the ...
const_iterator end(StringRef path)
Get end iterator over path.
virtual void finishBlock()
Cleans up after scheduling in the given block.
virtual void initialize(ScheduleDAGMI *DAG)=0
Initialize the strategy after building the DAG for a new region.
A common definition of LaneBitmask for use in TableGen and CodeGen.
unsigned getZoneCritResIdx() const
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static cl::opt< bool > ViewMISchedDAGs("view-misched-dags", cl::Hidden, cl::desc("Pop up a window to show MISched dags after they are processed"))
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G)
static cl::opt< bool > EnablePostRAMachineSched("enable-post-misched", cl::desc("Enable the post-ra machine instruction scheduling pass."), cl::init(true), cl::Hidden)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
iterator_base< SparseMultiSet *> iterator
ProcResIter getWriteProcResBegin(const MCSchedClassDesc *SC) const
void detectDeadDefs(const MachineInstr &MI, const LiveIntervals &LIS)
Use liveness information to find dead defs not marked with a dead flag and move them to the DeadDefs ...
void dumpSchedule() const
dump the scheduled Sequence.
typename SuperClass::const_iterator const_iterator
virtual ~MachineSchedContext()
Each Scheduling boundary is associated with ready queues.
SlotIndex def
The index of the defining instruction.
Compute iterated dominance frontiers using a linear time algorithm.
void addPressureChange(unsigned RegUnit, bool IsDec, const MachineRegisterInfo *MRI)
Add a change in pressure to the pressure diff of a given instruction.
SUnit * pickNodeBidirectional(bool &IsTopNode)
Pick the best candidate node from either the top or bottom queue.
virtual void releaseTopNode(SUnit *SU)=0
When all predecessor dependencies have been resolved, free this node for top-down scheduling...
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel)
A Module instance is used to store all the information related to an LLVM module. ...
Segments::iterator iterator
const MCSchedClassDesc * getSchedClass(SUnit *SU) const
Resolves and cache a resolved scheduling class for an SUnit.
void dump(const ScheduleDAG *G) const
void startBlock(MachineBasicBlock *bb) override
Prepares to perform scheduling in the given block.
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
unsigned getCurrCycle() const
Number of cycles to issue the instructions scheduled in this zone.
LiveInterval - This class represents the liveness of a register, or stack slot.
unsigned getDepth() const
Returns the depth of this node, which is the length of the maximum path up to any node which has no p...
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
static cl::opt< std::string > SchedOnlyFunc("misched-only-func", cl::Hidden, cl::desc("Only schedule this function"))
unsigned getReg() const
getReg - Returns the register number.
unsigned computeCyclicCriticalPath()
Compute the cyclic critical path through the DAG.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
void fixupKills(MachineBasicBlock &MBB)
Fixes register kill flags that scheduling has made invalid.
virtual const TargetLowering * getTargetLowering() const
void traceCandidate(const SchedCandidate &Cand)
unsigned DemandedResources
reverse_iterator rbegin() const
static bool renderGraphFromBottomUp()
bool test(unsigned Idx) const
ScheduleDAGMI * createGenericSchedPostRA(MachineSchedContext *C)
Create a generic scheduler with no vreg liveness or DAG mutation passes.
ProcResIter getWriteProcResEnd(const MCSchedClassDesc *SC) const
Mutate the DAG as a postpass after normal DAG building.
const IntervalPressure & getRegPressure() const
Get register pressure for the entire scheduling region before scheduling.
void initQueues(ArrayRef< SUnit *> TopRoots, ArrayRef< SUnit *> BotRoots)
Release ExitSU predecessors and setup scheduler queues.
static ScheduleDAGInstrs * createILPMaxScheduler(MachineSchedContext *C)
virtual std::string getGraphNodeLabel(const SUnit *SU) const =0
Returns a label for an SUnit node in a visualization of the ScheduleDAG.
virtual const TargetRegisterClass * getRegClassFor(MVT VT) const
Return the register class that should be used for the specified value type.
unsigned getDependentLatency() const
static ScheduleDAGInstrs * createInstructionShuffler(MachineSchedContext *C)
unsigned const TargetRegisterInfo * TRI
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
char & MachineSchedulerID
MachineScheduler - This pass schedules machine instructions.
Summarize the unscheduled region.
void reset(const CandPolicy &NewPolicy)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
const SchedDFSResult * getDFSResult() const
Return a non-null DFS result if the scheduling strategy initialized it.
RegisterPassParser class - Handle the addition of new machine passes.
unsigned getReg() const
Returns the register associated with this edge.
MachineSchedRegistry provides a selection of available machine instruction schedulers.
bool isBottomReady() const
VNInfo - Value Number Information.
iterator_range< mop_iterator > operands()
static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G)
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
static MachineSchedRegistry ShufflerRegistry("shuffle", "Shuffle machine instructions alternating directions", createInstructionShuffler)
unsigned BotReadyCycle
Cycle relative to end when node is ready.
static MachineSchedRegistry ILPMaxRegistry("ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler)
void updateQueues(SUnit *SU, bool IsTopNode)
Update scheduler DAG and queues after scheduling an instruction.
virtual void schedNode(SUnit *SU, bool IsTopNode)=0
Notify MachineSchedStrategy that ScheduleDAGMI has scheduled an instruction and updated scheduled/rem...
SmallVector< SDep, 4 > Preds
All sunit predecessors.
virtual void startBlock(MachineBasicBlock *BB)
Prepares to perform scheduling in the given block.
bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary &Zone)
A register anti-dependence (aka WAR).
ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules machine instructions while...
virtual bool hasVRegLiveness() const
Return true if this DAG supports VReg liveness and RegPressure.
MachineFunction & MF
Machine function.
bool isScheduled
True once scheduled.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
ArrayRef< SUnit * > elements()
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
const RegPressureTracker & getBotRPTracker() const
unsigned getLatency() const
Returns the latency value for this edge, which roughly means the minimum number of cycles that must e...
unsigned NumSuccsLeft
of succs not scheduled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Provide an instruction scheduling machine model to CodeGen passes.
const HexagonInstrInfo * TII
static std::string getEdgeAttributes(const SUnit *Node, SUnitIterator EI, const ScheduleDAG *Graph)
If you want to override the dot attributes printed for a particular edge, override this method...
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
An individual mapping from virtual register number to SUnit.
Printable printReg(unsigned Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
static cl::opt< MachineSchedRegistry::ScheduleDAGCtor, false, RegisterPassParser< MachineSchedRegistry > > MachineSchedOpt("misched", cl::init(&useDefaultMachineSched), cl::Hidden, cl::desc("Machine instruction scheduler to use"))
MachineSchedOpt allows command line selection of the scheduler.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Regular data dependence (aka true-dependence).
Result of a LiveRange query.
bool hasPhysRegUses
Has physreg uses.
void apply(Opt *O, const Mod &M, const Mods &... Ms)
StringRef getName() const
bool hasPhysRegDefs
Has physreg defs that are being used.
PressureDiff & getPressureDiff(const SUnit *SU)
bool hasInstrSchedModel() const
Return true if this machine model includes an instruction-level scheduling model. ...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Target-Independent Code Generator Pass Configuration Options.
static constexpr LaneBitmask getNone()
void initPolicy(MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, unsigned NumRegionInstrs) override
Initialize the per-region scheduling policy.
static bool isSimple(Instruction *I)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
static const char * getReasonStr(SIScheduleCandReason Reason)
Compute the values of each DAG node for various metrics during DFS.
void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs) override
Implement the ScheduleDAGInstrs interface for handling the next scheduling region.
unsigned TopReadyCycle
Cycle relative to start when node is ready.
static const unsigned InvalidCycle
unsigned getNumMicroOps(const MachineInstr *MI, const MCSchedClassDesc *SC=nullptr) const
Return the number of issue slots required for this MI.
static cl::opt< bool > VerifyScheduling("verify-misched", cl::Hidden, cl::desc("Verify machine instrs before and after machine scheduling"))
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register. ...
void bumpCycle(unsigned NextCycle)
Move the boundary of scheduled code by one cycle.
unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle)
Add the given processor resource to this scheduled zone.
static MachineBasicBlock::const_iterator priorNonDebug(MachineBasicBlock::const_iterator I, MachineBasicBlock::const_iterator Beg)
Decrement this iterator until reaching the top or a non-debug instr.
bool hasReservedResource
Uses a reserved resource.
void scheduleMI(SUnit *SU, bool IsTopNode)
Move an instruction and update register pressure.
virtual void overrideSchedPolicy(MachineSchedPolicy &Policy, unsigned NumRegionInstrs) const
Override generic scheduling policy within a region.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def...
MachineBasicBlock::iterator top() const
void buildDAGWithRegPressure()
Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking enabled.
unsigned WeakSuccsLeft
of weak succs not scheduled.
static void getSchedRegions(MachineBasicBlock *MBB, MBBRegionsVector &Regions, bool RegionsTopDown)
static const char * getReasonStr(GenericSchedulerBase::CandReason Reason)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
static std::string getGraphName(const ScheduleDAG *G)
MachineBasicBlock::iterator begin() const
Returns an iterator to the top of the current scheduling region.
bool isCtrl() const
Shorthand for getKind() != SDep::Data.
Itinerary data supplied by a subtarget to be used by a target.
unsigned NumPredsLeft
of preds not scheduled.
static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop)
void releasePending()
Release pending ready nodes in to the available queue.
void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, bool TrackLaneMasks, bool IgnoreDead)
Analyze the given instruction MI and fill in the Uses, Defs and DeadDefs list based on the MachineOpe...
COFF::MachineTypes Machine
ScheduleDAGMILive * createGenericSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
MachinePassRegistry - Track the registration of machine passes.
List of registers defined and used by a machine instruction.
virtual const TargetInstrInfo * getInstrInfo() const
std::vector< SUnit * >::iterator iterator
void collectVRegUses(SUnit &SU)
virtual void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs)
Initialize the DAG and common scheduler state for a new scheduling region.
unsigned getCurrMOps() const
Micro-ops issued in the current cycle.
const SUnit * getNextClusterSucc() const
void bumpNode(SUnit *SU)
Move the boundary of scheduled code by one SUnit.
SUnit * pickNode(bool &IsTopNode) override
Pick the next node to schedule.
unsigned getSubtreeID(const SUnit *SU) const
Get the ID of the subtree the given DAG node belongs to.
void initCandidate(SchedCandidate &Cand, SUnit *SU, bool AtTop, const RegPressureTracker &RPTracker, RegPressureTracker &TempTracker)
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
SUnit * getSUnit(MachineInstr *MI) const
Returns an existing SUnit for this MI, or nullptr.
void checkAcyclicLatency()
Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic critical path by more cycle...
static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G)
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
void incExecutedResources(unsigned PIdx, unsigned Count)
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
TargetInstrInfo - Interface to description of machine instruction set.
virtual void registerRoots()
Notify this strategy that all roots have been released (including those that depend on EntrySU or Exi...
bool isUnbuffered
Uses an unbuffered resource.
void getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit)
Consider the pressure increase caused by traversing this instruction top-down.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
unsigned getPSetOrMax() const
initializer< Ty > init(const Ty &Val)
bool isCall
Is a function call.
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
unsigned getNextResourceCycle(unsigned PIdx, unsigned Cycles)
Compute the next cycle at which the given processor resource can be scheduled.
CandReason
Represent the type of SchedCandidate found within a single queue.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
Helpers for implementing custom MachineSchedStrategy classes.
bool isArtificial() const
Tests if this is an Order dependence that is marked as "artificial", meaning it isn't necessary for c...
unsigned const MachineRegisterInfo * MRI
PressureChange CurrentMax
bool tryGreater(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
unsigned short Latency
Node latency.
static const unsigned MinSubtreeSize
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void removeReady(SUnit *SU)
Remove SU from the ready set for this boundary.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Summarize the scheduling resources required for an instruction of a particular scheduling class...
void updatePressureDiffs(ArrayRef< RegisterMaskPair > LiveUses)
Update the PressureDiff array for liveness after scheduling this instruction.
void getUpwardPressureDelta(const MachineInstr *MI, PressureDiff &PDiff, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit) const
This is the fast version of querying register pressure that does not directly depend on current liven...
static bool isSchedBoundary(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB, MachineFunction *MF, const TargetInstrInfo *TII)
Return true of the given instruction should not be included in a scheduling region.
Printable printVRegOrUnit(unsigned VRegOrUnit, const TargetRegisterInfo *TRI)
Create Printable object to print virtual registers and physical registers on a raw_ostream.
RegisterPressure computed within a region of instructions delimited by TopPos and BottomPos...
int getNumOccurrences() const
virtual bool doMBBSchedRegionsTopDown() const
If this method returns true, handling of the scheduling regions themselves (in case of a scheduling b...
bool addEdge(SUnit *SuccSU, const SDep &PredDep)
Add a DAG edge to the given SU with the given predecessor dependence data.
Represent the analysis usage information of a pass.
static MachinePassRegistry Registry
Store the state used by GenericScheduler heuristics, required for the lifetime of one invocation of p...
bool checkHazard(SUnit *SU)
Does this SU have a hazard within the current instruction group.
void releasePred(SUnit *SU, SDep *PredEdge)
ReleasePred - Decrement the NumSuccsLeft count of a predecessor.
Track the current register pressure at some position in the instruction stream, and remember the high...
virtual void releaseBottomNode(SUnit *SU)=0
When all successor dependencies have been resolved, free this node for bottom-up scheduling.
Policy for scheduling the next instruction in the candidate's zone.
static ScheduleDAGInstrs * useDefaultMachineSched(MachineSchedContext *C)
A dummy default scheduler factory indicates whether the scheduler is overridden on the command line...
const TargetSchedModel * getSchedModel() const
Gets the machine model for instruction scheduling.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
unsigned getScheduledLatency() const
Get the number of latency cycles "covered" by the scheduled instructions.
List of PressureChanges in order of increasing, unique PSetID.
virtual void exitRegion()
Called when the scheduler has finished scheduling the current region.
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
DOTGraphTraits(bool isSimple=false)
SchedResourceDelta ResDelta
ScheduleDAGInstrs *(*)(MachineSchedContext *) ScheduleDAGCtor
std::unique_ptr< ScheduleDAGMutation > createStoreClusterDAGMutation(const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
static MachineBasicBlock::const_iterator nextIfDebug(MachineBasicBlock::const_iterator I, MachineBasicBlock::const_iterator End)
If this iterator is a debug value, increment until reaching the End or a non-debug instruction...
void initQueues(ArrayRef< SUnit *> TopRoots, ArrayRef< SUnit *> BotRoots)
Release ExitSU predecessors and setup scheduler queues.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
unsigned getWeakLeft(const SUnit *SU, bool isTop)
bool isDebugInstr() const
void releaseSuccessors(SUnit *SU)
releaseSuccessors - Call releaseSucc on each of SU's successors.
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream...
std::string & str()
Flushes the stream contents to the target string and returns the string's reference.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void viewGraph() override
Out-of-line implementation with no arguments is handy for gdb.
void setPolicy(CandPolicy &Policy, bool IsPostRA, SchedBoundary &CurrZone, SchedBoundary *OtherZone)
Set the CandPolicy given a scheduling zone given the current resources and latencies inside and outsi...
virtual bool enableMachineScheduler() const
True if the subtarget should run MachineScheduler after aggressive coalescing.
static cl::opt< bool > EnableRegPressure("misched-regpressure", cl::Hidden, cl::desc("Enable register pressure scheduling."), cl::init(true))
void sort(IteratorTy Start, IteratorTy End)
iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
unsigned WeakPredsLeft
of weak preds not scheduled.
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem)
static cl::opt< unsigned > SchedOnlyBlock("misched-only-block", cl::Hidden, cl::desc("Only schedule this MBB#"))
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::vector< unsigned > MaxSetPressure
Map of max reg pressure indexed by pressure set ID, not class ID.
void adjustLaneLiveness(const LiveIntervals &LIS, const MachineRegisterInfo &MRI, SlotIndex Pos, MachineInstr *AddFlagsMI=nullptr)
Use liveness information to find out which uses/defs are partially undefined/dead and adjust the Regi...
virtual bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const
Test if the given instruction should be considered a scheduling boundary.
Iterator for intrusive lists based on ilist_node.
std::unique_ptr< ScheduleDAGMutation > createLoadClusterDAGMutation(const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
void registerRoots() override
Notify this strategy that all roots have been released (including those that depend on EntrySU or Exi...
void reschedulePhysRegCopies(SUnit *SU, bool isTop)
AnalysisUsage & addRequiredID(const void *ID)
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...
static cl::opt< unsigned > MISchedCutoff("misched-cutoff", cl::Hidden, cl::desc("Stop scheduling after N instructions"), cl::init(~0U))
static ScheduleDAGInstrs * createILPMinScheduler(MachineSchedContext *C)
MachineInstrBuilder MachineInstrBuilder & DefMI
static cl::opt< bool > EnableMachineSched("enable-misched", cl::desc("Enable the machine instruction scheduling pass."), cl::init(true), cl::Hidden)
void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs) override
Implement the ScheduleDAGInstrs interface for handling the next scheduling region.
cl::opt< bool > DumpCriticalPathLength("misched-dcpl", cl::Hidden, cl::desc("Print critical path length to stdout"))
void releaseNode(SUnit *SU, unsigned ReadyCycle)
unsigned getMicroOpFactor() const
Multiply number of micro-ops by this factor to normalize it relative to other resources.
CHAIN = SC CHAIN, Imm128 - System call.
const RegPressureTracker & getTopRPTracker() const
StringRef getColorString(unsigned NodeNumber)
Get a color string for this node number.
void updateScheduledPressure(const SUnit *SU, const std::vector< unsigned > &NewMaxPressure)
bool isResourceLimited() const
void setPreservesCFG()
This function should be called by the pass, iff they do not:
LiveInterval & getInterval(unsigned Reg)
int biasPhysRegCopy(const SUnit *SU, bool isTop)
Minimize physical register live ranges.
std::unique_ptr< ScheduleDAGMutation > createCopyConstrainDAGMutation(const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
static cl::opt< bool > EnableCyclicPath("misched-cyclicpath", cl::Hidden, cl::desc("Enable cyclic critical path analysis."), cl::init(true))
void initResourceDelta(const ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel)
INITIALIZE_PASS(PostMachineScheduler, "postmisched", "PostRA Machine Instruction Scheduler", false, false) PostMachineScheduler
const Function & getFunction() const
Return the LLVM function that this machine code represents.
~ScheduleDAGMILive() override
void initializeMachineSchedulerPass(PassRegistry &)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
unsigned getOtherResourceCount(unsigned &OtherCritIdx)
void dumpPolicy() const override
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarilly including Idx...
virtual void finalizeSchedule()
Allow targets to perform final scheduling actions at the level of the whole MachineFunction.
void tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand)
Apply a set of heuristics to a new candidate for PostRA scheduling.
bool tryLess(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
Return true if this heuristic determines order.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
PressureChange CriticalMax
virtual void schedule()=0
Orders nodes according to selected style.
unsigned getResourceFactor(unsigned ResIdx) const
Multiply the number of units consumed for a resource by this factor to normalize it relative to other...
typename SuperClass::iterator iterator
void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos)
Change the position of an instruction within the basic block and update live ranges and region bounda...
unsigned getNumProcResourceKinds() const
Get the number of kinds of resources for this target.
static MachineSchedRegistry DefaultSchedRegistry("default", "Use the target's default scheduler choice.", useDefaultMachineSched)
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
void schedNode(SUnit *SU, bool IsTopNode) override
Update the scheduler's state after scheduling a node.
virtual void scheduleTree(unsigned SubtreeID)
Scheduler callback to notify that a new subtree is scheduled.
void releasePredecessors(SUnit *SU)
releasePredecessors - Call releasePred on each of SU's predecessors.
unsigned getSubtreeLevel(unsigned SubtreeID) const
Get the connection level of a subtree.
void initialize(ScheduleDAGMI *dag) override
Initialize the strategy after building the DAG for a new region.
virtual void tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone) const
Apply a set of heuristics to a new candidate.
virtual SUnit * pickNode(bool &IsTopNode)=0
Pick the next node to schedule, or return NULL.
unsigned getHeight() const
Returns the height of this node, which is the length of the maximum path down to any node which has n...
A ScheduleDAG for scheduling lists of MachineInstr.
reverse_iterator rend() const
Representation of each machine instruction.
SUnit ExitSU
Special node for the region exit.
void initializePostMachineSchedulerPass(PassRegistry &)
void dump(const TargetRegisterInfo &TRI) const
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void initialize(ScheduleDAGMI *Dag) override
Initialize the strategy after building the DAG for a new region.
const TargetRegisterInfo * TRI
Target processor register info.
SUnit * pickOnlyChoice()
Call this before applying any other heuristics to the Available queue.
void findRootsAndBiasEdges(SmallVectorImpl< SUnit *> &TopRoots, SmallVectorImpl< SUnit *> &BotRoots)
void dumpRegSetPressure(ArrayRef< unsigned > SetPressure, const TargetRegisterInfo *TRI)
Status of an instruction's critical resource consumption.
~ScheduleDAGMI() override
LiveIntervals * getLIS() const
char & PostMachineSchedulerID
PostMachineScheduler - This pass schedules machine instructions postRA.
cl::opt< bool > ForceBottomUp
bool verify(Pass *p=nullptr, const char *Banner=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use...
void dumpScheduledState() const
MachineBasicBlock::iterator bottom() const
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
MachineSchedStrategy - Interface to the scheduling algorithm used by ScheduleDAGMI.
Capture a change in pressure for a single pressure set.
void getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit)
Consider the pressure increase caused by traversing this instruction bottom-up.
const SUnit * getNextClusterPred() const
static ScheduleDAGInstrs * createConveringSched(MachineSchedContext *C)
void placeDebugValues()
Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
static cl::opt< unsigned > ViewMISchedCutoff("view-misched-cutoff", cl::Hidden, cl::desc("Hide nodes with more predecessor/successor than cutoff"))
In some situations a few uninteresting nodes depend on nearly all other nodes in the graph...
unsigned getLatencyStallCycles(SUnit *SU)
Get the difference between the given SUnit's ready time and the current cycle.
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
SUnit * pickNode(bool &IsTopNode) override
Pick the best node to balance the schedule. Implements MachineSchedStrategy.
void pickNodeFromQueue(SchedBoundary &Zone, const CandPolicy &ZonePolicy, const RegPressureTracker &RPTracker, SchedCandidate &Candidate)
Pick the best candidate from the queue.
const TargetInstrInfo * TII
Target instruction information.
static bool isNodeHidden(const SUnit *Node)
Kind getKind() const
Returns an enum value representing the kind of the dependence.
static MachineSchedRegistry GenericSchedRegistry("converge", "Standard converging scheduler.", createConveringSched)
virtual bool enablePostRAScheduler() const
True if the subtarget should run a scheduler after register allocation.
static cl::opt< unsigned > ReadyListLimit("misched-limit", cl::Hidden, cl::desc("Limit ready list to N instructions"), cl::init(256))
Avoid quadratic complexity in unusually large basic blocks by limiting the size of the ready lists...
unsigned NodeNum
Entry # of node in the node vector.
const std::vector< PressureChange > & getRegionCriticalPSets() const
bool isCtrlDep() const
Tests if this is not an SDep::Data dependence.
void registerRoots() override
Notify this strategy that all roots have been released (including those that depend on EntrySU or Exi...
MachineBasicBlock::iterator end() const
Returns an iterator to the bottom of the current scheduling region.
bool tryPressure(const PressureChange &TryP, const PressureChange &CandP, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason, const TargetRegisterInfo *TRI, const MachineFunction &MF)
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool addPred(const SDep &D, bool Required=true)
Adds the specified edge as a pred of the current node if not already.
bool operator<(int64_t V1, const APSInt &V2)
A raw_ostream that writes to an std::string.
bool isTrackingPressure() const
Return true if register pressure tracking is enabled.
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
bool isLocal(SlotIndex Start, SlotIndex End) const
True iff this segment is a single segment that lies between the specified boundaries, exclusively.
static bool checkResourceLimit(unsigned LFactor, unsigned Count, unsigned Latency)
Given a Count of resource usage and a Latency value, return true if a SchedBoundary becomes resource ...
void postprocessDAG()
Apply each ScheduleDAGMutation step in order.
nonconst_iterator getNonConstIterator() const
virtual ScheduleHazardRecognizer * CreateTargetMIHazardRecognizer(const InstrItineraryData *, const ScheduleDAG *DAG) const
Allocate and return a hazard recognizer to use for this target when scheduling the machine instructio...
SmallVector< SDep, 4 > Succs
All sunit successors.
bool isCluster() const
Tests if this is an Order dependence that is marked as "cluster", meaning it is artificial and wants ...
static const Function * getParent(const Value *V)
Arbitrary strong DAG edge (no real dependence).
bool isWeak() const
Tests if this a weak dependence.
This class implements an extremely fast bulk output stream that can only output to a stream...
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
Machine Instruction Scheduler
void clear()
clear - Erase all elements from the queue.
INITIALIZE_PASS_BEGIN(MachineScheduler, DEBUG_TYPE, "Machine Instruction Scheduler", false, false) INITIALIZE_PASS_END(MachineScheduler
bool canAddEdge(SUnit *SuccSU, SUnit *PredSU)
True if an edge can be added from PredSU to SuccSU without creating a cycle.
static MachineSchedRegistry ILPMinRegistry("ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler)
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
std::vector< SUnit > SUnits
The scheduling units.
bool getMemOpBaseRegImmOfs(MachineInstr &LdSt, unsigned &BaseReg, int64_t &Offset, const TargetRegisterInfo *TRI) const override
Get the base register and byte offset of a load/store instr.
PriorityQueue - This class behaves like std::priority_queue and provides a few additional convenience...
const MachineOperand & getOperand(unsigned i) const
SlotIndex - An opaque wrapper around machine indexes.
void finishBlock() override
Cleans up after scheduling in the given block.
void setBest(SchedCandidate &Best)
virtual unsigned getRegPressureSetScore(const MachineFunction &MF, unsigned PSetID) const
Return a heuristic for the machine scheduler to compare the profitability of increasing one register ...
void pickNodeFromQueue(SchedCandidate &Cand)
Scheduling unit. This is a node in the scheduling DAG.
This file describes how to lower LLVM code to machine code.
void addMutation(std::unique_ptr< ScheduleDAGMutation > Mutation)
Add a postprocessing step to the DAG builder.
cl::opt< bool > ForceTopDown
ILPValue getILP(const SUnit *SU) const
Get the ILP value for a DAG node.
static cl::opt< bool > EnableMemOpCluster("misched-cluster", cl::Hidden, cl::desc("Enable memop clustering."), cl::init(true))
bool isArtificialDep() const