50 #include "llvm/Config/llvm-config.h" 74 #define DEBUG_TYPE "machine-scheduler" 79 cl::desc(
"Force top-down list scheduling"));
81 cl::desc(
"Force bottom-up list scheduling"));
84 cl::desc(
"Print critical path length to stdout"));
88 cl::desc(
"Verify machine instrs before and after machine scheduling"));
94 cl::desc(
"Pop up a window to show MISched dags after they are processed"));
99 cl::desc(
"Hide nodes with more predecessor/successor than cutoff"));
105 cl::desc(
"Only schedule this function"));
107 cl::desc(
"Only schedule this MBB#"));
111 static const bool ViewMISchedDAGs =
false;
112 static const bool PrintDAGs =
false;
127 cl::desc(
"Enable memop clustering."),
134 void MachineSchedStrategy::anchor() {}
136 void ScheduleDAGMutation::anchor() {}
165 class MachineScheduler :
public MachineSchedulerBase {
180 class PostMachineScheduler :
public MachineSchedulerBase {
182 PostMachineScheduler();
201 "Machine Instruction Scheduler",
false,
false)
210 MachineScheduler::MachineScheduler() : MachineSchedulerBase(
ID) {
214 void MachineScheduler::getAnalysisUsage(
AnalysisUsage &AU)
const {
232 "PostRA Machine Instruction Scheduler",
false,
false)
234 PostMachineScheduler::PostMachineScheduler() : MachineSchedulerBase(
ID) {
238 void PostMachineScheduler::getAnalysisUsage(
AnalysisUsage &AU)
const {
261 cl::desc(
"Machine instruction scheduler to use"));
269 cl::desc(
"Enable the machine instruction scheduling pass."),
cl::init(
true),
273 "enable-post-misched",
274 cl::desc(
"Enable the post-ra machine instruction scheduling pass."),
281 assert(I != Beg &&
"reached the top of the region, cannot decrement");
283 if (!I->isDebugInstr())
302 for(; I != End; ++
I) {
303 if (!I->isDebugInstr())
367 if (!EnableMachineSched)
376 MLI = &getAnalysis<MachineLoopInfo>();
377 MDT = &getAnalysis<MachineDominatorTree>();
378 PassConfig = &getAnalysis<TargetPassConfig>();
379 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
381 LIS = &getAnalysis<LiveIntervals>();
385 MF->verify(
this,
"Before machine scheduling.");
387 RegClassInfo->runOnMachineFunction(*MF);
391 std::unique_ptr<ScheduleDAGInstrs>
Scheduler(createMachineScheduler());
392 scheduleRegions(*Scheduler,
false);
396 MF->verify(
this,
"After machine scheduling.");
405 if (!EnablePostRAMachineSched)
415 MLI = &getAnalysis<MachineLoopInfo>();
416 PassConfig = &getAnalysis<TargetPassConfig>();
417 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
420 MF->verify(
this,
"Before post machine scheduling.");
424 std::unique_ptr<ScheduleDAGInstrs>
Scheduler(createPostMachineScheduler());
425 scheduleRegions(*Scheduler,
true);
428 MF->verify(
this,
"After post machine scheduling.");
459 unsigned NumRegionInstrs;
463 RegionBegin(B), RegionEnd(E), NumRegionInstrs(N) {}
472 bool RegionsTopDown) {
478 RegionEnd != MBB->
begin(); RegionEnd =
I) {
481 if (RegionEnd != MBB->
end() ||
488 unsigned NumRegionInstrs = 0;
490 for (;I != MBB->
begin(); --
I) {
503 if (NumRegionInstrs != 0)
504 Regions.
push_back(SchedRegion(I, RegionEnd, NumRegionInstrs));
519 MBB != MBBEnd; ++MBB) {
527 && (int)SchedOnlyBlock != MBB->getNumber())
548 R != MBBRegions.
end(); ++R) {
551 unsigned NumRegionInstrs = R->NumRegionInstrs;
555 Scheduler.
enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
558 if (I == RegionEnd || I == std::prev(RegionEnd)) {
566 <<
" " << MBB->getName() <<
"\n From: " << *I
568 if (RegionEnd != MBB->end())
dbgs() << *RegionEnd;
569 else dbgs() <<
"End";
570 dbgs() <<
" RegionInstrs: " << NumRegionInstrs <<
'\n');
572 errs() << MF->getName();
573 errs() <<
":%bb. " << MBB->getNumber();
574 errs() <<
" " << MBB->getName() <<
" \n";
598 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 601 for (
const SUnit *SU : Queue)
602 dbgs() << SU->NodeNum <<
" ";
626 NextClusterSucc = SuccSU;
631 dbgs() <<
"*** Scheduling failed! ***\n";
633 dbgs() <<
" has been released too many times!\n";
644 SchedImpl->releaseTopNode(SuccSU);
650 releaseSucc(SU, &Succ);
663 NextClusterPred = PredSU;
668 dbgs() <<
"*** Scheduling failed! ***\n";
670 dbgs() <<
" has been released too many times!\n";
681 SchedImpl->releaseBottomNode(PredSU);
687 releasePred(SU, &Pred);
692 SchedImpl->enterMBB(bb);
696 SchedImpl->leaveMBB();
707 unsigned regioninstrs)
711 SchedImpl->initPolicy(begin, end, regioninstrs);
719 if (&*RegionBegin == MI)
723 BB->splice(InsertPos, BB, MI);
727 LIS->handleMove(*MI,
true);
730 if (RegionBegin == InsertPos)
736 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
737 CurrentTop = CurrentBottom;
740 ++NumInstrsScheduled;
759 findRootsAndBiasEdges(TopRoots, BotRoots);
762 if (PrintDAGs)
dump();
763 if (ViewMISchedDAGs) viewGraph();
767 SchedImpl->initialize(
this);
770 initQueues(TopRoots, BotRoots);
772 bool IsTopNode =
false;
774 LLVM_DEBUG(
dbgs() <<
"** ScheduleDAGMI::schedule picking next node\n");
775 SUnit *SU = SchedImpl->pickNode(IsTopNode);
779 if (!checkSchedLimit())
785 if (&*CurrentTop == MI)
786 CurrentTop =
nextIfDebug(++CurrentTop, CurrentBottom);
788 moveInstruction(MI, CurrentTop);
794 CurrentBottom = priorII;
796 if (&*CurrentTop == MI)
798 moveInstruction(MI, CurrentBottom);
806 SchedImpl->schedNode(SU, IsTopNode);
808 updateQueues(SU, IsTopNode);
810 assert(CurrentTop == CurrentBottom &&
"Nonempty unscheduled zone.");
815 dbgs() <<
"*** Final schedule for " 824 for (
auto &m : Mutations)
831 for (
SUnit &SU : SUnits) {
832 assert(!SU.isBoundaryNode() &&
"Boundary node should not be in SUnits");
835 SU.biasCriticalPath();
838 if (!SU.NumPredsLeft)
841 if (!SU.NumSuccsLeft)
844 ExitSU.biasCriticalPath();
850 NextClusterSucc =
nullptr;
851 NextClusterPred =
nullptr;
857 for (
SUnit *SU : TopRoots)
858 SchedImpl->releaseTopNode(SU);
864 SchedImpl->releaseBottomNode(*
I);
867 releaseSuccessors(&EntrySU);
868 releasePredecessors(&ExitSU);
870 SchedImpl->registerRoots();
874 CurrentBottom = RegionEnd;
881 releaseSuccessors(SU);
883 releasePredecessors(SU);
892 BB->splice(RegionBegin, BB, FirstDbgValue);
893 RegionBegin = FirstDbgValue;
896 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
897 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
898 std::pair<MachineInstr *, MachineInstr *>
P = *std::prev(DI);
901 if (&*RegionBegin == DbgValue)
903 BB->splice(++OrigPrevMI, BB, DbgValue);
904 if (OrigPrevMI == std::prev(RegionEnd))
905 RegionEnd = DbgValue;
908 FirstDbgValue =
nullptr;
911 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 914 if (
SUnit *SU = getSUnit(&(*
MI)))
917 dbgs() <<
"Missing SUnit\n";
938 if (TrackLaneMasks && !MO.isUse())
946 if (TrackLaneMasks) {
947 bool FoundDef =
false;
949 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
960 for (; UI != VRegUses.end(); ++UI) {
964 if (UI == VRegUses.end())
976 unsigned regioninstrs)
982 LiveRegionEnd = (RegionEnd == bb->
end()) ? RegionEnd : std::next(RegionEnd);
984 SUPressureDiffs.clear();
986 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
987 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
989 assert((!ShouldTrackLaneMasks || ShouldTrackPressure) &&
990 "ShouldTrackLaneMasks requires ShouldTrackPressure");
997 VRegUses.setUniverse(
MRI.getNumVirtRegs());
998 for (
SUnit &SU : SUnits)
1001 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
1002 ShouldTrackLaneMasks,
false);
1003 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1004 ShouldTrackLaneMasks,
false);
1007 RPTracker.closeRegion();
1012 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
1013 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
1018 TopRPTracker.closeTop();
1019 BotRPTracker.closeBottom();
1021 BotRPTracker.initLiveThru(RPTracker);
1022 if (!BotRPTracker.getLiveThru().empty()) {
1023 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
1030 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
1033 if (LiveRegionEnd != RegionEnd) {
1035 BotRPTracker.recede(&LiveUses);
1036 updatePressureDiffs(LiveUses);
1041 dbgs() <<
"Bottom Pressure:\n";
1044 assert((BotRPTracker.getPos() == RegionEnd ||
1045 (RegionEnd->isDebugInstr() &&
1046 BotRPTracker.getPos() ==
priorNonDebug(RegionEnd, RegionBegin))) &&
1047 "Can't find the region bottom");
1051 RegionCriticalPSets.clear();
1054 for (
unsigned i = 0,
e = RegionPressure.size(); i <
e; ++i) {
1055 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
1056 if (RegionPressure[i] > Limit) {
1058 <<
" Actual " << RegionPressure[i] <<
"\n");
1064 : RegionCriticalPSets)
dbgs()
1065 <<
TRI->getRegPressureSetName(RCPS.getPSet()) <<
" ";
1071 const std::vector<unsigned> &NewMaxPressure) {
1073 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
1077 unsigned ID = PC.getPSet();
1078 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1080 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1081 if ((
int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
1083 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1085 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1086 if (NewMaxPressure[ID] >= Limit - 2) {
1088 << NewMaxPressure[
ID]
1089 << ((NewMaxPressure[
ID] > Limit) ?
" > " :
" <= ")
1090 << Limit <<
"(+ " << BotRPTracker.getLiveThru()[
ID]
1101 unsigned Reg =
P.RegUnit;
1106 if (ShouldTrackLaneMasks) {
1111 bool Decrement =
P.LaneMask.any();
1114 :
make_range(VRegUses.find(Reg), VRegUses.end())) {
1115 SUnit &SU = *V2SU.SU;
1144 assert(VNI &&
"No live value at use.");
1146 :
make_range(VRegUses.find(Reg), VRegUses.end())) {
1147 SUnit *SU = V2SU.SU;
1167 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1168 if (EntrySU.getInstr() !=
nullptr)
1169 dumpNodeAll(EntrySU);
1170 for (
const SUnit &SU : SUnits) {
1172 if (ShouldTrackPressure) {
1173 dbgs() <<
" Pressure Diff : ";
1174 getPressureDiff(&SU).dump(*
TRI);
1176 dbgs() <<
" Single Issue : ";
1177 if (SchedModel.mustBeginGroup(SU.getInstr()) &&
1178 SchedModel.mustEndGroup(SU.getInstr()))
1184 if (ExitSU.getInstr() !=
nullptr)
1185 dumpNodeAll(ExitSU);
1202 buildDAGWithRegPressure();
1207 findRootsAndBiasEdges(TopRoots, BotRoots);
1211 SchedImpl->initialize(
this);
1214 if (PrintDAGs)
dump();
1215 if (ViewMISchedDAGs) viewGraph();
1218 initQueues(TopRoots, BotRoots);
1220 bool IsTopNode =
false;
1222 LLVM_DEBUG(
dbgs() <<
"** ScheduleDAGMILive::schedule picking next node\n");
1223 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1227 if (!checkSchedLimit())
1230 scheduleMI(SU, IsTopNode);
1233 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1234 if (!ScheduledTrees.test(SubtreeID)) {
1235 ScheduledTrees.set(SubtreeID);
1236 DFSResult->scheduleTree(SubtreeID);
1237 SchedImpl->scheduleTree(SubtreeID);
1242 SchedImpl->schedNode(SU, IsTopNode);
1244 updateQueues(SU, IsTopNode);
1246 assert(CurrentTop == CurrentBottom &&
"Nonempty unscheduled zone.");
1251 dbgs() <<
"*** Final schedule for " 1260 if (!ShouldTrackPressure) {
1262 RegionCriticalPSets.clear();
1263 buildSchedGraph(AA);
1268 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1269 ShouldTrackLaneMasks,
true);
1272 if (LiveRegionEnd != RegionEnd)
1276 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
1286 ScheduledTrees.clear();
1287 DFSResult->resize(SUnits.size());
1288 DFSResult->compute(SUnits);
1289 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1320 if (!BB->isSuccessor(BB))
1323 unsigned MaxCyclicLatency = 0;
1326 unsigned Reg =
P.RegUnit;
1335 const SUnit *DefSU = getSUnit(DefMI);
1339 unsigned LiveOutHeight = DefSU->
getHeight();
1343 :
make_range(VRegUses.find(Reg), VRegUses.end())) {
1344 SUnit *SU = V2SU.SU;
1356 unsigned CyclicLatency = 0;
1358 CyclicLatency = LiveOutDepth - SU->
getDepth();
1361 if (LiveInHeight > LiveOutHeight) {
1362 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1363 CyclicLatency = LiveInHeight - LiveOutHeight;
1368 << SU->
NodeNum <<
") = " << CyclicLatency <<
"c\n");
1369 if (CyclicLatency > MaxCyclicLatency)
1370 MaxCyclicLatency = CyclicLatency;
1373 LLVM_DEBUG(
dbgs() <<
"Cyclic Critical Path: " << MaxCyclicLatency <<
"c\n");
1374 return MaxCyclicLatency;
1382 if (ShouldTrackPressure) {
1383 assert(TopRPTracker.getPos() == RegionBegin &&
"bad initial Top tracker");
1384 TopRPTracker.setPos(CurrentTop);
1395 if (&*CurrentTop == MI)
1396 CurrentTop =
nextIfDebug(++CurrentTop, CurrentBottom);
1398 moveInstruction(MI, CurrentTop);
1399 TopRPTracker.setPos(MI);
1402 if (ShouldTrackPressure) {
1405 RegOpers.
collect(*MI, *
TRI,
MRI, ShouldTrackLaneMasks,
false);
1406 if (ShouldTrackLaneMasks) {
1415 TopRPTracker.advance(RegOpers);
1416 assert(TopRPTracker.getPos() == CurrentTop &&
"out of sync");
1418 TopRPTracker.getRegSetPressureAtPos(),
TRI););
1420 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
1426 if (&*priorII == MI)
1427 CurrentBottom = priorII;
1429 if (&*CurrentTop == MI) {
1431 TopRPTracker.setPos(CurrentTop);
1433 moveInstruction(MI, CurrentBottom);
1435 BotRPTracker.setPos(CurrentBottom);
1437 if (ShouldTrackPressure) {
1439 RegOpers.
collect(*MI, *
TRI,
MRI, ShouldTrackLaneMasks,
false);
1440 if (ShouldTrackLaneMasks) {
1449 if (BotRPTracker.getPos() != CurrentBottom)
1450 BotRPTracker.recedeSkipDebugValues();
1452 BotRPTracker.recede(RegOpers, &LiveUses);
1453 assert(BotRPTracker.getPos() == CurrentBottom &&
"out of sync");
1455 BotRPTracker.getRegSetPressureAtPos(),
TRI););
1457 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
1458 updatePressureDiffs(LiveUses);
1478 : SU(su), BaseOp(Op),
Offset(ofs) {}
1480 bool operator<(
const MemOpInfo &RHS)
const {
1481 if (BaseOp->
getType() != RHS.BaseOp->getType())
1482 return BaseOp->
getType() < RHS.BaseOp->getType();
1484 if (BaseOp->
isReg())
1486 std::make_tuple(RHS.BaseOp->getReg(), RHS.Offset,
1488 if (BaseOp->
isFI()) {
1496 if (BaseOp->
getIndex() != RHS.BaseOp->getIndex())
1497 return StackGrowsDown ? BaseOp->
getIndex() > RHS.BaseOp->getIndex()
1498 : BaseOp->
getIndex() < RHS.BaseOp->getIndex();
1500 if (Offset != RHS.Offset)
1501 return Offset < RHS.Offset;
1503 return SU->
NodeNum < RHS.SU->NodeNum;
1518 :
TII(tii),
TRI(tri), IsLoad(IsLoad) {}
1526 class StoreClusterMutation :
public BaseMemOpClusterMutation {
1530 : BaseMemOpClusterMutation(tii, tri,
false) {}
1533 class LoadClusterMutation :
public BaseMemOpClusterMutation {
1536 : BaseMemOpClusterMutation(tii, tri,
true) {}
1543 std::unique_ptr<ScheduleDAGMutation>
1546 return EnableMemOpCluster ? std::make_unique<LoadClusterMutation>(
TII,
TRI)
1550 std::unique_ptr<ScheduleDAGMutation>
1553 return EnableMemOpCluster ? std::make_unique<StoreClusterMutation>(
TII,
TRI)
1559 void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1562 for (
SUnit *SU : MemOps) {
1566 MemOpRecords.
push_back(MemOpInfo(SU, BaseOp, Offset));
1568 if (MemOpRecords.
size() < 2)
1572 unsigned ClusterLength = 1;
1573 for (
unsigned Idx = 0, End = MemOpRecords.
size(); Idx < (End - 1); ++Idx) {
1574 SUnit *SUa = MemOpRecords[Idx].SU;
1575 SUnit *SUb = MemOpRecords[Idx+1].SU;
1578 if (
TII->shouldClusterMemOps(*MemOpRecords[Idx].BaseOp,
1579 *MemOpRecords[Idx + 1].BaseOp,
1610 unsigned ChainPredID = DAG->
SUnits.size();
1619 Chain.push_back(&SU);
1623 for (
auto &SCD : StoreChains)
1624 clusterNeighboringMemOps(SCD.second, DAG);
1657 std::unique_ptr<ScheduleDAGMutation>
1660 return std::make_unique<CopyConstrain>(
TII,
TRI);
1705 unsigned LocalReg = SrcReg;
1706 unsigned GlobalReg = DstReg;
1708 if (!LocalLI->
isLocal(RegionBeginIdx, RegionEndIdx)) {
1712 if (!LocalLI->
isLocal(RegionBeginIdx, RegionEndIdx))
1723 if (GlobalSegment == GlobalLI->
end())
1730 if (GlobalSegment->contains(LocalLI->
beginIndex()))
1733 if (GlobalSegment == GlobalLI->
end())
1737 if (GlobalSegment != GlobalLI->
begin()) {
1740 GlobalSegment->start)) {
1751 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
1752 "Disconnected LRG within the scheduling region.");
1768 for (
const SDep &Succ : LastLocalSU->
Succs) {
1783 for (
const SDep &Pred : GlobalSU->
Preds) {
1786 if (Pred.
getSUnit() == FirstLocalSU)
1796 LLVM_DEBUG(
dbgs() <<
" Local use SU(" << (*I)->NodeNum <<
") -> SU(" 1797 << GlobalSU->
NodeNum <<
")\n");
1801 I = GlobalUses.
begin(),
E = GlobalUses.
end();
I !=
E; ++
I) {
1802 LLVM_DEBUG(
dbgs() <<
" Global use SU(" << (*I)->NodeNum <<
") -> SU(" 1803 << FirstLocalSU->
NodeNum <<
")\n");
1815 if (FirstPos == DAG->
end())
1825 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
1843 unsigned Latency,
bool AfterSchedNode) {
1844 int ResCntFactor = (int)(Count - (Latency * LFactor));
1846 return ResCntFactor >= (int)LFactor;
1848 return ResCntFactor > (int)LFactor;
1855 if (HazardRec && HazardRec->isEnabled()) {
1857 HazardRec =
nullptr;
1861 CheckPending =
false;
1865 ExpectedLatency = 0;
1866 DependentLatency = 0;
1868 MaxExecutedResCount = 0;
1870 IsResourceLimited =
false;
1871 ReservedCycles.clear();
1872 ReservedCyclesIndex.clear();
1877 MaxObservedStall = 0;
1880 ExecutedResCounts.resize(1);
1881 assert(!ExecutedResCounts[0] &&
"nonzero count for bad resource");
1897 unsigned PIdx = PI->ProcResourceIdx;
1899 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1908 SchedModel = smodel;
1910 if (SchedModel->hasInstrSchedModel()) {
1911 unsigned ResourceCount = SchedModel->getNumProcResourceKinds();
1912 ReservedCyclesIndex.resize(ResourceCount);
1913 ExecutedResCounts.resize(ResourceCount);
1914 unsigned NumUnits = 0;
1916 for (
unsigned i = 0; i < ResourceCount; ++i) {
1917 ReservedCyclesIndex[i] = NumUnits;
1918 NumUnits += SchedModel->getProcResource(i)->NumUnits;
1921 ReservedCycles.resize(NumUnits, InvalidCycle);
1937 if (ReadyCycle > CurrCycle)
1938 return ReadyCycle - CurrCycle;
1946 unsigned NextUnreserved = ReservedCycles[InstanceIdx];
1948 if (NextUnreserved == InvalidCycle)
1952 NextUnreserved += Cycles;
1953 return NextUnreserved;
1959 std::pair<unsigned, unsigned>
1962 unsigned InstanceIdx = 0;
1963 unsigned StartIndex = ReservedCyclesIndex[PIdx];
1964 unsigned NumberOfInstances = SchedModel->getProcResource(PIdx)->NumUnits;
1965 assert(NumberOfInstances > 0 &&
1966 "Cannot have zero instances of a ProcResource");
1968 for (
unsigned I = StartIndex, End = StartIndex + NumberOfInstances;
I < End;
1970 unsigned NextUnreserved = getNextResourceCycleByInstance(
I, Cycles);
1971 if (MinNextUnreserved > NextUnreserved) {
1973 MinNextUnreserved = NextUnreserved;
1976 return std::make_pair(MinNextUnreserved, InstanceIdx);
1993 if (HazardRec->isEnabled()
1998 unsigned uops = SchedModel->getNumMicroOps(SU->
getInstr());
1999 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
2001 << SchedModel->getNumMicroOps(SU->
getInstr()) <<
'\n');
2006 ((isTop() && SchedModel->mustBeginGroup(SU->
getInstr())) ||
2007 (!isTop() && SchedModel->mustEndGroup(SU->
getInstr())))) {
2009 << (isTop() ?
"begin" :
"end") <<
" group\n");
2016 make_range(SchedModel->getWriteProcResBegin(SC),
2017 SchedModel->getWriteProcResEnd(SC))) {
2018 unsigned ResIdx = PE.ProcResourceIdx;
2019 unsigned Cycles = PE.Cycles;
2020 unsigned NRCycle, InstanceIdx;
2021 std::tie(NRCycle, InstanceIdx) = getNextResourceCycle(ResIdx, Cycles);
2022 if (NRCycle > CurrCycle) {
2024 MaxObservedStall =
std::max(Cycles, MaxObservedStall);
2027 << SchedModel->getResourceName(ResIdx)
2028 <<
'[' << InstanceIdx - ReservedCyclesIndex[ResIdx] <<
']' 2029 <<
"=" << NRCycle <<
"c\n");
2040 SUnit *LateSU =
nullptr;
2041 unsigned RemLatency = 0;
2042 for (
SUnit *SU : ReadySUs) {
2043 unsigned L = getUnscheduledLatency(SU);
2044 if (L > RemLatency) {
2051 << LateSU->
NodeNum <<
") " << RemLatency <<
"c\n");
2062 if (!SchedModel->hasInstrSchedModel())
2065 unsigned OtherCritCount = Rem->RemIssueCount
2066 + (RetiredMOps * SchedModel->getMicroOpFactor());
2067 LLVM_DEBUG(
dbgs() <<
" " << Available.getName() <<
" + Remain MOps: " 2068 << OtherCritCount / SchedModel->getMicroOpFactor() <<
'\n');
2069 for (
unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
2070 PIdx != PEnd; ++PIdx) {
2071 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
2072 if (OtherCount > OtherCritCount) {
2073 OtherCritCount = OtherCount;
2074 OtherCritIdx = PIdx;
2079 dbgs() <<
" " << Available.getName() <<
" + Remain CritRes: " 2080 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
2081 <<
" " << SchedModel->getResourceName(OtherCritIdx) <<
"\n");
2083 return OtherCritCount;
2094 if (ReadyCycle > CurrCycle)
2095 MaxObservedStall =
std::max(ReadyCycle - CurrCycle, MaxObservedStall);
2098 if (ReadyCycle < MinReadyCycle)
2099 MinReadyCycle = ReadyCycle;
2103 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2104 bool HazardDetected = (!IsBuffered && ReadyCycle > CurrCycle) ||
2107 if (!HazardDetected) {
2111 Pending.remove(Pending.begin() + Idx);
2121 if (SchedModel->getMicroOpBufferSize() == 0) {
2123 "MinReadyCycle uninitialized");
2124 if (MinReadyCycle > NextCycle)
2125 NextCycle = MinReadyCycle;
2128 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
2129 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2132 if ((NextCycle - CurrCycle) > DependentLatency)
2133 DependentLatency = 0;
2135 DependentLatency -= (NextCycle - CurrCycle);
2137 if (!HazardRec->isEnabled()) {
2139 CurrCycle = NextCycle;
2142 for (; CurrCycle != NextCycle; ++CurrCycle) {
2144 HazardRec->AdvanceCycle();
2146 HazardRec->RecedeCycle();
2149 CheckPending =
true;
2152 getScheduledLatency(),
true);
2154 LLVM_DEBUG(
dbgs() <<
"Cycle: " << CurrCycle <<
' ' << Available.getName()
2159 ExecutedResCounts[PIdx] += Count;
2160 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2161 MaxExecutedResCount = ExecutedResCounts[PIdx];
2173 unsigned Factor = SchedModel->getResourceFactor(PIdx);
2174 unsigned Count = Factor * Cycles;
2175 LLVM_DEBUG(
dbgs() <<
" " << SchedModel->getResourceName(PIdx) <<
" +" 2176 << Cycles <<
"x" << Factor <<
"u\n");
2179 incExecutedResources(PIdx, Count);
2180 assert(Rem->RemainingCounts[PIdx] >= Count &&
"resource double counted");
2181 Rem->RemainingCounts[PIdx] -= Count;
2185 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
2186 ZoneCritResIdx = PIdx;
2188 << SchedModel->getResourceName(PIdx) <<
": " 2189 << getResourceCount(PIdx) / SchedModel->getLatencyFactor()
2193 unsigned NextAvailable, InstanceIdx;
2194 std::tie(NextAvailable, InstanceIdx) = getNextResourceCycle(PIdx, Cycles);
2195 if (NextAvailable > CurrCycle) {
2197 << SchedModel->getResourceName(PIdx)
2198 <<
'[' << InstanceIdx - ReservedCyclesIndex[PIdx] <<
']' 2199 <<
" reserved until @" << NextAvailable <<
"\n");
2201 return NextAvailable;
2207 if (HazardRec->isEnabled()) {
2208 if (!isTop() && SU->
isCall) {
2213 HazardRec->EmitInstruction(SU);
2215 CheckPending =
true;
2220 unsigned IncMOps = SchedModel->getNumMicroOps(SU->
getInstr());
2222 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
2223 "Cannot schedule this instruction's MicroOps in the current cycle.");
2228 unsigned NextCycle = CurrCycle;
2229 switch (SchedModel->getMicroOpBufferSize()) {
2231 assert(ReadyCycle <= CurrCycle &&
"Broken PendingQueue");
2234 if (ReadyCycle > NextCycle) {
2235 NextCycle = ReadyCycle;
2236 LLVM_DEBUG(
dbgs() <<
" *** Stall until: " << ReadyCycle <<
"\n");
2245 NextCycle = ReadyCycle;
2248 RetiredMOps += IncMOps;
2251 if (SchedModel->hasInstrSchedModel()) {
2252 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2253 assert(Rem->RemIssueCount >= DecRemIssue &&
"MOps double counted");
2254 Rem->RemIssueCount -= DecRemIssue;
2255 if (ZoneCritResIdx) {
2257 unsigned ScaledMOps =
2258 RetiredMOps * SchedModel->getMicroOpFactor();
2262 if ((
int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2263 >= (
int)SchedModel->getLatencyFactor()) {
2266 << ScaledMOps / SchedModel->getLatencyFactor()
2271 PI = SchedModel->getWriteProcResBegin(SC),
2272 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2274 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
2275 if (RCycle > NextCycle)
2284 PI = SchedModel->getWriteProcResBegin(SC),
2285 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2286 unsigned PIdx = PI->ProcResourceIdx;
2287 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
2288 unsigned ReservedUntil, InstanceIdx;
2289 std::tie(ReservedUntil, InstanceIdx) = getNextResourceCycle(PIdx, 0);
2291 ReservedCycles[InstanceIdx] =
2292 std::max(ReservedUntil, NextCycle + PI->Cycles);
2294 ReservedCycles[InstanceIdx] = NextCycle;
2300 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2301 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2304 LLVM_DEBUG(
dbgs() <<
" " << Available.getName() <<
" TopLatency SU(" 2305 << SU->
NodeNum <<
") " << TopLatency <<
"c\n");
2309 LLVM_DEBUG(
dbgs() <<
" " << Available.getName() <<
" BotLatency SU(" 2310 << SU->
NodeNum <<
") " << BotLatency <<
"c\n");
2313 if (NextCycle > CurrCycle)
2314 bumpCycle(NextCycle);
2320 getScheduledLatency(),
true);
2326 CurrMOps += IncMOps;
2332 if ((isTop() && SchedModel->mustEndGroup(SU->
getInstr())) ||
2333 (!isTop() && SchedModel->mustBeginGroup(SU->
getInstr()))) {
2334 LLVM_DEBUG(
dbgs() <<
" Bump cycle to " << (isTop() ?
"end" :
"begin")
2336 bumpCycle(++NextCycle);
2339 while (CurrMOps >= SchedModel->getIssueWidth()) {
2340 LLVM_DEBUG(
dbgs() <<
" *** Max MOps " << CurrMOps <<
" at cycle " 2341 << CurrCycle <<
'\n');
2342 bumpCycle(++NextCycle);
2351 if (Available.empty())
2356 for (
unsigned I = 0,
E = Pending.size();
I <
E; ++
I) {
2357 SUnit *SU = *(Pending.begin() +
I);
2360 if (ReadyCycle < MinReadyCycle)
2361 MinReadyCycle = ReadyCycle;
2366 releaseNode(SU, ReadyCycle,
true,
I);
2367 if (E != Pending.size()) {
2372 CheckPending =
false;
2377 if (Available.isInQueue(SU))
2378 Available.remove(Available.find(SU));
2380 assert(Pending.isInQueue(SU) &&
"bad ready count");
2381 Pending.remove(Pending.find(SU));
2395 if (checkHazard(*
I)) {
2397 I = Available.remove(
I);
2403 for (
unsigned i = 0; Available.empty(); ++i) {
2408 bumpCycle(CurrCycle + 1);
2415 if (Available.size() == 1)
2416 return *Available.begin();
2420 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2426 if (ZoneCritResIdx) {
2427 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2428 ResCount = getResourceCount(ZoneCritResIdx);
2430 ResFactor = SchedModel->getMicroOpFactor();
2431 ResCount = RetiredMOps * ResFactor;
2433 unsigned LFactor = SchedModel->getLatencyFactor();
2434 dbgs() << Available.getName() <<
" @" << CurrCycle <<
"c\n" 2435 <<
" Retired: " << RetiredMOps;
2436 dbgs() <<
"\n Executed: " << getExecutedCount() / LFactor <<
"c";
2437 dbgs() <<
"\n Critical: " << ResCount / LFactor <<
"c, " 2438 << ResCount / ResFactor <<
" " 2439 << SchedModel->getResourceName(ZoneCritResIdx)
2440 <<
"\n ExpectedLatency: " << ExpectedLatency <<
"c\n" 2441 << (IsResourceLimited ?
" - Resource" :
" - Latency")
2453 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2460 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2461 ResDelta.CritResources += PI->Cycles;
2462 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2463 ResDelta.DemandedResources += PI->Cycles;
2494 bool GenericSchedulerBase::shouldReduceLatency(
const CandPolicy &Policy,
2496 bool ComputeRemLatency,
2497 unsigned &RemLatency)
const {
2507 if (ComputeRemLatency)
2510 return RemLatency + CurrZone.
getCurrCycle() > Rem.CriticalPath;
2523 unsigned OtherCritIdx = 0;
2524 unsigned OtherCount =
2527 bool OtherResLimited =
false;
2528 unsigned RemLatency = 0;
2529 bool RemLatencyComputed =
false;
2530 if (SchedModel->hasInstrSchedModel() && OtherCount != 0) {
2532 RemLatencyComputed =
true;
2534 OtherCount, RemLatency,
false);
2540 if (!OtherResLimited &&
2541 (IsPostRA || shouldReduceLatency(Policy, CurrZone, !RemLatencyComputed,
2545 <<
" RemainingLatency " << RemLatency <<
" + " 2547 << Rem.CriticalPath <<
"\n");
2556 }
if (OtherResLimited)
dbgs()
2557 <<
" RemainingLimit: " 2558 << SchedModel->getResourceName(OtherCritIdx) <<
"\n";
2560 <<
" Latency limited both directions.\n");
2565 if (OtherResLimited)
2573 case NoCand:
return "NOCAND ";
2574 case Only1:
return "ONLY1 ";
2575 case PhysReg:
return "PHYS-REG ";
2576 case RegExcess:
return "REG-EXCESS";
2577 case RegCritical:
return "REG-CRIT ";
2578 case Stall:
return "STALL ";
2579 case Cluster:
return "CLUSTER ";
2580 case Weak:
return "WEAK ";
2581 case RegMax:
return "REG-MAX ";
2582 case ResourceReduce:
return "RES-REDUCE";
2583 case ResourceDemand:
return "RES-DEMAND";
2584 case TopDepthReduce:
return "TOP-DEPTH ";
2585 case TopPathReduce:
return "TOP-PATH ";
2586 case BotHeightReduce:
return "BOT-HEIGHT";
2587 case BotPathReduce:
return "BOT-PATH ";
2588 case NextDefUse:
return "DEF-USE ";
2596 unsigned ResIdx = 0;
2610 case ResourceReduce:
2613 case ResourceDemand:
2616 case TopDepthReduce:
2622 case BotHeightReduce:
2636 dbgs() <<
" " << SchedModel->getProcResource(ResIdx)->Name <<
" ";
2640 dbgs() <<
" " << Latency <<
" cycles ";
2653 if (TryVal < CandVal) {
2657 if (TryVal > CandVal) {
2658 if (Cand.
Reason > Reason)
2669 if (TryVal > CandVal) {
2673 if (TryVal < CandVal) {
2674 if (Cand.
Reason > Reason)
2718 "(PreRA)GenericScheduler needs vreg liveness");
2723 Rem.init(DAG, SchedModel);
2724 Top.init(DAG, SchedModel, &Rem);
2725 Bot.init(DAG, SchedModel, &Rem);
2732 if (!Top.HazardRec) {
2734 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
2737 if (!Bot.HazardRec) {
2739 DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
2742 TopCand.SU =
nullptr;
2743 BotCand.SU =
nullptr;
2749 unsigned NumRegionInstrs) {
2756 RegionPolicy.ShouldTrackPressure =
true;
2760 unsigned NIntRegs =
Context->RegClassInfo->getNumAllocatableRegs(
2762 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2768 RegionPolicy.OnlyBottomUp =
true;
2774 if (!EnableRegPressure) {
2775 RegionPolicy.ShouldTrackPressure =
false;
2776 RegionPolicy.ShouldTrackLaneMasks =
false;
2782 "-misched-topdown incompatible with -misched-bottomup");
2785 if (RegionPolicy.OnlyBottomUp)
2786 RegionPolicy.OnlyTopDown =
false;
2790 if (RegionPolicy.OnlyTopDown)
2791 RegionPolicy.OnlyBottomUp =
false;
2797 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2798 dbgs() <<
"GenericScheduler RegionPolicy: " 2799 <<
" ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2800 <<
" OnlyTopDown=" << RegionPolicy.OnlyTopDown
2801 <<
" OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2816 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2820 unsigned IterCount =
2821 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2824 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2826 unsigned InFlightCount =
2827 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2828 unsigned BufferLimit =
2829 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2831 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2834 dbgs() <<
"IssueCycles=" 2835 << Rem.RemIssueCount / SchedModel->getLatencyFactor() <<
"c " 2836 <<
"IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2837 <<
"c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount
2838 <<
" InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2839 <<
"m BufferLim=" << SchedModel->getMicroOpBufferSize() <<
"m\n";
2840 if (Rem.IsAcyclicLatencyLimited)
dbgs() <<
" ACYCLIC LATENCY LIMIT\n");
2847 for (
const SUnit *SU : Bot.Available) {
2848 if (SU->
getDepth() > Rem.CriticalPath)
2851 LLVM_DEBUG(
dbgs() <<
"Critical Path(GS-RR ): " << Rem.CriticalPath <<
'\n');
2853 errs() <<
"Critical Path(GS-RR ): " << Rem.CriticalPath <<
" \n";
2856 if (EnableCyclicPath && SchedModel->getMicroOpBufferSize() > 0) {
2858 checkAcyclicLatency();
2878 if (Cand.AtTop != TryCand.
AtTop)
2885 if (TryPSet == CandPSet) {
2899 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2917 unsigned ScheduledOper = isTop ? 1 : 0;
2918 unsigned UnscheduledOper = isTop ? 0 : 1;
2927 return AtBoundary ? -1 : 1;
2943 return isTop ? -1 : 1;
2982 <<
" Try SU(" << Cand.
SU->
NodeNum <<
") " 3014 TryCand, Cand, RegExcess,
TRI,
3021 TryCand, Cand, RegCritical,
TRI,
3030 bool SameBoundary = Zone !=
nullptr;
3035 if (Rem.IsAcyclicLatencyLimited && !Zone->
getCurrMOps() &&
3051 const SUnit *CandNextClusterSU =
3053 const SUnit *TryCandNextClusterSU =
3056 Cand.
SU == CandNextClusterSU,
3057 TryCand, Cand, Cluster))
3064 TryCand, Cand, Weak))
3071 TryCand, Cand, RegMax,
TRI,
3079 TryCand, Cand, ResourceReduce))
3083 TryCand, Cand, ResourceDemand))
3089 !Rem.IsAcyclicLatencyLimited &&
tryLatency(TryCand, Cand, *Zone))
3113 for (
SUnit *SU : Q) {
3116 initCandidate(TryCand, SU, Zone.
isTop(), RPTracker, TempTracker);
3119 tryCandidate(Cand, TryCand, ZoneArg);
3134 if (
SUnit *SU = Bot.pickOnlyChoice()) {
3139 if (
SUnit *SU = Top.pickOnlyChoice()) {
3147 setPolicy(BotPolicy,
false, Bot, &Top);
3151 setPolicy(TopPolicy,
false, Top, &Bot);
3155 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
3156 BotCand.Policy != BotPolicy) {
3159 assert(BotCand.Reason !=
NoCand &&
"failed to find the first candidate");
3168 "Last pick result should correspond to re-picking right now");
3175 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
3176 TopCand.Policy != TopPolicy) {
3179 assert(TopCand.Reason !=
NoCand &&
"failed to find the first candidate");
3188 "Last pick result should correspond to re-picking right now");
3194 assert(BotCand.isValid());
3195 assert(TopCand.isValid());
3198 tryCandidate(Cand, TopCand,
nullptr);
3199 if (TopCand.Reason !=
NoCand) {
3200 Cand.setBest(TopCand);
3204 IsTopNode = Cand.AtTop;
3212 assert(Top.Available.empty() && Top.Pending.empty() &&
3213 Bot.Available.empty() && Bot.Pending.empty() &&
"ReadyQ garbage");
3218 if (RegionPolicy.OnlyTopDown) {
3219 SU = Top.pickOnlyChoice();
3222 TopCand.reset(NoPolicy);
3224 assert(TopCand.Reason !=
NoCand &&
"failed to find a candidate");
3229 }
else if (RegionPolicy.OnlyBottomUp) {
3230 SU = Bot.pickOnlyChoice();
3233 BotCand.reset(NoPolicy);
3235 assert(BotCand.Reason !=
NoCand &&
"failed to find a candidate");
3241 SU = pickNodeBidirectional(IsTopNode);
3246 Top.removeReady(SU);
3248 Bot.removeReady(SU);
3263 for (
SDep &Dep : Deps) {
3267 SUnit *DepSU = Dep.getSUnit();
3268 if (isTop ? DepSU->
Succs.size() > 1 : DepSU->
Preds.size() > 1)
3291 reschedulePhysReg(SU,
true);
3296 reschedulePhysReg(SU,
false);
3331 Rem.init(DAG, SchedModel);
3332 Top.init(DAG, SchedModel, &Rem);
3338 if (!Top.HazardRec) {
3349 for (
const SUnit *SU : BotRoots) {
3350 if (SU->getDepth() > Rem.CriticalPath)
3351 Rem.CriticalPath = SU->getDepth();
3353 LLVM_DEBUG(
dbgs() <<
"Critical Path: (PGS-RR) " << Rem.CriticalPath <<
'\n');
3355 errs() <<
"Critical Path(PGS-RR ): " << Rem.CriticalPath <<
" \n";
3372 if (
tryLess(Top.getLatencyStallCycles(TryCand.
SU),
3373 Top.getLatencyStallCycles(Cand.
SU), TryCand, Cand, Stall))
3379 TryCand, Cand, Cluster))
3384 TryCand, Cand, ResourceReduce))
3387 Cand.ResDelta.DemandedResources,
3388 TryCand, Cand, ResourceDemand))
3392 if (Cand.Policy.ReduceLatency &&
tryLatency(TryCand, Cand, Top)) {
3397 if (TryCand.
SU->
NodeNum < Cand.SU->NodeNum)
3403 for (
SUnit *SU : Q) {
3406 TryCand.
AtTop =
true;
3408 tryCandidate(Cand, TryCand);
3419 assert(Top.Available.empty() && Top.Pending.empty() &&
"ReadyQ garbage");
3424 SU = Top.pickOnlyChoice();
3432 setPolicy(TopCand.
Policy,
true, Top,
nullptr);
3433 pickNodeFromQueue(TopCand);
3441 Top.removeReady(SU);
3456 return new ScheduleDAGMI(C, std::make_unique<PostGenericScheduler>(C),
3469 const BitVector *ScheduledTrees =
nullptr;
3472 ILPOrder(
bool MaxILP) : MaximizeILP(MaxILP) {}
3477 bool operator()(
const SUnit *A,
const SUnit *
B)
const {
3480 if (SchedTreeA != SchedTreeB) {
3482 if (ScheduledTrees->
test(SchedTreeA) != ScheduledTrees->
test(SchedTreeB))
3483 return ScheduledTrees->
test(SchedTreeB);
3504 std::vector<SUnit*> ReadyQ;
3507 ILPScheduler(
bool MaximizeILP) : Cmp(MaximizeILP) {}
3513 Cmp.DFSResult = DAG->getDFSResult();
3514 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
3520 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3528 if (ReadyQ.empty())
return nullptr;
3529 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3530 SUnit *SU = ReadyQ.back();
3534 <<
"SU(" << SU->NodeNum <<
") " 3541 <<
"Scheduling " << *SU->getInstr());
3547 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3553 assert(!IsTopNode &&
"SchedDFSResult needs bottom-up");
3559 ReadyQ.push_back(SU);
3560 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3587 template<
bool IsReverse>
3613 InstructionShuffler(
bool alternate,
bool topdown)
3614 : IsAlternating(alternate), IsTopDown(topdown) {}
3628 if (TopQ.empty())
return nullptr;
3635 if (BottomQ.empty())
return nullptr;
3642 IsTopDown = !IsTopDown;
3662 "-misched-topdown incompatible with -misched-bottomup");
3664 C, std::make_unique<InstructionShuffler>(Alternate, TopDown));
3668 "shuffle",
"Shuffle machine instructions alternating directions",
3695 if (ViewMISchedCutoff == 0)
3697 return (Node->
Preds.size() > ViewMISchedCutoff
3707 return "color=cyan,style=dashed";
3709 return "color=blue,style=dashed";
3730 std::string Str(
"shape=Mrecord");
3735 Str +=
",style=filled,fillcolor=\"#";
3752 errs() <<
"ScheduleDAGMI::viewGraph is only available in debug builds on " 3753 <<
"systems with Graphviz or gv!\n";
3759 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.
int biasPhysReg(const SUnit *SU, bool isTop)
Minimize physical register live ranges.
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 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.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
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...
static MachinePassRegistry< ScheduleDAGCtor > Registry
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.
This class represents lattice values for constants.
void addPressureChange(unsigned RegUnit, bool IsDec, const MachineRegisterInfo *MRI)
Add a change in pressure to the pressure diff of a given instruction.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
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. ...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
Segments::iterator iterator
const MCSchedClassDesc * getSchedClass(SUnit *SU) const
Resolves and cache a resolved scheduling class for an SUnit.
void push_back(const T &Elt)
void startBlock(MachineBasicBlock *bb) override
Prepares to perform scheduling in the given block.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
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 computeCyclicCriticalPath()
Compute the cyclic critical path through the DAG.
void dump() const override
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
virtual bool enablePostRAMachineScheduler() const
True if the subtarget should run a machine scheduler after register allocation.
static bool checkResourceLimit(unsigned LFactor, unsigned Count, unsigned Latency, bool AfterSchedNode)
Given a Count of resource usage and a Latency value, return true if a SchedBoundary becomes resource ...
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.
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)
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.
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
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)
virtual ScheduleHazardRecognizer * CreateTargetMIHazardRecognizer(const InstrItineraryData *, const ScheduleDAGMI *DAG) const
Allocate and return a hazard recognizer to use for this target when scheduling the machine instructio...
static cl::opt< bool > PrintDAGs("misched-print-dags", cl::Hidden, cl::desc("Print schedule DAGs"))
bool isMoveImmediate(QueryType Type=IgnoreBundle) const
Return true if this instruction is a move immediate (including conditional moves) instruction...
A register anti-dependence (aka WAR).
ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules machine instructions while...
*ViewGraph Emit a dot run run gv on the postscript *then cleanup For use from the debugger *void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
virtual bool hasVRegLiveness() const
Return true if this DAG supports VReg liveness and RegPressure.
MachineFunction & MF
Machine function.
bool isScheduled
True once scheduled.
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.
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.
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...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
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)
bool canAddEdge(SUnit *SuccSU, SUnit *PredSU)
True if an edge can be added from PredSU to SuccSU without creating a cycle.
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)
value_type & FindAndConstruct(const KeyT &Key)
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.
void releaseNode(SUnit *SU, unsigned ReadyCycle, bool InPQueue, unsigned Idx=0)
Release SU to make it ready.
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.
CandReason
Represent the type of SchedCandidate found within a single queue.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
Helpers for implementing custom MachineSchedStrategy classes.
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
cl::opt< bool > VerifyScheduling
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.
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...
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
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...
Represent the analysis usage information of a pass.
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.
iterator_range< mop_iterator > defs()
Returns a range over all explicit operands that are register definitions.
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.
LiveInterval & getInterval(Register Reg)
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.
unsigned getNextResourceCycleByInstance(unsigned InstanceIndex, unsigned Cycles)
Compute the next cycle at which the given processor resource unit can be 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)
bool addEdge(SUnit *SuccSU, const SDep &PredDep)
Add a DAG edge to the given SU with the given predecessor dependence data.
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)
Align max(MaybeAlign Lhs, Align Rhs)
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...
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)
Information about stack frame layout on the target.
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"))
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:
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.
std::pair< unsigned, unsigned > getNextResourceCycle(unsigned PIdx, unsigned Cycles)
Compute the next cycle at which the given processor resource can be scheduled.
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.
void dumpNode(const SUnit &SU) const override
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.
const MachineBasicBlock * getParent() const
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...
void reschedulePhysReg(SUnit *SU, bool isTop)
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
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
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
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.
virtual const TargetFrameLowering * getFrameLowering() const
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
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)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
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 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.
void postprocessDAG()
Apply each ScheduleDAGMutation step in order.
nonconst_iterator getNonConstIterator() const
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
SmallVector< SDep, 4 > Succs
All sunit successors.
bool getMemOperandWithOffset(const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset, const TargetRegisterInfo *TRI) const override
Get the base register and byte offset of a load/store instr.
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
static MachineSchedRegistry ILPMinRegistry("ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler)
Register getReg() const
getReg - Returns the register number.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
std::vector< SUnit > SUnits
The scheduling units.
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.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
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.
Wrapper class representing virtual and physical registers.
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
static unsigned computeRemLatency(SchedBoundary &CurrZone)
Compute remaining latency.
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