41 #define DEBUG_TYPE "machine-scheduler"
145 case NoCand:
return "NOCAND";
147 case Latency:
return "LATENCY";
149 case Depth:
return "DEPTH";
161 if (TryVal < CandVal) {
165 if (TryVal > CandVal) {
178 if (TryVal > CandVal) {
182 if (TryVal < CandVal) {
194 NodeNum2Index[SU->
NodeNum] = SUnits.size();
195 SUnits.push_back(SU);
199 void SIScheduleBlock::traceCandidate(
const SISchedCandidate &Cand) {
206 void SIScheduleBlock::tryCandidateTopDown(SISchedCandidate &Cand,
207 SISchedCandidate &TryCand) {
209 if (!Cand.isValid()) {
214 if (Cand.SGPRUsage > 60 &&
233 if (
tryLess(TryCand.HasLowLatencyNonWaitedParent,
234 Cand.HasLowLatencyNonWaitedParent,
238 if (
tryGreater(TryCand.IsLowLatency, Cand.IsLowLatency,
242 if (TryCand.IsLowLatency &&
243 tryLess(TryCand.LowLatencyOffset, Cand.LowLatencyOffset,
247 if (
tryLess(TryCand.VGPRUsage, Cand.VGPRUsage, TryCand, Cand,
RegUsage))
251 if (TryCand.SU->NodeNum < Cand.SU->NodeNum) {
256 SUnit* SIScheduleBlock::pickNode() {
257 SISchedCandidate TopCand;
259 for (
SUnit* SU : TopReadySUs) {
260 SISchedCandidate TryCand;
261 std::vector<unsigned> pressure;
262 std::vector<unsigned> MaxPressure;
270 TryCand.HasLowLatencyNonWaitedParent =
271 HasLowLatencyNonWaitedParent[NodeNum2Index[SU->NodeNum]];
272 tryCandidateTopDown(TopCand, TryCand);
273 if (TryCand.Reason !=
NoCand)
274 TopCand.setBest(TryCand);
287 for (
SUnit* SU : SUnits) {
288 if (!SU->NumPredsLeft)
289 TopReadySUs.push_back(SU);
292 while (!TopReadySUs.empty()) {
293 SUnit *SU = TopReadySUs[0];
294 ScheduledSUnits.push_back(SU);
313 if (InstSlot >= First && InstSlot <= Last)
331 for (
SUnit* SU : ScheduledSUnits) {
332 RPTracker.setPos(SU->getInstr());
337 RPTracker.closeRegion();
340 TopRPTracker.
addLiveRegs(RPTracker.getPressure().LiveInRegs);
341 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
344 for (
const auto &RegMaskPair : RPTracker.getPressure().LiveInRegs) {
346 LiveInRegs.insert(RegMaskPair.RegUnit);
371 for (
const auto &RegMaskPair : RPTracker.getPressure().LiveOutRegs) {
372 unsigned Reg = RegMaskPair.RegUnit;
377 LiveOutRegs.insert(Reg);
398 initRegPressure(BeginBlock, EndBlock);
405 for (
SUnit* SU : SUnits) {
406 if (!SU->NumPredsLeft)
407 TopReadySUs.push_back(SU);
410 while (!TopReadySUs.empty()) {
411 SUnit *SU = pickNode();
412 ScheduledSUnits.push_back(SU);
419 InternalAdditionnalPressure.resize(TopPressure.
MaxSetPressure.size());
423 assert(SUnits.size() == ScheduledSUnits.size() &&
424 TopReadySUs.empty());
425 for (
SUnit* SU : SUnits) {
427 SU->NumPredsLeft == 0);
434 void SIScheduleBlock::undoSchedule() {
435 for (
SUnit* SU : SUnits) {
436 SU->isScheduled =
false;
437 for (
SDep& Succ : SU->Succs) {
439 undoReleaseSucc(SU, &Succ);
442 HasLowLatencyNonWaitedParent.assign(SUnits.size(), 0);
443 ScheduledSUnits.clear();
447 void SIScheduleBlock::undoReleaseSucc(
SUnit *SU,
SDep *SuccEdge) {
457 void SIScheduleBlock::releaseSucc(
SUnit *SU,
SDep *SuccEdge) {
466 dbgs() <<
"*** Scheduling failed! ***\n";
468 dbgs() <<
" has been released too many times!\n";
477 void SIScheduleBlock::releaseSuccessors(
SUnit *SU,
bool InOrOutBlock) {
487 releaseSucc(SU, &Succ);
489 TopReadySUs.push_back(SuccSU);
493 void SIScheduleBlock::nodeScheduled(
SUnit *SU) {
496 std::vector<SUnit *>::iterator
I =
llvm::find(TopReadySUs, SU);
497 if (I == TopReadySUs.end()) {
498 dbgs() <<
"Data Structure Bug in SI Scheduler\n";
501 TopReadySUs.erase(I);
503 releaseSuccessors(SU,
true);
506 if (HasLowLatencyNonWaitedParent[NodeNum2Index[SU->
NodeNum]])
507 HasLowLatencyNonWaitedParent.assign(SUnits.size(), 0);
511 std::map<unsigned, unsigned>::iterator I =
513 if (I != NodeNum2Index.end())
514 HasLowLatencyNonWaitedParent[I->second] = 1;
522 for (
SUnit* SU : SUnits) {
523 releaseSuccessors(SU,
false);
525 HighLatencyBlock =
true;
527 HasLowLatencyNonWaitedParent.resize(SUnits.size(), 0);
532 unsigned PredID = Pred->
getID();
536 if (PredID ==
P->getID())
539 Preds.push_back(Pred);
544 return PredID == S.first->getID();
546 "Loop in the Block Graph!");
551 unsigned SuccID = Succ->
getID();
554 for (std::pair<SIScheduleBlock*, SIScheduleBlockLinkKind> &S : Succs) {
555 if (SuccID == S.first->getID()) {
563 ++NumHighLatencySuccessors;
564 Succs.push_back(std::make_pair(Succ, Kind));
568 "Loop in the Block Graph!");
573 dbgs() <<
"Block (" << ID <<
")\n";
577 dbgs() <<
"\nContains High Latency Instruction: "
578 << HighLatencyBlock <<
'\n';
579 dbgs() <<
"\nDepends On:\n";
581 P->printDebug(
false);
584 dbgs() <<
"\nSuccessors:\n";
585 for (std::pair<SIScheduleBlock*, SIScheduleBlockLinkKind> S : Succs) {
587 dbgs() <<
"(Data Dep) ";
588 S.first->printDebug(
false);
596 dbgs() <<
"LiveIns:\n";
597 for (
unsigned Reg : LiveInRegs)
600 dbgs() <<
"\nLiveOuts:\n";
601 for (
unsigned Reg : LiveOutRegs)
605 dbgs() <<
"\nInstructions:\n";
607 for (
SUnit* SU : SUnits) {
611 for (
SUnit* SU : SUnits) {
616 dbgs() <<
"///////////////////////\n";
630 std::map<SISchedulerBlockCreatorVariant, SIScheduleBlocks>::iterator
B =
631 Blocks.find(BlockVariant);
632 if (B == Blocks.end()) {
634 createBlocksForVariant(BlockVariant);
636 scheduleInsideBlocks();
638 Res.
Blocks = CurrentBlocks;
641 Blocks[BlockVariant] = Res;
651 return CurrentBlocks[Node2CurrentBlock[SU->
NodeNum]]->getID() ==
ID;
654 void SIScheduleBlockCreator::colorHighLatenciesAlone() {
655 unsigned DAGSize = DAG->
SUnits.size();
657 for (
unsigned i = 0, e = DAGSize; i != e; ++i) {
660 CurrentColoring[SU->
NodeNum] = NextReservedID++;
667 for (
const auto &PredDep : SU.
Preds) {
668 if (PredDep.getSUnit() == &FromSU &&
675 void SIScheduleBlockCreator::colorHighLatenciesGroups() {
676 unsigned DAGSize = DAG->
SUnits.size();
677 unsigned NumHighLatencies = 0;
679 int Color = NextReservedID;
681 std::set<unsigned> FormingGroup;
683 for (
unsigned i = 0, e = DAGSize; i != e; ++i) {
689 if (NumHighLatencies == 0)
692 if (NumHighLatencies <= 6)
694 else if (NumHighLatencies <= 12)
702 unsigned CompatibleGroup =
true;
703 int ProposedColor =
Color;
704 std::vector<int> AdditionalElements;
716 for (
unsigned j : FormingGroup) {
718 std::vector<int> SubGraph;
731 else if (SubGraph.size() > 5) {
733 CompatibleGroup =
false;
738 for (
unsigned k : SubGraph) {
744 (CurrentColoring[k] != ProposedColor &&
745 CurrentColoring[k] != 0)) {
746 CompatibleGroup =
false;
752 CompatibleGroup =
false;
756 if (!CompatibleGroup)
760 CompatibleGroup =
false;
768 AdditionalElements.insert(AdditionalElements.end(),
769 SubGraph.begin(), SubGraph.end());
772 if (CompatibleGroup) {
773 FormingGroup.insert(SU.
NodeNum);
774 for (
unsigned j : AdditionalElements)
775 CurrentColoring[j] = ProposedColor;
776 CurrentColoring[SU.
NodeNum] = ProposedColor;
782 if (!CompatibleGroup) {
783 FormingGroup.clear();
784 Color = ++NextReservedID;
785 ProposedColor =
Color;
786 FormingGroup.insert(SU.
NodeNum);
787 CurrentColoring[SU.
NodeNum] = ProposedColor;
789 }
else if (Count == GroupSize) {
790 FormingGroup.clear();
791 Color = ++NextReservedID;
792 ProposedColor =
Color;
799 void SIScheduleBlockCreator::colorComputeReservedDependencies() {
800 unsigned DAGSize = DAG->
SUnits.size();
801 std::map<std::set<unsigned>,
unsigned> ColorCombinations;
803 CurrentTopDownReservedDependencyColoring.clear();
804 CurrentBottomUpReservedDependencyColoring.clear();
806 CurrentTopDownReservedDependencyColoring.resize(DAGSize, 0);
807 CurrentBottomUpReservedDependencyColoring.resize(DAGSize, 0);
814 std::set<unsigned> SUColors;
817 if (CurrentColoring[SU->
NodeNum]) {
818 CurrentTopDownReservedDependencyColoring[SU->
NodeNum] =
827 if (CurrentTopDownReservedDependencyColoring[Pred->
NodeNum] > 0)
828 SUColors.insert(CurrentTopDownReservedDependencyColoring[Pred->
NodeNum]);
831 if (SUColors.empty())
834 if (SUColors.size() == 1 && *SUColors.begin() > DAGSize)
835 CurrentTopDownReservedDependencyColoring[SU->
NodeNum] =
838 std::map<std::set<unsigned>,
unsigned>::iterator Pos =
839 ColorCombinations.find(SUColors);
840 if (Pos != ColorCombinations.end()) {
841 CurrentTopDownReservedDependencyColoring[SU->
NodeNum] = Pos->second;
843 CurrentTopDownReservedDependencyColoring[SU->
NodeNum] =
845 ColorCombinations[SUColors] = NextNonReservedID++;
850 ColorCombinations.clear();
856 std::set<unsigned> SUColors;
859 if (CurrentColoring[SU->
NodeNum]) {
860 CurrentBottomUpReservedDependencyColoring[SU->
NodeNum] =
869 if (CurrentBottomUpReservedDependencyColoring[Succ->
NodeNum] > 0)
870 SUColors.insert(CurrentBottomUpReservedDependencyColoring[Succ->
NodeNum]);
873 if (SUColors.empty())
876 if (SUColors.size() == 1 && *SUColors.begin() > DAGSize)
877 CurrentBottomUpReservedDependencyColoring[SU->
NodeNum] =
880 std::map<std::set<unsigned>,
unsigned>::iterator Pos =
881 ColorCombinations.find(SUColors);
882 if (Pos != ColorCombinations.end()) {
883 CurrentBottomUpReservedDependencyColoring[SU->
NodeNum] = Pos->second;
885 CurrentBottomUpReservedDependencyColoring[SU->
NodeNum] =
887 ColorCombinations[SUColors] = NextNonReservedID++;
893 void SIScheduleBlockCreator::colorAccordingToReservedDependencies() {
894 unsigned DAGSize = DAG->
SUnits.size();
895 std::map<std::pair<unsigned, unsigned>,
unsigned> ColorCombinations;
900 for (
unsigned i = 0, e = DAGSize; i != e; ++i) {
902 std::pair<unsigned, unsigned> SUColors;
905 if (CurrentColoring[SU->
NodeNum])
908 SUColors.first = CurrentTopDownReservedDependencyColoring[SU->
NodeNum];
909 SUColors.second = CurrentBottomUpReservedDependencyColoring[SU->
NodeNum];
911 std::map<std::pair<unsigned, unsigned>,
unsigned>::iterator Pos =
912 ColorCombinations.find(SUColors);
913 if (Pos != ColorCombinations.end()) {
914 CurrentColoring[SU->
NodeNum] = Pos->second;
916 CurrentColoring[SU->
NodeNum] = NextNonReservedID;
917 ColorCombinations[SUColors] = NextNonReservedID++;
922 void SIScheduleBlockCreator::colorEndsAccordingToDependencies() {
923 unsigned DAGSize = DAG->
SUnits.size();
924 std::vector<int> PendingColoring = CurrentColoring;
927 CurrentBottomUpReservedDependencyColoring.size() == DAGSize &&
928 CurrentTopDownReservedDependencyColoring.size() == DAGSize);
931 if (*std::max_element(CurrentBottomUpReservedDependencyColoring.begin(),
932 CurrentBottomUpReservedDependencyColoring.end()) == 0 &&
933 *std::max_element(CurrentTopDownReservedDependencyColoring.begin(),
934 CurrentTopDownReservedDependencyColoring.end()) == 0)
939 std::set<unsigned> SUColors;
940 std::set<unsigned> SUColorsPending;
942 if (CurrentColoring[SU->
NodeNum] <= (
int)DAGSize)
945 if (CurrentBottomUpReservedDependencyColoring[SU->
NodeNum] > 0 ||
946 CurrentTopDownReservedDependencyColoring[SU->
NodeNum] > 0)
953 if (CurrentBottomUpReservedDependencyColoring[Succ->
NodeNum] > 0 ||
954 CurrentTopDownReservedDependencyColoring[Succ->
NodeNum] > 0)
955 SUColors.insert(CurrentColoring[Succ->
NodeNum]);
956 SUColorsPending.insert(PendingColoring[Succ->
NodeNum]);
961 if (SUColors.size() == 1 && SUColorsPending.size() == 1)
962 PendingColoring[SU->
NodeNum] = *SUColors.begin();
965 PendingColoring[SU->
NodeNum] = NextNonReservedID++;
967 CurrentColoring = PendingColoring;
971 void SIScheduleBlockCreator::colorForceConsecutiveOrderInGroup() {
972 unsigned DAGSize = DAG->
SUnits.size();
973 unsigned PreviousColor;
974 std::set<unsigned> SeenColors;
979 PreviousColor = CurrentColoring[0];
981 for (
unsigned i = 1, e = DAGSize; i != e; ++i) {
983 unsigned CurrentColor = CurrentColoring[i];
984 unsigned PreviousColorSave = PreviousColor;
987 if (CurrentColor != PreviousColor)
988 SeenColors.insert(PreviousColor);
989 PreviousColor = CurrentColor;
991 if (CurrentColoring[SU->
NodeNum] <= (
int)DAGSize)
994 if (SeenColors.find(CurrentColor) == SeenColors.end())
997 if (PreviousColorSave != CurrentColor)
998 CurrentColoring[i] = NextNonReservedID++;
1000 CurrentColoring[i] = CurrentColoring[i-1];
1004 void SIScheduleBlockCreator::colorMergeConstantLoadsNextGroup() {
1005 unsigned DAGSize = DAG->
SUnits.size();
1009 std::set<unsigned> SUColors;
1011 if (CurrentColoring[SU->
NodeNum] <= (
int)DAGSize)
1023 SUColors.insert(CurrentColoring[Succ->
NodeNum]);
1025 if (SUColors.size() == 1)
1026 CurrentColoring[SU->
NodeNum] = *SUColors.begin();
1030 void SIScheduleBlockCreator::colorMergeIfPossibleNextGroup() {
1031 unsigned DAGSize = DAG->
SUnits.size();
1035 std::set<unsigned> SUColors;
1037 if (CurrentColoring[SU->
NodeNum] <= (
int)DAGSize)
1044 SUColors.insert(CurrentColoring[Succ->
NodeNum]);
1046 if (SUColors.size() == 1)
1047 CurrentColoring[SU->
NodeNum] = *SUColors.begin();
1051 void SIScheduleBlockCreator::colorMergeIfPossibleNextGroupOnlyForReserved() {
1052 unsigned DAGSize = DAG->
SUnits.size();
1056 std::set<unsigned> SUColors;
1058 if (CurrentColoring[SU->
NodeNum] <= (
int)DAGSize)
1065 SUColors.insert(CurrentColoring[Succ->
NodeNum]);
1067 if (SUColors.size() == 1 && *SUColors.begin() <= DAGSize)
1068 CurrentColoring[SU->
NodeNum] = *SUColors.begin();
1072 void SIScheduleBlockCreator::colorMergeIfPossibleSmallGroupsToNextGroup() {
1073 unsigned DAGSize = DAG->
SUnits.size();
1074 std::map<unsigned, unsigned> ColorCount;
1078 unsigned color = CurrentColoring[SU->
NodeNum];
1079 ++ColorCount[color];
1084 unsigned color = CurrentColoring[SU->
NodeNum];
1085 std::set<unsigned> SUColors;
1087 if (CurrentColoring[SU->
NodeNum] <= (
int)DAGSize)
1090 if (ColorCount[color] > 1)
1097 SUColors.insert(CurrentColoring[Succ->
NodeNum]);
1099 if (SUColors.size() == 1 && *SUColors.begin() != color) {
1100 --ColorCount[color];
1101 CurrentColoring[SU->
NodeNum] = *SUColors.begin();
1102 ++ColorCount[*SUColors.begin()];
1107 void SIScheduleBlockCreator::cutHugeBlocks() {
1111 void SIScheduleBlockCreator::regroupNoUserInstructions() {
1112 unsigned DAGSize = DAG->
SUnits.size();
1113 int GroupID = NextNonReservedID++;
1117 bool hasSuccessor =
false;
1119 if (CurrentColoring[SU->
NodeNum] <= (
int)DAGSize)
1126 hasSuccessor =
true;
1129 CurrentColoring[SU->
NodeNum] = GroupID;
1134 unsigned DAGSize = DAG->
SUnits.size();
1135 std::map<unsigned,unsigned> RealID;
1137 CurrentBlocks.clear();
1138 CurrentColoring.clear();
1139 CurrentColoring.resize(DAGSize, 0);
1140 Node2CurrentBlock.clear();
1146 NextNonReservedID = DAGSize + 1;
1148 DEBUG(
dbgs() <<
"Coloring the graph\n");
1151 colorHighLatenciesGroups();
1153 colorHighLatenciesAlone();
1154 colorComputeReservedDependencies();
1155 colorAccordingToReservedDependencies();
1156 colorEndsAccordingToDependencies();
1158 colorForceConsecutiveOrderInGroup();
1159 regroupNoUserInstructions();
1160 colorMergeConstantLoadsNextGroup();
1161 colorMergeIfPossibleNextGroupOnlyForReserved();
1164 Node2CurrentBlock.resize(DAGSize, -1);
1165 for (
unsigned i = 0, e = DAGSize; i != e; ++i) {
1167 unsigned Color = CurrentColoring[SU->
NodeNum];
1168 if (RealID.find(Color) == RealID.end()) {
1169 int ID = CurrentBlocks.size();
1170 BlockPtrs.push_back(llvm::make_unique<SIScheduleBlock>(DAG,
this, ID));
1171 CurrentBlocks.push_back(BlockPtrs.rbegin()->get());
1174 CurrentBlocks[RealID[
Color]]->addUnit(SU);
1179 for (
unsigned i = 0, e = DAGSize; i != e; ++i) {
1181 int SUID = Node2CurrentBlock[i];
1186 if (Node2CurrentBlock[Succ->
NodeNum] != SUID)
1187 CurrentBlocks[SUID]->addSucc(CurrentBlocks[Node2CurrentBlock[Succ->
NodeNum]],
1194 if (Node2CurrentBlock[Pred->
NodeNum] != SUID)
1195 CurrentBlocks[SUID]->addPred(CurrentBlocks[Node2CurrentBlock[Pred->
NodeNum]]);
1200 for (
unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1205 dbgs() <<
"Blocks created:\n\n";
1206 for (
unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1219 for (; I !=
End; ++
I) {
1220 if (!I->isDebugValue())
1226 void SIScheduleBlockCreator::topologicalSort() {
1227 unsigned DAGSize = CurrentBlocks.size();
1228 std::vector<int> WorkList;
1232 WorkList.reserve(DAGSize);
1233 TopDownIndex2Block.resize(DAGSize);
1234 TopDownBlock2Index.resize(DAGSize);
1235 BottomUpIndex2Block.resize(DAGSize);
1237 for (
unsigned i = 0, e = DAGSize; i != e; ++i) {
1239 unsigned Degree = Block->
getSuccs().size();
1240 TopDownBlock2Index[i] = Degree;
1242 WorkList.push_back(i);
1247 while (!WorkList.empty()) {
1248 int i = WorkList.back();
1250 WorkList.pop_back();
1251 TopDownBlock2Index[i] = --
Id;
1252 TopDownIndex2Block[
Id] = i;
1254 if (!--TopDownBlock2Index[Pred->getID()])
1255 WorkList.push_back(Pred->getID());
1261 for (
unsigned i = 0, e = DAGSize; i != e; ++i) {
1264 assert(TopDownBlock2Index[i] > TopDownBlock2Index[Pred->getID()] &&
1265 "Wrong Top Down topological sorting");
1270 BottomUpIndex2Block = std::vector<int>(TopDownIndex2Block.rbegin(),
1271 TopDownIndex2Block.rend());
1274 void SIScheduleBlockCreator::scheduleInsideBlocks() {
1275 unsigned DAGSize = CurrentBlocks.size();
1277 DEBUG(
dbgs() <<
"\nScheduling Blocks\n\n");
1281 DEBUG(
dbgs() <<
"First phase: Fast scheduling for Reg Liveness\n");
1282 for (
unsigned i = 0, e = DAGSize; i != e; ++i) {
1292 std::vector<MachineBasicBlock::iterator> PosOld;
1293 std::vector<MachineBasicBlock::iterator> PosNew;
1294 PosOld.reserve(DAG->
SUnits.size());
1295 PosNew.reserve(DAG->
SUnits.size());
1297 for (
unsigned i = 0, e = DAGSize; i != e; ++i) {
1298 int BlockIndice = TopDownIndex2Block[i];
1302 for (
SUnit* SU : SUs) {
1305 PosOld.push_back(Pos);
1306 if (&*CurrentTopFastSched == MI) {
1307 PosNew.push_back(Pos);
1308 CurrentTopFastSched =
nextIfDebug(++CurrentTopFastSched,
1320 PosNew.push_back(CurrentTopFastSched);
1329 for (
unsigned i = 0, e = DAGSize; i != e; ++i) {
1332 Block->
schedule((*SUs.begin())->getInstr(), (*SUs.rbegin())->getInstr());
1337 for (
unsigned i = PosOld.size(), e = 0; i != e; --i) {
1350 for (
unsigned i = 0, e = CurrentBlocks.size(); i != e; ++i) {
1357 void SIScheduleBlockCreator::fillStats() {
1358 unsigned DAGSize = CurrentBlocks.size();
1360 for (
unsigned i = 0, e = DAGSize; i != e; ++i) {
1361 int BlockIndice = TopDownIndex2Block[i];
1368 if (Depth < Pred->
Depth + 1)
1369 Depth = Pred->Depth + 1;
1375 for (
unsigned i = 0, e = DAGSize; i != e; ++i) {
1376 int BlockIndice = BottomUpIndex2Block[i];
1381 unsigned Height = 0;
1383 Height =
std::min(Height, Succ.first->Height + 1);
1394 DAG(DAG), Variant(Variant), Blocks(BlocksStruct.Blocks),
1395 LastPosWaitedHighLatency(0), NumBlockScheduled(0), VregCurrentUsage(0),
1396 SregCurrentUsage(0), maxVregUsage(0), maxSregUsage(0) {
1408 LiveOutRegsNumUsages.resize(Blocks.size());
1409 for (
unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1411 for (
unsigned Reg : Block->
getInRegs()) {
1415 std::set<unsigned> PredOutRegs = Pred->getOutRegs();
1416 std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg);
1418 if (RegPos != PredOutRegs.end()) {
1430 ++LiveOutRegsNumUsages[PredID][
Reg];
1434 LastPosHighLatencyParentScheduled.resize(Blocks.size(), 0);
1435 BlockNumPredsLeft.resize(Blocks.size());
1436 BlockNumSuccsLeft.resize(Blocks.size());
1438 for (
unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1440 BlockNumPredsLeft[i] = Block->
getPreds().size();
1441 BlockNumSuccsLeft[i] = Block->
getSuccs().size();
1445 for (
unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1451 std::set<unsigned> InRegs = DAG->
getInRegs();
1452 addLiveRegs(InRegs);
1458 for (
unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1462 const std::set<unsigned> &OutRegs = Block->
getOutRegs();
1464 if (OutRegs.find(Reg) == OutRegs.end())
1467 ++LiveOutRegsNumUsages[
ID][
Reg];
1474 for (
unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1476 for (
unsigned Reg : Block->
getInRegs()) {
1479 std::set<unsigned> PredOutRegs = Pred->getOutRegs();
1480 std::set<unsigned>::iterator RegPos = PredOutRegs.find(Reg);
1482 if (RegPos != PredOutRegs.end()) {
1489 ++LiveRegsConsumers[
Reg];
1493 for (
unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1495 if (BlockNumPredsLeft[i] == 0) {
1496 ReadyBlocks.push_back(Block);
1501 BlocksScheduled.push_back(Block);
1502 blockScheduled(Block);
1506 dbgs() <<
"Block Order:";
1514 bool SIScheduleBlockScheduler::tryCandidateLatency(SIBlockSchedCandidate &Cand,
1515 SIBlockSchedCandidate &TryCand) {
1516 if (!Cand.isValid()) {
1522 if (
tryLess(TryCand.LastPosHighLatParentScheduled,
1523 Cand.LastPosHighLatParentScheduled, TryCand, Cand,
Latency))
1526 if (
tryGreater(TryCand.IsHighLatency, Cand.IsHighLatency,
1529 if (TryCand.IsHighLatency &&
tryGreater(TryCand.Height, Cand.Height,
1530 TryCand, Cand,
Depth))
1532 if (
tryGreater(TryCand.NumHighLatencySuccessors,
1533 Cand.NumHighLatencySuccessors,
1539 bool SIScheduleBlockScheduler::tryCandidateRegUsage(SIBlockSchedCandidate &Cand,
1540 SIBlockSchedCandidate &TryCand) {
1541 if (!Cand.isValid()) {
1546 if (
tryLess(TryCand.VGPRUsageDiff > 0, Cand.VGPRUsageDiff > 0,
1550 Cand.NumSuccessors > 0,
1555 if (
tryLess(TryCand.VGPRUsageDiff, Cand.VGPRUsageDiff,
1562 SIBlockSchedCandidate Cand;
1563 std::vector<SIScheduleBlock*>::iterator Best;
1565 if (ReadyBlocks.empty())
1569 VregCurrentUsage, SregCurrentUsage);
1570 if (VregCurrentUsage > maxVregUsage)
1571 maxVregUsage = VregCurrentUsage;
1572 if (SregCurrentUsage > maxSregUsage)
1573 maxSregUsage = SregCurrentUsage;
1575 dbgs() <<
"Picking New Blocks\n";
1576 dbgs() <<
"Available: ";
1579 dbgs() <<
"\nCurrent Live:\n";
1580 for (
unsigned Reg : LiveRegs)
1583 dbgs() <<
"Current VGPRs: " << VregCurrentUsage <<
'\n';
1584 dbgs() <<
"Current SGPRs: " << SregCurrentUsage <<
'\n';
1587 Cand.Block =
nullptr;
1588 for (std::vector<SIScheduleBlock*>::iterator I = ReadyBlocks.begin(),
1589 E = ReadyBlocks.end(); I !=
E; ++
I) {
1590 SIBlockSchedCandidate TryCand;
1592 TryCand.IsHighLatency = TryCand.Block->isHighLatencyBlock();
1593 TryCand.VGPRUsageDiff =
1594 checkRegUsageImpact(TryCand.Block->getInRegs(),
1596 TryCand.NumSuccessors = TryCand.Block->getSuccs().size();
1597 TryCand.NumHighLatencySuccessors =
1598 TryCand.Block->getNumHighLatencySuccessors();
1599 TryCand.LastPosHighLatParentScheduled =
1600 (
unsigned int) std::max<int> (0,
1601 LastPosHighLatencyParentScheduled[TryCand.Block->getID()] -
1602 LastPosWaitedHighLatency);
1603 TryCand.Height = TryCand.Block->Height;
1605 if (VregCurrentUsage > 120 ||
1607 if (!tryCandidateRegUsage(Cand, TryCand) &&
1609 tryCandidateLatency(Cand, TryCand);
1611 if (!tryCandidateLatency(Cand, TryCand))
1612 tryCandidateRegUsage(Cand, TryCand);
1614 if (TryCand.Reason !=
NoCand) {
1615 Cand.setBest(TryCand);
1617 DEBUG(
dbgs() <<
"Best Current Choice: " << Cand.Block->getID() <<
' '
1623 dbgs() <<
"Picking: " << Cand.Block->getID() <<
'\n';
1624 dbgs() <<
"Is a block with high latency instruction: "
1625 << (Cand.IsHighLatency ?
"yes\n" :
"no\n");
1626 dbgs() <<
"Position of last high latency dependency: "
1627 << Cand.LastPosHighLatParentScheduled <<
'\n';
1628 dbgs() <<
"VGPRUsageDiff: " << Cand.VGPRUsageDiff <<
'\n';
1633 ReadyBlocks.erase(Best);
1639 void SIScheduleBlockScheduler::addLiveRegs(std::set<unsigned> &
Regs) {
1640 for (
unsigned Reg : Regs) {
1645 (void) LiveRegs.insert(Reg);
1649 void SIScheduleBlockScheduler::decreaseLiveRegs(
SIScheduleBlock *Block,
1650 std::set<unsigned> &Regs) {
1651 for (
unsigned Reg : Regs) {
1653 std::set<unsigned>::iterator Pos = LiveRegs.find(Reg);
1654 assert (Pos != LiveRegs.end() &&
1655 LiveRegsConsumers.find(Reg) != LiveRegsConsumers.end() &&
1656 LiveRegsConsumers[
Reg] >= 1);
1657 --LiveRegsConsumers[
Reg];
1658 if (LiveRegsConsumers[Reg] == 0)
1659 LiveRegs.erase(Pos);
1663 void SIScheduleBlockScheduler::releaseBlockSuccs(
SIScheduleBlock *Parent) {
1664 for (
const auto &Block : Parent->
getSuccs()) {
1665 if (--BlockNumPredsLeft[Block.first->
getID()] == 0)
1666 ReadyBlocks.push_back(Block.first);
1670 LastPosHighLatencyParentScheduled[Block.first->
getID()] = NumBlockScheduled;
1674 void SIScheduleBlockScheduler::blockScheduled(
SIScheduleBlock *Block) {
1675 decreaseLiveRegs(Block, Block->
getInRegs());
1677 releaseBlockSuccs(Block);
1678 for (std::map<unsigned, unsigned>::iterator RegI =
1679 LiveOutRegsNumUsages[Block->
getID()].begin(),
1680 E = LiveOutRegsNumUsages[Block->
getID()].end(); RegI !=
E; ++RegI) {
1681 std::pair<unsigned, unsigned> RegP = *RegI;
1683 assert(LiveRegsConsumers.find(RegP.first) == LiveRegsConsumers.end() ||
1684 LiveRegsConsumers[RegP.first] == 0);
1685 LiveRegsConsumers[RegP.first] += RegP.second;
1687 if (LastPosHighLatencyParentScheduled[Block->
getID()] >
1688 (
unsigned)LastPosWaitedHighLatency)
1689 LastPosWaitedHighLatency =
1690 LastPosHighLatencyParentScheduled[Block->
getID()];
1691 ++NumBlockScheduled;
1695 SIScheduleBlockScheduler::checkRegUsageImpact(std::set<unsigned> &InRegs,
1696 std::set<unsigned> &OutRegs) {
1697 std::vector<int> DiffSetPressure;
1700 for (
unsigned Reg : InRegs) {
1704 if (LiveRegsConsumers[Reg] > 1)
1707 for (; PSetI.
isValid(); ++PSetI) {
1708 DiffSetPressure[*PSetI] -= PSetI.
getWeight();
1712 for (
unsigned Reg : OutRegs) {
1717 for (; PSetI.
isValid(); ++PSetI) {
1718 DiffSetPressure[*PSetI] += PSetI.
getWeight();
1722 return DiffSetPressure;
1728 SIScheduler::scheduleVariant(SISchedulerBlockCreatorVariant BlockVariant,
1729 SISchedulerBlockSchedulerVariant ScheduleVariant) {
1732 std::vector<SIScheduleBlock*> ScheduledBlocks;
1735 ScheduledBlocks = Scheduler.
getBlocks();
1737 for (
unsigned b = 0; b < ScheduledBlocks.size(); ++b) {
1741 for (
SUnit* SU : SUs)
1766 void SIScheduleDAGMI::topologicalSort() {
1779 void SIScheduleDAGMI::moveLowLatencies() {
1780 unsigned DAGSize = SUnits.size();
1781 int LastLowLatencyUser = -1;
1782 int LastLowLatencyPos = -1;
1784 for (
unsigned i = 0, e = ScheduledSUnits.size(); i != e; ++i) {
1785 SUnit *SU = &SUnits[ScheduledSUnits[i]];
1786 bool IsLowLatencyUser =
false;
1787 unsigned MinPos = 0;
1792 IsLowLatencyUser =
true;
1796 unsigned PredPos = ScheduledSUnitsInv[Pred->
NodeNum];
1797 if (PredPos >= MinPos)
1798 MinPos = PredPos + 1;
1802 unsigned BestPos = LastLowLatencyUser + 1;
1803 if ((
int)BestPos <= LastLowLatencyPos)
1804 BestPos = LastLowLatencyPos + 1;
1805 if (BestPos < MinPos)
1808 for (
unsigned u = i; u > BestPos; --u) {
1809 ++ScheduledSUnitsInv[ScheduledSUnits[u-1]];
1810 ScheduledSUnits[u] = ScheduledSUnits[u-1];
1812 ScheduledSUnits[BestPos] = SU->
NodeNum;
1813 ScheduledSUnitsInv[SU->
NodeNum] = BestPos;
1815 LastLowLatencyPos = BestPos;
1816 if (IsLowLatencyUser)
1817 LastLowLatencyUser = BestPos;
1818 }
else if (IsLowLatencyUser) {
1819 LastLowLatencyUser = i;
1823 bool CopyForLowLat =
false;
1827 CopyForLowLat =
true;
1833 for (
unsigned u = i; u > MinPos; --u) {
1834 ++ScheduledSUnitsInv[ScheduledSUnits[u-1]];
1835 ScheduledSUnits[u] = ScheduledSUnits[u-1];
1837 ScheduledSUnits[MinPos] = SU->
NodeNum;
1838 ScheduledSUnitsInv[SU->
NodeNum] = MinPos;
1845 for (
unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1846 SUnits[i].isScheduled =
false;
1847 SUnits[i].WeakPredsLeft = SUnitsLinksBackup[i].WeakPredsLeft;
1848 SUnits[i].NumPredsLeft = SUnitsLinksBackup[i].NumPredsLeft;
1849 SUnits[i].WeakSuccsLeft = SUnitsLinksBackup[i].WeakSuccsLeft;
1850 SUnits[i].NumSuccsLeft = SUnitsLinksBackup[i].NumSuccsLeft;
1855 template<
typename _Iterator>
void
1857 unsigned &VgprUsage,
unsigned &SgprUsage) {
1860 for (_Iterator RegI = First; RegI !=
End; ++RegI) {
1861 unsigned Reg = *RegI;
1866 for (; PSetI.
isValid(); ++PSetI) {
1867 if (*PSetI == VGPRSetID)
1869 else if (*PSetI == SGPRSetID)
1879 DEBUG(
dbgs() <<
"Preparing Scheduling\n");
1883 for(
SUnit& SU : SUnits)
1898 SUnitsLinksBackup =
SUnits;
1907 for (
unsigned i = 0, e = (
unsigned)SUnits.size(); i != e; ++i) {
1908 SUnit *SU = &SUnits[i];
1909 unsigned BaseLatReg;
1939 for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) {
1960 for (std::pair<SISchedulerBlockCreatorVariant, SISchedulerBlockSchedulerVariant> v : Variants) {
1967 ScheduledSUnits = Best.
SUs;
1968 ScheduledSUnitsInv.resize(SUnits.size());
1970 for (
unsigned i = 0, e = (
unsigned)SUnits.size(); i != e; ++i) {
1971 ScheduledSUnitsInv[ScheduledSUnits[i]] = i;
1981 for (std::vector<unsigned>::iterator I = ScheduledSUnits.begin(),
1982 E = ScheduledSUnits.end(); I !=
E; ++
I) {
1996 unsigned BBNum =
begin()->getParent()->getNumber();
1997 dbgs() <<
"*** Final schedule for BB#" << BBNum <<
" ***\n";
bool isCtrl() const
Shorthand for getKind() != SDep::Data.
Interface definition for SIRegisterInfo.
virtual unsigned getNumRegPressureSets() const =0
Get the number of dimensions of register pressure.
std::vector< SIScheduleBlock * > Blocks
SIScheduleDAGMI(MachineSchedContext *C)
void dumpSchedule() const
dump the scheduled Sequence.
ScheduleDAGTopologicalSort Topo
Topo - A topological ordering for SUnits which permits fast IsReachable and similar queries...
MachineBasicBlock::iterator CurrentTop
The top of the unscheduled zone.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
SIScheduleCandReason Reason
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
std::vector< unsigned > IsLowLatencySU
void addUnit(SUnit *SU)
Functions for Block construction.
void dumpAll(const ScheduleDAG *G) const
std::vector< SIScheduleBlock * > getBlocks()
static MachineBasicBlock::iterator nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::const_iterator End)
Non-const version.
MachineBasicBlock::iterator begin() const
Returns an iterator to the top of the current scheduling region.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
std::unique_ptr< MachineSchedStrategy > SchedImpl
SmallVector< SDep, 4 > Preds
All sunit predecessors.
MachineBasicBlock::const_iterator getPos() const
Get the MI position corresponding to this register pressure.
ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules machine instructions while...
bool isScheduled
True once scheduled.
std::vector< unsigned > LowLatencyOffset
static bool hasDataDependencyPred(const SUnit &SU, const SUnit &FromSU)
static bool tryGreater(int TryVal, int CandVal, SISchedulerCandidate &TryCand, SISchedulerCandidate &Cand, SIScheduleCandReason Reason)
bool isWeak() const
Tests if this a weak dependence.
Regular data dependence (aka true-dependence).
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
Reg
All possible values of the reg field in the ModR/M byte.
ArrayRef< std::pair< SIScheduleBlock *, SIScheduleBlockLinkKind > > getSuccs() const
void InitDAGTopologicalSorting()
Creates the initial topological ordering from the DAG to be scheduled.
defusechain_iterator - This class provides iterator support for machine operands in the function that...
static const char * getReasonStr(SIScheduleCandReason Reason)
std::set< unsigned > getOutRegs()
void scheduleMI(SUnit *SU, bool IsTopNode)
Move an instruction and update register pressure.
std::set< unsigned > getInRegs()
static bool tryLess(int TryVal, int CandVal, SISchedulerCandidate &TryCand, SISchedulerCandidate &Cand, SIScheduleCandReason Reason)
std::vector< int > GetSubGraph(const SUnit &StartSU, const SUnit &TargetSU, bool &Success)
Returns an array of SUs that are both in the successor subtree of StartSU and in the predecessor subt...
MachineBasicBlock::iterator RegionBegin
The beginning of the range to be scheduled.
void buildDAGWithRegPressure()
Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking enabled.
static def_instr_iterator def_instr_end()
void dump(const ScheduleDAG *G) const
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
unsigned NumPredsLeft
of preds not scheduled.
unsigned getSGPRSetID() const
std::vector< int > TopDownIndex2Block
struct SIScheduleBlockResult scheduleVariant(SISchedulerBlockCreatorVariant BlockVariant, SISchedulerBlockSchedulerVariant ScheduleVariant)
unsigned getVGPRPressureSet() const
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
SI Machine Scheduler interface.
void printDebug(bool Full)
bool isDebugValue() const
void addLiveRegs(ArrayRef< RegisterMaskPair > Regs)
Force liveness of virtual registers or physical register units.
bool getMemOpBaseRegImmOfs(MachineInstr &LdSt, unsigned &BaseReg, int64_t &Offset, const TargetRegisterInfo *TRI) const final
reverse_iterator rbegin()
void initQueues(ArrayRef< SUnit * > TopRoots, ArrayRef< SUnit * > BotRoots)
Release ExitSU predecessors and setup scheduler queues.
unsigned const MachineRegisterInfo * MRI
~SIScheduleDAGMI() override
RegisterPressure computed within a region of instructions delimited by TopIdx and BottomIdx...
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&...args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
bool isSUInBlock(SUnit *SU, unsigned ID)
std::vector< SUnit * > getScheduledUnits()
std::vector< int > TopDownIndex2SU
void addSucc(SIScheduleBlock *Succ, SIScheduleBlockLinkKind Kind)
MachineRegisterInfo * getMRI()
MachineBasicBlock * getBB()
static const unsigned End
Track the current register pressure at some position in the instruction stream, and remember the high...
void findRootsAndBiasEdges(SmallVectorImpl< SUnit * > &TopRoots, SmallVectorImpl< SUnit * > &BotRoots)
for(unsigned i=0, e=MI->getNumOperands();i!=e;++i)
const TargetRegisterInfo * getTRI()
SIScheduleBlocks getBlocks(SISchedulerBlockCreatorVariant BlockVariant)
bool isHighLatencyInstruction(const MachineInstr &MI) const
MachineBasicBlock::iterator getCurrentBottom()
void schedule(MachineBasicBlock::iterator BeginBlock, MachineBasicBlock::iterator EndBlock)
unsigned WeakPredsLeft
of weak preds not scheduled.
std::vector< unsigned > MaxSetPressure
Map of max reg pressure indexed by pressure set ID, not class ID.
void advance()
Advance across the current instruction.
std::set< unsigned > & getOutRegs()
Color
A "color", which is either even or odd.
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
GenericScheduler shrinks the unscheduled zone using heuristics to balance the schedule.
std::vector< unsigned > IsHighLatencySU
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
std::vector< unsigned > SUs
SISchedulerBlockCreatorVariant
unsigned getWeight() const
SIScheduleBlockCreator(SIScheduleDAGMI *DAG)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
MachineBasicBlock::iterator getCurrentTop()
void fillVgprSgprCost(_Iterator First, _Iterator End, unsigned &VgprUsage, unsigned &SgprUsage)
bool isHighLatencyBlock()
unsigned getVGPRSetID() const
llvm_unreachable("Unknown RegBank!")
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
void closeTop()
Set the boundary for the top of the region and summarize live ins.
ScheduleDAGTopologicalSort * GetTopo()
Representation of each machine instruction.
Interface definition for SIInstrInfo.
void addPred(SIScheduleBlock *Pred)
const TargetRegisterInfo * TRI
Target processor register info.
def_instr_iterator def_instr_begin(unsigned RegNo) const
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
std::vector< int > BottomUpIndex2SU
Iterate over the pressure sets affected by the given physical or virtual register.
PSetIterator getPressureSets(unsigned RegUnit) const
Get an iterator over the pressure sets affected by the given physical or virtual register.
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
static bool isDefBetween(unsigned Reg, SlotIndex First, SlotIndex Last, const MachineRegisterInfo *MRI, const LiveIntervals *LIS)
bool isLowLatencyInstruction(const MachineInstr &MI) const
void placeDebugValues()
Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
const TargetInstrInfo * TII
Target instruction information.
void restoreSULinksLeft()
unsigned getSGPRPressureSet() const
unsigned NodeNum
Entry # of node in the node vector.
void initRPTracker(RegPressureTracker &RPTracker)
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 CurrentBottom
The bottom of the unscheduled zone.
std::set< unsigned > & getInRegs()
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::vector< int > TopDownBlock2Index
void setRepeat(SIScheduleCandReason R)
const std::vector< SIScheduleBlock * > & getPreds() const
SmallVector< SDep, 4 > Succs
All sunit successors.
~SIScheduleBlockCreator()
void getDownwardPressure(const MachineInstr *MI, std::vector< unsigned > &PressureResult, std::vector< unsigned > &MaxPressureResult)
Get the pressure of each PSet after traversing this instruction top-down.
Machine Instruction Scheduler
void setPos(MachineBasicBlock::const_iterator Pos)
std::vector< SUnit > SUnits
The scheduling units.
SlotIndex - An opaque wrapper around machine indexes.
Printable PrintVRegOrUnit(unsigned VRegOrUnit, const TargetRegisterInfo *TRI)
Create Printable object to print virtual registers and physical registers on a raw_ostream.
RegPressureTracker TopRPTracker
SISchedulerBlockSchedulerVariant
void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block...
Scheduling unit. This is a node in the scheduling DAG.