40#include "llvm/Config/llvm-config.h"
63#define DEBUG_TYPE "pre-RA-sched"
65STATISTIC(NumBacktracks,
"Number of times scheduler backtracked");
68STATISTIC(NumPRCopies,
"Number of physical register copies");
72 "Bottom-up register reduction list scheduling",
77 "Similar to list-burr but schedules in source "
78 "order when possible",
83 "Bottom-up register pressure aware list scheduling "
84 "which tries to balance latency and register pressure",
89 "Bottom-up register pressure aware list scheduling "
90 "which tries to balance ILP and register pressure",
95 cl::desc(
"Disable cycle-level precision during preRA scheduling"));
101 cl::desc(
"Disable regpressure priority in sched=list-ilp"));
104 cl::desc(
"Disable live use priority in sched=list-ilp"));
107 cl::desc(
"Disable virtual register cycle interference checks"));
110 cl::desc(
"Disable physreg def-use affinity"));
113 cl::desc(
"Disable no-stall priority in sched=list-ilp"));
116 cl::desc(
"Disable critical path priority in sched=list-ilp"));
119 cl::desc(
"Disable scheduled-height priority in sched=list-ilp"));
122 cl::desc(
"Disable scheduler's two-address hack"));
126 cl::desc(
"Number of instructions to allow ahead of the critical path "
127 "in sched=list-ilp"));
131 cl::desc(
"Average inst/cycle when no target itinerary exists."));
151 std::vector<SUnit *> PendingQueue;
157 unsigned CurCycle = 0;
160 unsigned MinAvailableCycle = ~0u;
164 unsigned IssueCount = 0u;
171 SUnit *Def =
nullptr;
173 SUnit *Gen =
nullptr;
175 explicit LiveReg(
unsigned Reg) :
Reg(
Reg) {}
176 unsigned getSparseSetIndex()
const {
return Reg; }
183 SparseSet<LiveReg> LiveRegs;
189 using LRegsMapT = DenseMap<SUnit *, SmallVector<unsigned, 4>>;
195 ScheduleDAGTopologicalSort Topo;
199 SmallDenseMap<SUnit *, SUnit *, 16> CallSeqEndForStart;
203 SchedulingPriorityQueue *availqueue,
205 : ScheduleDAGSDNodes(mf), NeedLatency(needlatency),
206 AvailableQueue(availqueue), Topo(SUnits, nullptr) {
209 HazardRec =
new ScheduleHazardRecognizer();
211 HazardRec = STI.
getInstrInfo()->CreateTargetHazardRecognizer(&STI,
this);
214 ~ScheduleDAGRRList()
override {
216 delete AvailableQueue;
219 void Schedule()
override;
221 LiveReg *findLiveReg(
unsigned Reg) {
223 if (LiveRegs.empty())
225 auto I = LiveRegs.find(
Reg);
226 return I == LiveRegs.end() ? nullptr : &*
I;
229 SUnit *getLiveRegDef(
unsigned Reg) {
230 LiveReg *LR = findLiveReg(
Reg);
231 return LR ? LR->Def :
nullptr;
234 SUnit *getLiveRegGen(
unsigned Reg) {
235 LiveReg *LR = findLiveReg(
Reg);
236 return LR ? LR->Gen :
nullptr;
241 LiveReg &addLiveReg(
unsigned Reg) {
243 if (LiveRegs.empty())
244 LiveRegs.setUniverse(
TRI->getNumRegs() + 1);
245 return *LiveRegs.insert(LiveReg(
Reg)).first;
248 void removeLiveReg(
unsigned Reg) {
249 if (!LiveRegs.erase(
Reg))
253 ScheduleHazardRecognizer *getHazardRec() {
return HazardRec; }
256 bool IsReachable(
const SUnit *SU,
const SUnit *TargetSU) {
257 return Topo.IsReachable(SU, TargetSU);
262 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
263 return Topo.WillCreateCycle(SU, TargetSU);
269 void AddPredQueued(SUnit *SU,
const SDep &
D) {
270 Topo.AddPredQueued(SU,
D.getSUnit());
277 void RemovePred(SUnit *SU,
const SDep &
D) {
278 Topo.RemovePred(SU,
D.getSUnit());
283 bool isReady(SUnit *SU) {
285 AvailableQueue->isReady(SU);
288 void ReleasePred(SUnit *SU,
const SDep *PredEdge);
289 void ReleasePredecessors(SUnit *SU);
290 void ReleasePending();
291 void AdvanceToCycle(
unsigned NextCycle);
292 void AdvancePastStalls(SUnit *SU);
293 void EmitNode(SUnit *SU);
294 void ScheduleNodeBottomUp(SUnit*);
295 void CapturePred(SDep *PredEdge);
296 void UnscheduleNodeBottomUp(SUnit*);
297 void RestoreHazardCheckerBottomUp();
298 void BacktrackBottomUp(SUnit*, SUnit*);
299 SUnit *TryUnfoldSU(SUnit *);
300 SUnit *CopyAndMoveSuccessors(SUnit*);
301 void InsertCopiesAndMoveSuccs(SUnit*,
unsigned,
304 SmallVectorImpl<SUnit*>&);
305 bool DelayForLiveRegsBottomUp(SUnit*, SmallVectorImpl<unsigned>&);
307 SmallSet<unsigned, 4> &RegAdded,
308 SmallVectorImpl<unsigned> &LRegs,
309 const SDNode *Node =
nullptr);
310 void CheckForLiveRegDefMasked(SUnit *SU,
const uint32_t *RegMask,
311 SmallSet<unsigned, 4> &RegAdded,
312 SmallVectorImpl<unsigned> &LRegs);
314 void releaseInterferences(
unsigned Reg = 0);
316 SUnit *PickNodeToScheduleBottomUp();
317 void ListScheduleBottomUp();
320 SUnit *CreateNewSUnit(SDNode *
N) {
321 unsigned NumSUnits = SUnits.size();
322 SUnit *NewNode = newSUnit(
N);
324 if (NewNode->
NodeNum >= NumSUnits)
325 Topo.AddSUnitWithoutPredecessors(NewNode);
330 SUnit *CreateClone(SUnit *
N) {
331 unsigned NumSUnits = SUnits.size();
332 SUnit *NewNode = Clone(
N);
334 if (NewNode->
NodeNum >= NumSUnits)
335 Topo.AddSUnitWithoutPredecessors(NewNode);
341 bool forceUnitLatencies()
const override {
358 unsigned &RegClass,
unsigned &Cost,
364 if (VT == MVT::Untyped) {
371 RegClass = RC->
getID();
376 unsigned Opcode =
Node->getMachineOpcode();
377 if (Opcode == TargetOpcode::REG_SEQUENCE) {
378 unsigned DstRCIdx =
Node->getConstantOperandVal(0);
380 RegClass = RC->
getID();
385 unsigned Idx = RegDefPos.
GetIdx();
388 assert(RC &&
"Not a valid register class");
389 RegClass = RC->
getID();
394 RegClass =
TLI->getRepRegClassFor(VT)->getID();
395 Cost =
TLI->getRepRegClassCostFor(VT);
400void ScheduleDAGRRList::Schedule() {
402 <<
" '" << BB->getName() <<
"' **********\n");
409 CallSeqEndForStart.
clear();
410 assert(Interferences.
empty() && LRegsMap.empty() &&
"stale Interferences");
411 assert(PendingQueue.empty() &&
"stale PendingQueue");
424 ListScheduleBottomUp();
429 dbgs() <<
"*** Final schedule ***\n";
441void ScheduleDAGRRList::ReleasePred(SUnit *SU,
const SDep *PredEdge) {
442 SUnit *PredSU = PredEdge->
getSUnit();
446 dbgs() <<
"*** Scheduling failed! ***\n";
448 dbgs() <<
" has been released too many times!\n";
454 if (!forceUnitLatencies()) {
466 if (Height < MinAvailableCycle)
467 MinAvailableCycle = Height;
469 if (isReady(PredSU)) {
470 AvailableQueue->
push(PredSU);
476 PendingQueue.push_back(PredSU);
500 if (
N->isMachineOpcode()) {
501 if (
N->getMachineOpcode() ==
TII->getCallFrameDestroyOpcode()) {
503 }
else if (
N->getMachineOpcode() ==
TII->getCallFrameSetupOpcode()) {
511 if (
Op.getValueType() == MVT::Other) {
513 goto found_chain_operand;
516 found_chain_operand:;
540 unsigned BestMaxNest = MaxNest;
542 unsigned MyNestLevel = NestLevel;
543 unsigned MyMaxNest = MaxNest;
545 MyNestLevel, MyMaxNest,
TII))
546 if (!Best || (MyMaxNest > BestMaxNest)) {
548 BestMaxNest = MyMaxNest;
552 MaxNest = BestMaxNest;
556 if (
N->isMachineOpcode()) {
557 if (
N->getMachineOpcode() ==
TII->getCallFrameDestroyOpcode()) {
559 MaxNest = std::max(MaxNest, NestLevel);
560 }
else if (
N->getMachineOpcode() ==
TII->getCallFrameSetupOpcode()) {
569 if (
Op.getValueType() == MVT::Other) {
571 goto found_chain_operand;
574 found_chain_operand:;
597void ScheduleDAGRRList::ReleasePredecessors(SUnit *SU) {
600 ReleasePred(SU, &
Pred);
601 if (
Pred.isAssignedRegDep()) {
606 LiveReg &LR = addLiveReg(
Pred.getReg());
607 assert((!LR.Def || LR.Def == SU || LR.Def ==
Pred.getSUnit()) &&
608 "interference on register dependence");
609 LR.Def =
Pred.getSUnit();
618 unsigned CallResource =
TRI->getNumRegs();
619 if (!getLiveRegDef(CallResource))
620 for (SDNode *Node = SU->
getNode(); Node; Node =
Node->getGluedNode())
621 if (
Node->isMachineOpcode() &&
622 Node->getMachineOpcode() ==
TII->getCallFrameDestroyOpcode()) {
623 unsigned NestLevel = 0;
624 unsigned MaxNest = 0;
626 assert(
N &&
"Must find call sequence start");
628 SUnit *
Def = &SUnits[
N->getNodeId()];
629 CallSeqEndForStart[
Def] = SU;
631 LiveReg &LR = addLiveReg(CallResource);
640void ScheduleDAGRRList::ReleasePending() {
642 assert(PendingQueue.empty() &&
"pending instrs not allowed in this mode");
647 if (AvailableQueue->
empty())
648 MinAvailableCycle = std::numeric_limits<unsigned>::max();
652 for (
unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
653 unsigned ReadyCycle = PendingQueue[i]->getHeight();
654 if (ReadyCycle < MinAvailableCycle)
655 MinAvailableCycle = ReadyCycle;
657 if (PendingQueue[i]->isAvailable) {
658 if (!isReady(PendingQueue[i]))
660 AvailableQueue->
push(PendingQueue[i]);
662 PendingQueue[i]->isPending =
false;
663 PendingQueue[i] = PendingQueue.back();
664 PendingQueue.pop_back();
670void ScheduleDAGRRList::AdvanceToCycle(
unsigned NextCycle) {
671 if (NextCycle <= CurCycle)
678 CurCycle = NextCycle;
681 for (; CurCycle != NextCycle; ++CurCycle) {
692void ScheduleDAGRRList::AdvancePastStalls(SUnit *SU) {
709 AdvanceToCycle(ReadyCycle);
729 AdvanceToCycle(CurCycle + Stalls);
734void ScheduleDAGRRList::EmitNode(SUnit *SU) {
745 "This target-independent node should not be scheduled.");
778void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU) {
783 if (CurCycle < SU->getHeight())
785 <<
"] pipeline stall!\n");
805 AdvanceToCycle(CurCycle + 1);
809 ReleasePredecessors(SU);
812 for (SDep &Succ : SU->
Succs) {
815 removeLiveReg(Succ.
getReg());
816 releaseInterferences(Succ.
getReg());
821 unsigned CallResource =
TRI->getNumRegs();
822 if (getLiveRegDef(CallResource) == SU)
823 for (
const SDNode *SUNode = SU->
getNode(); SUNode;
825 if (SUNode->isMachineOpcode() &&
826 SUNode->getMachineOpcode() ==
TII->getCallFrameSetupOpcode()) {
827 removeLiveReg(CallResource);
828 releaseInterferences(CallResource);
849 AdvanceToCycle(CurCycle + 1);
856void ScheduleDAGRRList::CapturePred(SDep *PredEdge) {
857 SUnit *PredSU = PredEdge->
getSUnit();
861 AvailableQueue->
remove(PredSU);
865 "NumSuccsLeft will overflow!");
871void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
877 if (
Pred.isAssignedRegDep() && SU == getLiveRegGen(
Pred.getReg())) {
879 "Physical register dependency violated?");
880 removeLiveReg(
Pred.getReg());
881 releaseInterferences(
Pred.getReg());
887 unsigned CallResource =
TRI->getNumRegs();
888 for (
const SDNode *SUNode = SU->
getNode(); SUNode;
890 if (SUNode->isMachineOpcode() &&
891 SUNode->getMachineOpcode() ==
TII->getCallFrameSetupOpcode()) {
892 SUnit *SeqEnd = CallSeqEndForStart[SU];
893 assert(SeqEnd &&
"Call sequence start/end must be known");
894 assert(!findLiveReg(CallResource));
895 LiveReg &LR = addLiveReg(CallResource);
903 if (getLiveRegGen(CallResource) == SU)
904 for (
const SDNode *SUNode = SU->
getNode(); SUNode;
906 if (SUNode->isMachineOpcode() &&
907 SUNode->getMachineOpcode() ==
TII->getCallFrameDestroyOpcode()) {
908 assert(getLiveRegDef(CallResource));
909 removeLiveReg(CallResource);
910 releaseInterferences(CallResource);
914 for (
auto &Succ : SU->
Succs) {
917 LiveReg &LR = addLiveReg(
Reg);
927 for (
auto &Succ2 : SU->
Succs) {
928 if (Succ2.isAssignedRegDep() && Succ2.getReg() ==
Reg &&
929 Succ2.getSUnit()->getHeight() < LR.Gen->getHeight())
930 LR.Gen = Succ2.getSUnit();
944 PendingQueue.push_back(SU);
947 AvailableQueue->
push(SU);
954void ScheduleDAGRRList::RestoreHazardCheckerBottomUp() {
957 unsigned LookAhead = std::min((
unsigned)
Sequence.size(),
962 std::vector<SUnit *>::const_iterator
I = (
Sequence.end() - LookAhead);
963 unsigned HazardCycle = (*I)->getHeight();
966 for (; SU->
getHeight() > HazardCycle; ++HazardCycle) {
975void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, SUnit *BtSU) {
981 UnscheduleNodeBottomUp(OldSU);
990 RestoreHazardCheckerBottomUp();
1000 if (SUNode->isOperandOf(
N))
1007SUnit *ScheduleDAGRRList::TryUnfoldSU(SUnit *SU) {
1011 if (!
TII->unfoldMemoryOperand(*DAG,
N, NewNodes))
1014 assert(NewNodes.
size() == 2 &&
"Expected a load folding node!");
1017 SDNode *LoadNode = NewNodes[0];
1018 unsigned NumVals =
N->getNumValues();
1029 assert(
N->getNodeId() == -1 &&
"Node using a new load can't exist yet!");
1031 SUnit *LoadSU = CreateNewSUnit(LoadNode);
1033 InitNumRegDefsLeft(LoadSU);
1034 computeLatency(LoadSU);
1036 SUnit *NewSU = CreateNewSUnit(
N);
1039 const MCInstrDesc &MCID =
TII->get(
N->getMachineOpcode());
1049 InitNumRegDefsLeft(NewSU);
1050 computeLatency(NewSU);
1055 for (
unsigned i = 0; i != NumVals; ++i)
1057 DAG->ReplaceAllUsesOfValueWith(
SDValue(SU->
getNode(), OldNumVals - 1),
1074 for (SDep &Succ : SU->
Succs) {
1082 for (
const SDep &
Pred : ChainPreds) {
1083 RemovePred(SU,
Pred);
1084 AddPredQueued(LoadSU,
Pred);
1086 for (
const SDep &
Pred : LoadPreds) {
1087 RemovePred(SU,
Pred);
1088 AddPredQueued(LoadSU,
Pred);
1090 for (
const SDep &
Pred : NodePreds) {
1091 RemovePred(SU,
Pred);
1092 AddPredQueued(NewSU,
Pred);
1094 for (SDep &
D : NodeSuccs) {
1095 SUnit *SuccDep =
D.getSUnit();
1097 RemovePred(SuccDep,
D);
1099 AddPredQueued(SuccDep,
D);
1105 for (SDep &
D : ChainSuccs) {
1106 SUnit *SuccDep =
D.getSUnit();
1108 RemovePred(SuccDep,
D);
1110 AddPredQueued(SuccDep,
D);
1117 AddPredQueued(NewSU,
D);
1119 AvailableQueue->
addNode(LoadSU);
1120 AvailableQueue->
addNode(NewSU);
1132SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
1140 if (
N->getGluedNode() &&
1141 !
TII->canCopyGluedNodeDuringSchedule(
N)) {
1144 <<
"Giving up because it has incoming glue and the target does not "
1145 "want to copy it\n");
1150 bool TryUnfold =
false;
1151 for (
unsigned i = 0, e =
N->getNumValues(); i != e; ++i) {
1152 MVT VT =
N->getSimpleValueType(i);
1153 if (VT == MVT::Glue) {
1154 LLVM_DEBUG(
dbgs() <<
"Giving up because it has outgoing glue\n");
1156 }
else if (VT == MVT::Other)
1160 MVT VT =
Op.getNode()->getSimpleValueType(
Op.getResNo());
1161 if (VT == MVT::Glue && !
TII->canCopyGluedNodeDuringSchedule(
N)) {
1163 dbgs() <<
"Giving up because it one of the operands is glue and "
1164 "the target does not want to copy it\n");
1171 SUnit *UnfoldSU = TryUnfoldSU(SU);
1182 NewSU = CreateClone(SU);
1186 if (!
Pred.isArtificial())
1187 AddPredQueued(NewSU,
Pred);
1196 for (SDep &Succ : SU->
Succs) {
1203 AddPredQueued(SuccSU,
D);
1208 for (
const auto &[DelSU, DelD] : DelDeps)
1209 RemovePred(DelSU, DelD);
1212 AvailableQueue->
addNode(NewSU);
1220void ScheduleDAGRRList::InsertCopiesAndMoveSuccs(SUnit *SU,
unsigned Reg,
1223 SmallVectorImpl<SUnit*> &
Copies) {
1224 SUnit *CopyFromSU = CreateNewSUnit(
nullptr);
1228 SUnit *CopyToSU = CreateNewSUnit(
nullptr);
1235 for (SDep &Succ : SU->
Succs) {
1242 AddPredQueued(SuccSU,
D);
1252 for (
const auto &[DelSU, DelD] : DelDeps)
1253 RemovePred(DelSU, DelD);
1256 FromDep.setLatency(SU->
Latency);
1257 AddPredQueued(CopyFromSU, FromDep);
1259 ToDep.setLatency(CopyFromSU->
Latency);
1260 AddPredQueued(CopyToSU, ToDep);
1263 AvailableQueue->
addNode(CopyFromSU);
1264 AvailableQueue->
addNode(CopyToSU);
1265 Copies.push_back(CopyFromSU);
1266 Copies.push_back(CopyToSU);
1273void ScheduleDAGRRList::CheckForLiveRegDef(SUnit *SU, MCRegister
Reg,
1274 SmallSet<unsigned, 4> &RegAdded,
1275 SmallVectorImpl<unsigned> &LRegs,
1276 const SDNode *Node) {
1277 for (MCRegAliasIterator AliasI(
Reg,
TRI,
true); AliasI.isValid(); ++AliasI) {
1278 SUnit *
Def = getLiveRegDef(*AliasI);
1289 if (Node &&
Def->getNode() == Node)
1293 if (RegAdded.
insert(*AliasI).second) {
1301void ScheduleDAGRRList::CheckForLiveRegDefMasked(
1302 SUnit *SU,
const uint32_t *RegMask, SmallSet<unsigned, 4> &RegAdded,
1303 SmallVectorImpl<unsigned> &LRegs) {
1306 unsigned CallResource =
TRI->getNumRegs();
1307 SmallVector<unsigned, 8> Clobbered;
1308 for (
const LiveReg &LR : LiveRegs) {
1309 if (LR.Reg == CallResource || LR.Def == SU)
1315 for (
unsigned Reg : Clobbered)
1324 return RegOp->getRegMask();
1332bool ScheduleDAGRRList::
1333DelayForLiveRegsBottomUp(SUnit *SU, SmallVectorImpl<unsigned> &LRegs) {
1334 if (LiveRegs.empty())
1337 SmallSet<unsigned, 4> RegAdded;
1343 if (
Pred.isAssignedRegDep() && getLiveRegDef(
Pred.getReg()) != SU)
1347 for (SDNode *Node = SU->
getNode(); Node; Node =
Node->getGluedNode()) {
1352 if (
Node->getOperand(
NumOps-1).getValueType() == MVT::Glue)
1356 unsigned Flags =
Node->getConstantOperandVal(i);
1357 const InlineAsm::Flag
F(Flags);
1358 unsigned NumVals =
F.getNumOperandRegisters();
1361 if (
F.isRegDefKind() ||
F.isRegDefEarlyClobberKind() ||
1362 F.isClobberKind()) {
1364 for (; NumVals; --NumVals, ++i) {
1378 SDNode *SrcNode =
Node->getOperand(2).getNode();
1383 if (!
Node->isMachineOpcode())
1388 if (
Node->getMachineOpcode() ==
TII->getCallFrameDestroyOpcode()) {
1390 unsigned CallResource =
TRI->getNumRegs();
1391 if (LiveReg *LR = findLiveReg(CallResource)) {
1392 SDNode *Gen = LR->Gen->getNode();
1396 RegAdded.
insert(CallResource).second)
1401 CheckForLiveRegDefMasked(SU, RegMask, RegAdded, LRegs);
1403 const MCInstrDesc &MCID =
TII->get(
Node->getMachineOpcode());
1409 for (
unsigned i = 0; i < MCID.
getNumDefs(); ++i)
1410 if (MCID.
operands()[i].isOptionalDef()) {
1420 return !LRegs.
empty();
1423void ScheduleDAGRRList::releaseInterferences(
unsigned Reg) {
1425 for (
unsigned i = Interferences.
size(); i > 0; --i) {
1426 SUnit *SU = Interferences[i-1];
1427 LRegsMapT::iterator LRegsPos = LRegsMap.find(SU);
1429 SmallVectorImpl<unsigned> &LRegs = LRegsPos->second;
1439 AvailableQueue->
push(SU);
1441 if (i < Interferences.
size())
1442 Interferences[i-1] = Interferences.
back();
1444 LRegsMap.erase(LRegsPos);
1452SUnit *ScheduleDAGRRList::PickNodeToScheduleBottomUp() {
1453 SUnit *CurSU = AvailableQueue->
empty() ? nullptr : AvailableQueue->
pop();
1454 auto FindAvailableNode = [&]() {
1456 SmallVector<unsigned, 4> LRegs;
1457 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
1460 if (LRegs[0] ==
TRI->getNumRegs())
dbgs() <<
"CallResource";
1462 dbgs() <<
" " << *CurSU <<
'\n');
1463 auto [LRegsIter, LRegsInserted] = LRegsMap.try_emplace(CurSU, LRegs);
1464 if (LRegsInserted) {
1471 LRegsIter->second = LRegs;
1473 CurSU = AvailableQueue->
pop();
1476 FindAvailableNode();
1488 for (SUnit *TrySU : Interferences) {
1489 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
1493 SUnit *BtSU =
nullptr;
1494 unsigned LiveCycle = std::numeric_limits<unsigned>::max();
1495 for (
unsigned Reg : LRegs) {
1496 SUnit *Gen = getLiveRegGen(
Reg);
1502 if (!WillCreateCycle(TrySU, BtSU)) {
1504 BacktrackBottomUp(TrySU, BtSU);
1511 AvailableQueue->
remove(BtSU);
1513 LLVM_DEBUG(
dbgs() <<
"ARTIFICIAL edge from " << *BtSU <<
" to " << *TrySU
1519 if (!TrySU->isAvailable || !TrySU->NodeQueueId) {
1520 LLVM_DEBUG(
dbgs() <<
"TrySU not available; choosing node from queue\n");
1521 CurSU = AvailableQueue->
pop();
1525 AvailableQueue->
remove(TrySU);
1528 FindAvailableNode();
1540 SUnit *TrySU = Interferences[0];
1541 SmallVectorImpl<unsigned> &LRegs = LRegsMap[TrySU];
1542 assert(LRegs.
size() == 1 &&
"Can't handle this yet!");
1543 unsigned Reg = LRegs[0];
1544 SUnit *LRDef = getLiveRegDef(
Reg);
1555 SUnit *NewDef =
nullptr;
1557 NewDef = CopyAndMoveSuccessors(LRDef);
1558 if (!DestRC && !NewDef)
1564 InsertCopiesAndMoveSuccs(LRDef,
Reg, DestRC, RC,
Copies);
1566 << *
Copies.front() <<
"\n");
1571 LLVM_DEBUG(
dbgs() <<
" Adding an edge from " << *NewDef <<
" to "
1573 findLiveReg(
Reg)->Def = NewDef;
1578 assert(CurSU &&
"Unable to resolve live physical register dependencies!");
1584void ScheduleDAGRRList::ListScheduleBottomUp() {
1586 ReleasePredecessors(&ExitSU);
1589 if (!SUnits.empty()) {
1590 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
1591 assert(RootSU->
Succs.empty() &&
"Graph root shouldn't have successors!");
1593 AvailableQueue->
push(RootSU);
1599 while (!AvailableQueue->
empty() || !Interferences.empty()) {
1601 AvailableQueue->
dump(
this));
1605 SUnit *SU = PickNodeToScheduleBottomUp();
1607 AdvancePastStalls(SU);
1609 ScheduleNodeBottomUp(SU);
1611 while (AvailableQueue->
empty() && !PendingQueue.empty()) {
1613 assert(MinAvailableCycle < std::numeric_limits<unsigned>::max() &&
1614 "MinAvailableCycle uninitialized");
1615 AdvanceToCycle(std::max(CurCycle + 1, MinAvailableCycle));
1623 VerifyScheduledSequence(
true);
1629class RegReductionPQBase;
1632 bool isReady(SUnit* SU,
unsigned CurCycle)
const {
return true; }
1637struct reverse_sort :
public queue_sort {
1640 reverse_sort(SF &sf) : SortFunc(sf) {}
1642 bool operator()(SUnit* left, SUnit* right)
const {
1645 return SortFunc(right, left);
1652struct bu_ls_rr_sort :
public queue_sort {
1655 HasReadyFilter =
false
1658 RegReductionPQBase *SPQ;
1660 bu_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1662 bool operator()(SUnit* left, SUnit* right)
const;
1666struct src_ls_rr_sort :
public queue_sort {
1669 HasReadyFilter =
false
1672 RegReductionPQBase *SPQ;
1674 src_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1676 bool operator()(SUnit* left, SUnit* right)
const;
1680struct hybrid_ls_rr_sort :
public queue_sort {
1683 HasReadyFilter =
false
1686 RegReductionPQBase *SPQ;
1688 hybrid_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1690 bool isReady(SUnit *SU,
unsigned CurCycle)
const;
1692 bool operator()(SUnit* left, SUnit* right)
const;
1697struct ilp_ls_rr_sort :
public queue_sort {
1700 HasReadyFilter =
false
1703 RegReductionPQBase *SPQ;
1705 ilp_ls_rr_sort(RegReductionPQBase *spq) : SPQ(spq) {}
1707 bool isReady(SUnit *SU,
unsigned CurCycle)
const;
1709 bool operator()(SUnit* left, SUnit* right)
const;
1712class RegReductionPQBase :
public SchedulingPriorityQueue {
1714 std::vector<SUnit *> Queue;
1715 unsigned CurQueueId = 0;
1716 bool TracksRegPressure;
1720 std::vector<SUnit> *SUnits =
nullptr;
1723 const TargetInstrInfo *
TII =
nullptr;
1724 const TargetRegisterInfo *
TRI =
nullptr;
1725 const TargetLowering *
TLI =
nullptr;
1726 ScheduleDAGRRList *scheduleDAG =
nullptr;
1729 std::vector<unsigned> SethiUllmanNumbers;
1732 std::vector<unsigned> RegPressure;
1736 std::vector<unsigned> RegLimit;
1740 bool hasReadyFilter,
1743 const TargetInstrInfo *tii,
1744 const TargetRegisterInfo *tri,
1745 const TargetLowering *tli)
1746 : SchedulingPriorityQueue(hasReadyFilter), TracksRegPressure(tracksrp),
1747 SrcOrder(srcorder), MF(mf),
TII(tii),
TRI(tri),
TLI(tli) {
1748 if (TracksRegPressure) {
1749 unsigned NumRC =
TRI->getNumRegClasses();
1750 RegLimit.resize(NumRC);
1757 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1758 scheduleDAG = scheduleDag;
1761 ScheduleHazardRecognizer* getHazardRec() {
1762 return scheduleDAG->getHazardRec();
1765 void initNodes(std::vector<SUnit> &sunits)
override;
1767 void addNode(
const SUnit *SU)
override;
1769 void updateNode(
const SUnit *SU)
override;
1771 void releaseState()
override {
1773 SethiUllmanNumbers.clear();
1777 unsigned getNodePriority(
const SUnit *SU)
const;
1779 unsigned getNodeOrdering(
const SUnit *SU)
const {
1785 bool empty()
const override {
return Queue.empty(); }
1787 void push(SUnit *U)
override {
1788 assert(!
U->NodeQueueId &&
"Node in the queue already");
1789 U->NodeQueueId = ++CurQueueId;
1793 void remove(SUnit *SU)
override {
1796 std::vector<SUnit *>::iterator
I =
llvm::find(Queue, SU);
1797 if (
I != std::prev(
Queue.end()))
1803 bool tracksRegPressure()
const override {
return TracksRegPressure; }
1805 void dumpRegPressure()
const;
1807 bool HighRegPressure(
const SUnit *SU)
const;
1809 bool MayReduceRegPressure(SUnit *SU)
const;
1811 int RegPressureDiff(SUnit *SU,
unsigned &LiveUses)
const;
1813 void scheduledNode(SUnit *SU)
override;
1815 void unscheduledNode(SUnit *SU)
override;
1818 bool canClobber(
const SUnit *SU,
const SUnit *
Op);
1819 void AddPseudoTwoAddrDeps();
1820 void PrescheduleNodesWithMultipleUses();
1821 void CalculateSethiUllmanNumbers();
1825static SUnit *popFromQueueImpl(std::vector<SUnit *> &Q, SF &Picker) {
1826 unsigned BestIdx = 0;
1829 for (
unsigned I = 1,
E = std::min(Q.size(), (
decltype(Q.size()))1000);
I !=
E;
1831 if (Picker(Q[BestIdx], Q[
I]))
1833 SUnit *
V = Q[BestIdx];
1834 if (BestIdx + 1 != Q.size())
1841SUnit *popFromQueue(std::vector<SUnit *> &Q, SF &Picker, ScheduleDAG *DAG) {
1844 reverse_sort<SF> RPicker(Picker);
1845 return popFromQueueImpl(Q, RPicker);
1849 return popFromQueueImpl(Q, Picker);
1860class RegReductionPriorityQueue :
public RegReductionPQBase {
1867 const TargetInstrInfo *tii,
1868 const TargetRegisterInfo *tri,
1869 const TargetLowering *tli)
1870 : RegReductionPQBase(mf, SF::HasReadyFilter, tracksrp, srcorder,
1874 bool isBottomUp()
const override {
return SF::IsBottomUp; }
1876 bool isReady(SUnit *U)
const override {
1877 return Picker.HasReadyFilter && Picker.isReady(U, getCurCycle());
1880 SUnit *pop()
override {
1881 if (
Queue.empty())
return nullptr;
1883 SUnit *
V = popFromQueue(Queue, Picker, scheduleDAG);
1888#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1891 std::vector<SUnit *> DumpQueue =
Queue;
1892 SF DumpPicker = Picker;
1893 while (!DumpQueue.empty()) {
1894 SUnit *SU = popFromQueue(DumpQueue, DumpPicker, scheduleDAG);
1902using BURegReductionPriorityQueue = RegReductionPriorityQueue<bu_ls_rr_sort>;
1903using SrcRegReductionPriorityQueue = RegReductionPriorityQueue<src_ls_rr_sort>;
1904using HybridBURRPriorityQueue = RegReductionPriorityQueue<hybrid_ls_rr_sort>;
1905using ILPBURRPriorityQueue = RegReductionPriorityQueue<ilp_ls_rr_sort>;
1922 if (LSchedLow != RSchedLow)
1923 return LSchedLow < RSchedLow ? 1 : -1;
1931 if (SUNumbers[SU->
NodeNum] != 0)
1932 return SUNumbers[SU->
NodeNum];
1936 WorkState(
const SUnit *SU) : SU(SU) {}
1938 unsigned PredsProcessed = 0;
1943 while (!WorkList.
empty()) {
1944 auto &Temp = WorkList.
back();
1945 auto *TempSU = Temp.SU;
1946 bool AllPredsKnown =
true;
1948 for (
unsigned P = Temp.PredsProcessed;
P < TempSU->Preds.size(); ++
P) {
1949 auto &
Pred = TempSU->Preds[
P];
1950 if (
Pred.isCtrl())
continue;
1952 if (SUNumbers[PredSU->
NodeNum] == 0) {
1955 for (
auto It : WorkList)
1956 assert(It.SU != PredSU &&
"Trying to push an element twice?");
1959 Temp.PredsProcessed =
P + 1;
1960 WorkList.push_back(PredSU);
1961 AllPredsKnown =
false;
1970 unsigned SethiUllmanNumber = 0;
1972 for (
const SDep &
Pred : TempSU->Preds) {
1973 if (
Pred.isCtrl())
continue;
1975 unsigned PredSethiUllman = SUNumbers[PredSU->
NodeNum];
1976 assert(PredSethiUllman > 0 &&
"We should have evaluated this pred!");
1977 if (PredSethiUllman > SethiUllmanNumber) {
1978 SethiUllmanNumber = PredSethiUllman;
1980 }
else if (PredSethiUllman == SethiUllmanNumber)
1984 SethiUllmanNumber += Extra;
1985 if (SethiUllmanNumber == 0)
1986 SethiUllmanNumber = 1;
1987 SUNumbers[TempSU->NodeNum] = SethiUllmanNumber;
1991 assert(SUNumbers[SU->
NodeNum] > 0 &&
"SethiUllman should never be zero!");
1992 return SUNumbers[SU->
NodeNum];
1997void RegReductionPQBase::CalculateSethiUllmanNumbers() {
1998 SethiUllmanNumbers.assign(SUnits->size(), 0);
2000 for (
const SUnit &SU : *SUnits)
2004void RegReductionPQBase::addNode(
const SUnit *SU) {
2005 unsigned SUSize = SethiUllmanNumbers.size();
2006 if (SUnits->size() > SUSize)
2007 SethiUllmanNumbers.resize(SUSize*2, 0);
2011void RegReductionPQBase::updateNode(
const SUnit *SU) {
2012 SethiUllmanNumbers[SU->
NodeNum] = 0;
2018unsigned RegReductionPQBase::getNodePriority(
const SUnit *SU)
const {
2025 if (
Opc == TargetOpcode::EXTRACT_SUBREG ||
2026 Opc == TargetOpcode::SUBREG_TO_REG ||
2027 Opc == TargetOpcode::INSERT_SUBREG)
2043 return SethiUllmanNumbers[SU->
NodeNum];
2045 unsigned Priority = SethiUllmanNumbers[SU->
NodeNum];
2049 return (NP > 0) ? NP : 0;
2059#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2066 << RegLimit[Id] <<
'\n');
2071bool RegReductionPQBase::HighRegPressure(
const SUnit *SU)
const {
2078 SUnit *PredSU =
Pred.getSUnit();
2084 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2085 RegDefPos.IsValid(); RegDefPos.Advance()) {
2086 unsigned RCId,
Cost;
2089 if ((RegPressure[RCId] +
Cost) >= RegLimit[RCId])
2096bool RegReductionPQBase::MayReduceRegPressure(SUnit *SU)
const {
2099 if (!
N->isMachineOpcode() || !SU->
NumSuccs)
2102 unsigned NumDefs =
TII->get(
N->getMachineOpcode()).getNumDefs();
2103 for (
unsigned i = 0; i != NumDefs; ++i) {
2104 MVT VT =
N->getSimpleValueType(i);
2105 if (!
N->hasAnyUseOfValue(i))
2108 if (RegPressure[RCId] >= RegLimit[RCId])
2121int RegReductionPQBase::RegPressureDiff(SUnit *SU,
unsigned &LiveUses)
const {
2127 SUnit *PredSU =
Pred.getSUnit();
2135 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2136 RegDefPos.IsValid(); RegDefPos.Advance()) {
2137 MVT VT = RegDefPos.GetValue();
2139 if (RegPressure[RCId] >= RegLimit[RCId])
2145 if (!
N || !
N->isMachineOpcode() || !SU->
NumSuccs)
2148 unsigned NumDefs =
TII->get(
N->getMachineOpcode()).getNumDefs();
2149 for (
unsigned i = 0; i != NumDefs; ++i) {
2150 MVT VT =
N->getSimpleValueType(i);
2151 if (!
N->hasAnyUseOfValue(i))
2154 if (RegPressure[RCId] >= RegLimit[RCId])
2160void RegReductionPQBase::scheduledNode(SUnit *SU) {
2161 if (!TracksRegPressure)
2170 SUnit *PredSU =
Pred.getSUnit();
2193 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(PredSU, scheduleDAG);
2194 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2198 unsigned RCId,
Cost;
2209 for (ScheduleDAGSDNodes::RegDefIter RegDefPos(SU, scheduleDAG);
2210 RegDefPos.IsValid(); RegDefPos.Advance(), --SkipRegDefs) {
2211 if (SkipRegDefs > 0)
2213 unsigned RCId,
Cost;
2215 if (RegPressure[RCId] <
Cost) {
2228void RegReductionPQBase::unscheduledNode(SUnit *SU) {
2229 if (!TracksRegPressure)
2235 if (!
N->isMachineOpcode()) {
2239 unsigned Opc =
N->getMachineOpcode();
2240 if (
Opc == TargetOpcode::EXTRACT_SUBREG ||
2241 Opc == TargetOpcode::INSERT_SUBREG ||
2242 Opc == TargetOpcode::SUBREG_TO_REG ||
2243 Opc == TargetOpcode::REG_SEQUENCE ||
2244 Opc == TargetOpcode::IMPLICIT_DEF)
2251 SUnit *PredSU =
Pred.getSUnit();
2256 const SDNode *PN = PredSU->
getNode();
2266 if (POpc == TargetOpcode::IMPLICIT_DEF)
2268 if (POpc == TargetOpcode::EXTRACT_SUBREG ||
2269 POpc == TargetOpcode::INSERT_SUBREG ||
2270 POpc == TargetOpcode::SUBREG_TO_REG) {
2276 if (POpc == TargetOpcode::REG_SEQUENCE) {
2279 unsigned RCId = RC->
getID();
2286 for (
unsigned i = 0; i != NumDefs; ++i) {
2301 if (SU->
NumSuccs &&
N->isMachineOpcode()) {
2302 unsigned NumDefs =
TII->get(
N->getMachineOpcode()).getNumDefs();
2303 for (
unsigned i = NumDefs, e =
N->getNumValues(); i != e; ++i) {
2304 MVT VT =
N->getSimpleValueType(i);
2305 if (VT == MVT::Glue || VT == MVT::Other)
2307 if (!
N->hasAnyUseOfValue(i))
2324 unsigned MaxHeight = 0;
2326 if (Succ.
isCtrl())
continue;
2333 if (Height > MaxHeight)
2342 unsigned Scratches = 0;
2344 if (
Pred.isCtrl())
continue;
2353 bool RetVal =
false;
2355 if (
Pred.isCtrl())
continue;
2361 if (
Reg.isVirtual()) {
2375 bool RetVal =
false;
2377 if (Succ.
isCtrl())
continue;
2382 if (
Reg.isVirtual()) {
2414 if (
Pred.isCtrl())
continue;
2415 Pred.getSUnit()->isVRegCycle =
true;
2426 if (
Pred.isCtrl())
continue;
2430 "VRegCycle def must be CopyFromReg");
2431 Pred.getSUnit()->isVRegCycle =
false;
2444 if (
Pred.isCtrl())
continue;
2445 if (
Pred.getSUnit()->isVRegCycle &&
2458 if ((
int)SPQ->getCurCycle() < Height)
return true;
2459 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2468 RegReductionPQBase *SPQ) {
2473 int LHeight = (int)left->
getHeight() + LPenalty;
2474 int RHeight = (int)right->
getHeight() + RPenalty;
2487 if (LHeight != RHeight)
2488 return LHeight > RHeight ? 1 : -1;
2500 if (!SPQ->getHazardRec()->isEnabled()) {
2501 if (LHeight != RHeight)
2502 return LHeight > RHeight ? 1 : -1;
2504 int LDepth = left->
getDepth() - LPenalty;
2505 int RDepth = right->
getDepth() - RPenalty;
2506 if (LDepth != RDepth) {
2507 LLVM_DEBUG(
dbgs() <<
" Comparing latency of " << *left <<
" depth "
2508 << LDepth <<
" vs " << *right <<
" depth " << RDepth
2510 return LDepth < RDepth ? 1 : -1;
2526 if (LHasPhysReg != RHasPhysReg) {
2528 static const char *
const PhysRegMsg[] = {
" has no physreg",
2529 " defines a physreg" };
2531 LLVM_DEBUG(
dbgs() <<
" " << *left <<
" " << PhysRegMsg[LHasPhysReg]
2532 <<
" " << *right <<
" " << PhysRegMsg[RHasPhysReg]
2534 return LHasPhysReg < RHasPhysReg;
2539 unsigned LPriority = SPQ->getNodePriority(left);
2540 unsigned RPriority = SPQ->getNodePriority(right);
2546 RPriority = (RPriority > RNumVals) ? (RPriority - RNumVals) : 0;
2550 LPriority = (LPriority > LNumVals) ? (LPriority - LNumVals) : 0;
2553 if (LPriority != RPriority)
2554 return LPriority > RPriority;
2559 unsigned LOrder = SPQ->getNodeOrdering(left);
2560 unsigned ROrder = SPQ->getNodeOrdering(right);
2564 if ((LOrder || ROrder) && LOrder != ROrder)
2565 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2588 return LDist < RDist;
2593 if (LScratch != RScratch)
2594 return LScratch > RScratch;
2598 if ((left->
isCall && RPriority > 0) || (right->
isCall && LPriority > 0))
2617 "NodeQueueId cannot be zero");
2622bool bu_ls_rr_sort::operator()(SUnit *left, SUnit *right)
const {
2630bool src_ls_rr_sort::operator()(SUnit *left, SUnit *right)
const {
2634 unsigned LOrder = SPQ->getNodeOrdering(left);
2635 unsigned ROrder = SPQ->getNodeOrdering(right);
2639 if ((LOrder || ROrder) && LOrder != ROrder)
2640 return LOrder != 0 && (LOrder < ROrder || ROrder == 0);
2649bool hybrid_ls_rr_sort::isReady(SUnit *SU,
unsigned CurCycle)
const {
2650 static const unsigned ReadyDelay = 3;
2652 if (SPQ->MayReduceRegPressure(SU))
return true;
2654 if (SU->
getHeight() > (CurCycle + ReadyDelay))
return false;
2656 if (SPQ->getHazardRec()->getHazardType(SU, -ReadyDelay)
2664bool hybrid_ls_rr_sort::operator()(SUnit *left, SUnit *right)
const {
2672 bool LHigh = SPQ->HighRegPressure(left);
2673 bool RHigh = SPQ->HighRegPressure(right);
2676 if (LHigh && !RHigh) {
2677 LLVM_DEBUG(
dbgs() <<
" pressure " << *left <<
" > " << *right <<
"\n");
2680 else if (!LHigh && RHigh) {
2681 LLVM_DEBUG(
dbgs() <<
" pressure " << *right <<
" > " << *left <<
"\n");
2684 if (!LHigh && !RHigh) {
2694bool ilp_ls_rr_sort::isReady(SUnit *SU,
unsigned CurCycle)
const {
2695 if (SU->
getHeight() > CurCycle)
return false;
2697 if (SPQ->getHazardRec()->getHazardType(SU, 0)
2711 if (
Opc == TargetOpcode::EXTRACT_SUBREG ||
2712 Opc == TargetOpcode::SUBREG_TO_REG ||
2713 Opc == TargetOpcode::INSERT_SUBREG)
2728bool ilp_ls_rr_sort::operator()(SUnit *left, SUnit *right)
const {
2736 unsigned LLiveUses = 0, RLiveUses = 0;
2737 int LPDiff = 0, RPDiff = 0;
2739 LPDiff = SPQ->RegPressureDiff(left, LLiveUses);
2740 RPDiff = SPQ->RegPressureDiff(right, RLiveUses);
2743 LLVM_DEBUG(
dbgs() <<
"RegPressureDiff " << *left <<
": " << LPDiff
2744 <<
" != " << *right <<
": " << RPDiff <<
"\n");
2745 return LPDiff > RPDiff;
2751 if (LReduce && !RReduce)
return false;
2752 if (RReduce && !LReduce)
return true;
2757 <<
" != " << *right <<
": " << RLiveUses <<
"\n");
2758 return LLiveUses < RLiveUses;
2764 if (LStall != RStall)
2772 <<
" != " << *right <<
": " << right->
getDepth()
2787void RegReductionPQBase::initNodes(std::vector<SUnit> &sunits) {
2793 if (TracksRegPressure)
2795 RegLimit[RC.
getID()] =
TRI->getRegPressureLimit(&RC, MF);
2798 AddPseudoTwoAddrDeps();
2800 if (!TracksRegPressure && !SrcOrder)
2801 PrescheduleNodesWithMultipleUses();
2803 CalculateSethiUllmanNumbers();
2806 if (scheduleDAG->BB->isSuccessor(scheduleDAG->BB))
2807 for (SUnit &SU : sunits)
2815bool RegReductionPQBase::canClobber(
const SUnit *SU,
const SUnit *
Op) {
2818 const MCInstrDesc &MCID =
TII->get(
Opc);
2821 for (
unsigned i = 0; i !=
NumOps; ++i) {
2837 ScheduleDAGRRList *scheduleDAG,
2843 if (ImpDefs.
empty() && !RegMask)
2848 for (
const SDep &SuccPred : SuccSU->
Preds) {
2854 scheduleDAG->IsReachable(DepSU, SuccPred.
getSUnit()))
2861 if (
TRI->regsOverlap(ImpDef, SuccPred.
getReg()) &&
2862 scheduleDAG->IsReachable(DepSU, SuccPred.
getSUnit()))
2876 unsigned NumDefs =
TII->get(
N->getMachineOpcode()).getNumDefs();
2878 assert(!ImpDefs.
empty() &&
"Caller should check hasPhysRegDefs");
2881 if (!SUNode->isMachineOpcode())
2884 TII->get(SUNode->getMachineOpcode()).implicit_defs();
2886 if (SUImpDefs.
empty() && !SURegMask)
2888 for (
unsigned i = NumDefs, e =
N->getNumValues(); i != e; ++i) {
2889 MVT VT =
N->getSimpleValueType(i);
2890 if (VT == MVT::Glue || VT == MVT::Other)
2892 if (!
N->hasAnyUseOfValue(i))
2898 if (
TRI->regsOverlap(
Reg, SUReg))
2936void RegReductionPQBase::PrescheduleNodesWithMultipleUses() {
2938 for (SUnit &SU : *SUnits) {
2954 SDNode *PredFrameSetup =
nullptr;
2956 if (
Pred.isCtrl() &&
Pred.getSUnit()) {
2958 SDNode *PredND =
Pred.getSUnit()->getNode();
2969 PredFrameSetup = PredND;
2974 if (PredFrameSetup !=
nullptr)
2978 SUnit *PredSU =
nullptr;
2980 if (!
Pred.isCtrl()) {
2981 PredSU =
Pred.getSUnit();
3001 for (
const SDep &PredSucc : PredSU->
Succs) {
3002 SUnit *PredSuccSU = PredSucc.
getSUnit();
3003 if (PredSuccSU == &SU)
continue;
3007 goto outer_loop_continue;
3011 goto outer_loop_continue;
3013 if (scheduleDAG->IsReachable(&SU, PredSuccSU))
3014 goto outer_loop_continue;
3020 dbgs() <<
" Prescheduling " << SU <<
" next to PredSU " << *PredSU
3021 <<
" to guide scheduling in the presence of multiple uses\n");
3022 for (
unsigned i = 0; i != PredSU->
Succs.size(); ++i) {
3025 SUnit *SuccSU =
Edge.getSUnit();
3026 if (SuccSU != &SU) {
3027 Edge.setSUnit(PredSU);
3028 scheduleDAG->RemovePred(SuccSU,
Edge);
3029 scheduleDAG->AddPredQueued(&SU,
Edge);
3031 scheduleDAG->AddPredQueued(SuccSU,
Edge);
3035 outer_loop_continue:;
3046void RegReductionPQBase::AddPseudoTwoAddrDeps() {
3047 for (SUnit &SU : *SUnits) {
3056 unsigned Opc =
Node->getMachineOpcode();
3057 const MCInstrDesc &MCID =
TII->get(
Opc);
3060 for (
unsigned j = 0;
j !=
NumOps; ++
j) {
3066 const SUnit *DUSU = &(*SUnits)[DU->
getNodeId()];
3069 for (
const SDep &Succ : DUSU->
Succs) {
3084 while (SuccSU->
Succs.size() == 1 &&
3087 TargetOpcode::COPY_TO_REGCLASS)
3088 SuccSU = SuccSU->
Succs.front().getSUnit();
3101 if (SuccOpc == TargetOpcode::EXTRACT_SUBREG ||
3102 SuccOpc == TargetOpcode::INSERT_SUBREG ||
3103 SuccOpc == TargetOpcode::SUBREG_TO_REG)
3106 (!canClobber(SuccSU, DUSU) ||
3109 !scheduleDAG->IsReachable(SuccSU, &SU)) {
3110 LLVM_DEBUG(
dbgs() <<
" Adding a pseudo-two-addr edge from " << SU
3111 <<
" to " << *SuccSU <<
"\n");
3129 BURegReductionPriorityQueue *PQ =
3130 new BURegReductionPriorityQueue(*IS->MF,
false,
false,
TII,
TRI,
nullptr);
3131 ScheduleDAGRRList *SD =
new ScheduleDAGRRList(*IS->MF,
false, PQ, OptLevel);
3132 PQ->setScheduleDAG(SD);
3143 SrcRegReductionPriorityQueue *PQ =
3144 new SrcRegReductionPriorityQueue(*IS->MF,
false,
true,
TII,
TRI,
nullptr);
3145 ScheduleDAGRRList *SD =
new ScheduleDAGRRList(*IS->MF,
false, PQ, OptLevel);
3146 PQ->setScheduleDAG(SD);
3158 HybridBURRPriorityQueue *PQ =
3159 new HybridBURRPriorityQueue(*IS->MF,
true,
false,
TII,
TRI,
TLI);
3161 ScheduleDAGRRList *SD =
new ScheduleDAGRRList(*IS->MF,
true, PQ, OptLevel);
3162 PQ->setScheduleDAG(SD);
3173 ILPBURRPriorityQueue *PQ =
3174 new ILPBURRPriorityQueue(*IS->MF,
true,
false,
TII,
TRI,
TLI);
3175 ScheduleDAGRRList *SD =
new ScheduleDAGRRList(*IS->MF,
true, PQ, OptLevel);
3176 PQ->setScheduleDAG(SD);
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
This file defines the DenseMap class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
Register const TargetRegisterInfo * TRI
Promote Memory to Register
static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg)
std::pair< BasicBlock *, BasicBlock * > Edge
static bool CheckForLiveRegDef(SUnit *SU, MCRegister Reg, std::vector< SUnit * > &LiveRegDefs, SmallSet< unsigned, 4 > &RegAdded, SmallVectorImpl< unsigned > &LRegs, const TargetRegisterInfo *TRI, const SDNode *Node=nullptr)
CheckForLiveRegDef - Return true and update live register vector if the specified register def of the...
static bool canEnableCoalescing(SUnit *SU)
static RegisterScheduler sourceListDAGScheduler("source", "Similar to list-burr but schedules in source " "order when possible", createSourceListDAGScheduler)
static cl::opt< bool > DisableSchedCycles("disable-sched-cycles", cl::Hidden, cl::init(false), cl::desc("Disable cycle-level precision during preRA scheduling"))
static cl::opt< bool > DisableSchedStalls("disable-sched-stalls", cl::Hidden, cl::init(true), cl::desc("Disable no-stall priority in sched=list-ilp"))
static bool hasOnlyLiveInOpers(const SUnit *SU)
hasOnlyLiveInOpers - Return true if SU has only value predecessors that are CopyFromReg from a virtua...
static bool IsChainDependent(SDNode *Outer, SDNode *Inner, unsigned NestLevel, const TargetInstrInfo *TII)
IsChainDependent - Test if Outer is reachable from Inner through chain dependencies.
static bool hasOnlyLiveOutUses(const SUnit *SU)
hasOnlyLiveOutUses - Return true if SU has only value successors that are CopyToReg to a virtual regi...
static cl::opt< bool > DisableSchedCriticalPath("disable-sched-critical-path", cl::Hidden, cl::init(false), cl::desc("Disable critical path priority in sched=list-ilp"))
static cl::opt< bool > Disable2AddrHack("disable-2addr-hack", cl::Hidden, cl::init(true), cl::desc("Disable scheduler's two-address hack"))
static RegisterScheduler ILPListDAGScheduler("list-ilp", "Bottom-up register pressure aware list scheduling " "which tries to balance ILP and register pressure", createILPListDAGScheduler)
static void resetVRegCycle(SUnit *SU)
static RegisterScheduler hybridListDAGScheduler("list-hybrid", "Bottom-up register pressure aware list scheduling " "which tries to balance latency and register pressure", createHybridListDAGScheduler)
static bool canClobberReachingPhysRegUse(const SUnit *DepSU, const SUnit *SU, ScheduleDAGRRList *scheduleDAG, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
canClobberReachingPhysRegUse - True if SU would clobber one of it's successor's explicit physregs who...
static cl::opt< bool > DisableSchedPhysRegJoin("disable-sched-physreg-join", cl::Hidden, cl::init(false), cl::desc("Disable physreg def-use affinity"))
static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI)
canClobberPhysRegDefs - True if SU would clobber one of SuccSU's physical register defs.
static cl::opt< unsigned > AvgIPC("sched-avg-ipc", cl::Hidden, cl::init(1), cl::desc("Average inst/cycle when no target itinerary exists."))
static void GetCostForDef(const ScheduleDAGSDNodes::RegDefIter &RegDefPos, const TargetLowering *TLI, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, unsigned &RegClass, unsigned &Cost, const MachineFunction &MF)
GetCostForDef - Looks up the register class and cost for a given definition.
static bool BURRSort(SUnit *left, SUnit *right, RegReductionPQBase *SPQ)
static cl::opt< bool > DisableSchedRegPressure("disable-sched-reg-pressure", cl::Hidden, cl::init(false), cl::desc("Disable regpressure priority in sched=list-ilp"))
static bool BUHasStall(SUnit *SU, int Height, RegReductionPQBase *SPQ)
static void initVRegCycle(SUnit *SU)
static constexpr unsigned RegSequenceCost
static cl::opt< int > MaxReorderWindow("max-sched-reorder", cl::Hidden, cl::init(6), cl::desc("Number of instructions to allow ahead of the critical path " "in sched=list-ilp"))
static SDNode * FindCallSeqStart(SDNode *N, unsigned &NestLevel, unsigned &MaxNest, const TargetInstrInfo *TII)
FindCallSeqStart - Starting from the (lowered) CALLSEQ_END node, locate the corresponding (lowered) C...
static bool isOperandOf(const SUnit *SU, SDNode *N)
static cl::opt< bool > DisableSchedVRegCycle("disable-sched-vrcycle", cl::Hidden, cl::init(false), cl::desc("Disable virtual register cycle interference checks"))
static int checkSpecialNodes(const SUnit *left, const SUnit *right)
static cl::opt< bool > DisableSchedLiveUses("disable-sched-live-uses", cl::Hidden, cl::init(true), cl::desc("Disable live use priority in sched=list-ilp"))
static const uint32_t * getNodeRegMask(const SDNode *N)
getNodeRegMask - Returns the register mask attached to an SDNode, if any.
static unsigned closestSucc(const SUnit *SU)
closestSucc - Returns the scheduled cycle of the successor which is closest to the current cycle.
static bool hasVRegCycleUse(const SUnit *SU)
static cl::opt< bool > DisableSchedHeight("disable-sched-height", cl::Hidden, cl::init(false), cl::desc("Disable scheduled-height priority in sched=list-ilp"))
static RegisterScheduler burrListDAGScheduler("list-burr", "Bottom-up register reduction list scheduling", createBURRListDAGScheduler)
static unsigned calcMaxScratches(const SUnit *SU)
calcMaxScratches - Returns an cost estimate of the worse case requirement for scratch registers,...
static unsigned CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector< unsigned > &SUNumbers)
CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
static int BUCompareLatency(SUnit *left, SUnit *right, bool checkPref, RegReductionPQBase *SPQ)
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the SparseSet class derived from the version described in Briggs,...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
This file describes how to lower LLVM code to machine code.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool empty() const
Check if the array is empty.
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
ArrayRef< MCOperandInfo > operands() const
bool hasOptionalDef() const
Set if this instruction has an optional definition, e.g.
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
int getOperandConstraint(unsigned OpNum, MCOI::OperandConstraint Constraint) const
Returns the value of the specified operand constraint if it is present.
ArrayRef< MCPhysReg > implicit_defs() const
Return a list of registers that are potentially written by any instance of this machine instruction.
bool isCommutable() const
Return true if this may be a 2- or 3-address instruction (of the form "X = op Y, Z,...
unsigned getID() const
getID() - Return the register class ID number.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
static bool clobbersPhysReg(const uint32_t *RegMask, MCRegister PhysReg)
clobbersPhysReg - Returns true if this RegMask clobbers PhysReg.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
Wrapper class representing virtual and physical registers.
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
int getNodeId() const
Return the unique node id.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
unsigned getIROrder() const
Return the node ordering.
void setNodeId(int Id)
Set unique node id.
MVT getSimpleValueType(unsigned ResNo) const
Return the type of a specified result as a simple type.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
const SDValue & getOperand(unsigned Num) const
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
LLVM_ABI bool hasAnyUseOfValue(unsigned Value) const
Return true if there are any use of the indicated value.
SDNode * getGluedNode() const
If this node has a glue operand, return the node to which the glue operand points.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
@ Data
Regular data dependence (aka true-dependence).
@ Artificial
Arbitrary strong DAG edge (no real dependence).
unsigned getLatency() const
Returns the latency value for this edge, which roughly means the minimum number of cycles that must e...
bool isAssignedRegDep() const
Tests if this is a Data dependence that is associated with a register.
bool isArtificial() const
Tests if this is an Order dependence that is marked as "artificial", meaning it isn't necessary for c...
bool isCtrl() const
Shorthand for getKind() != SDep::Data.
Register getReg() const
Returns the register associated with this edge.
Scheduling unit. This is a node in the scheduling DAG.
bool isCall
Is a function call.
LLVM_ABI void setHeightToAtLeast(unsigned NewHeight)
If NewHeight is greater than this node's height value, set it to be the new height value.
unsigned NodeQueueId
Queue id of node.
unsigned NodeNum
Entry # of node in the node vector.
bool hasPhysRegClobbers
Has any physreg defs, used or not.
bool isCallOp
Is a function call operand.
const TargetRegisterClass * CopyDstRC
Is a special copy node if != nullptr.
unsigned getHeight() const
Returns the height of this node, which is the length of the maximum path down to any node which has n...
LLVM_ABI void setHeightDirty()
Sets a flag in this node to indicate that its stored Height value will require recomputation the next...
bool isSucc(const SUnit *N) const
Tests if node N is a successor of this node.
LLVM_ABI void removePred(const SDep &D)
Removes the specified edge as a pred of the current node if it exists.
unsigned short Latency
Node latency.
unsigned short NumRegDefsLeft
bool isPending
True once pending.
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...
bool isScheduled
True once scheduled.
bool isAvailable
True once available.
bool isScheduleLow
True if preferable to schedule low.
bool hasPhysRegDefs
Has physreg defs that are being used.
SmallVector< SDep, 4 > Succs
All sunit successors.
Sched::Preference SchedulingPref
Scheduling preference.
const TargetRegisterClass * CopySrcRC
SDNode * getNode() const
Returns the representative SDNode for this SUnit.
bool isTwoAddress
Is a two-address instruction.
bool isCommutable
Is a commutable instruction.
bool isVRegCycle
May use and def the same vreg.
SmallVector< SDep, 4 > Preds
All sunit predecessors.
LLVM_ABI bool addPred(const SDep &D, bool Required=true)
Adds the specified edge as a pred of the current node if not already.
RegDefIter - In place iteration over the values defined by an SUnit.
const SDNode * GetNode() const
ScheduleDAGSDNodes - A ScheduleDAG for scheduling SDNode-based DAGs.
void MarkDirty()
Mark the ordering as temporarily broken, after a new node has been added.
virtual void dumpNode(const SUnit &SU) const =0
HazardRecognizer - This determines whether or not an instruction can be issued this cycle,...
unsigned getMaxLookAhead() const
virtual void RecedeCycle()
RecedeCycle - This callback is invoked whenever the next bottom-up instruction to be scheduled cannot...
virtual void Reset()
Reset - This callback is invoked when a new block of instructions is about to be schedule.
virtual void EmitInstruction(SUnit *)
EmitInstruction - This callback is invoked when an instruction is emitted, to advance the hazard stat...
virtual bool atIssueLimit() const
atIssueLimit - Return true if no more instructions may be issued in this cycle.
virtual HazardType getHazardType(SUnit *, int Stalls=0)
getHazardType - Return the hazard type of emitting this node.
This interface is used to plug different priorities computation algorithms into the list scheduler.
void setCurCycle(unsigned Cycle)
virtual void remove(SUnit *SU)=0
virtual void releaseState()=0
virtual void scheduledNode(SUnit *)
As each node is scheduled, this method is invoked.
virtual bool tracksRegPressure() const
virtual void dump(ScheduleDAG *) const
bool hasReadyFilter() const
virtual void initNodes(std::vector< SUnit > &SUnits)=0
virtual bool empty() const =0
virtual void unscheduledNode(SUnit *)
virtual void addNode(const SUnit *SU)=0
virtual void updateNode(const SUnit *SU)=0
virtual void push(SUnit *U)=0
SelectionDAGISel - This is the common base class used for SelectionDAG-based pattern-matching instruc...
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
TargetInstrInfo - Interface to description of machine instruction set.
virtual uint8_t getRepRegClassCostFor(MVT VT) const
Return the cost of the 'representative' register class for the specified value type.
virtual const TargetRegisterClass * getRepRegClassFor(MVT VT) const
Return the 'representative' register class for the specified value type.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
@ LIFETIME_START
This corresponds to the llvm.lifetime.
@ INLINEASM_BR
INLINEASM_BR - Branching version of inline asm. Used by asm-goto.
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
@ INLINEASM
INLINEASM - Represents an inline asm block.
initializer< Ty > init(const Ty &Val)
Sequence
A sequence of states that a pointer may go through in which an objc_retain and objc_release are actua...
NodeAddr< DefNode * > Def
NodeAddr< NodeBase * > Node
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI ScheduleDAGSDNodes * createBURRListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createBURRListDAGScheduler - This creates a bottom up register usage reduction list scheduler.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI ScheduleDAGSDNodes * createHybridListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel)
createHybridListDAGScheduler - This creates a bottom up register pressure aware list scheduler that m...
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
CodeGenOptLevel
Code generation optimization level.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI ScheduleDAGSDNodes * createSourceListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel OptLevel)
createSourceListDAGScheduler - This creates a bottom up list scheduler that schedules nodes in source...
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
DWARFExpression::Operation Op
LLVM_ABI ScheduleDAGSDNodes * createILPListDAGScheduler(SelectionDAGISel *IS, CodeGenOptLevel)
createILPListDAGScheduler - This creates a bottom up register pressure aware list scheduler that trie...
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
MCRegisterClass TargetRegisterClass
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.