96 #include "llvm/Config/llvm-config.h" 115 #include <functional> 123 using namespace llvm;
125 #define DEBUG_TYPE "pipeliner" 127 STATISTIC(NumTrytoPipeline,
"Number of loops that we attempt to pipeline");
128 STATISTIC(NumPipelined,
"Number of loops software pipelined");
129 STATISTIC(NumNodeOrderIssues,
"Number of node order issues found");
134 cl::desc(
"Enable Software Pipelining"));
143 cl::desc(
"Size limit for the MII."),
149 cl::desc(
"Maximum stages allowed in the generated scheduled."),
156 cl::desc(
"Prune dependences between unrelated Phi nodes."),
163 cl::desc(
"Prune loop carried order dependences."),
231 MachinePipeliner &
Pass;
235 bool Scheduled =
false;
247 int ZeroLatencyDepth = 0;
248 int ZeroLatencyHeight = 0;
250 NodeInfo() =
default;
253 std::vector<NodeInfo> ScheduleInfo;
255 enum OrderKind { BottomUp = 0, TopDown = 1 };
272 std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
276 std::vector<SUnit> &SUnits;
282 static unsigned MaxPaths;
285 Circuits(std::vector<SUnit> &SUs)
286 : SUnits(SUs), Blocked(SUs.
size()), B(SUs.
size()), AdjK(SUs.
size()) {}
296 void createAdjacencyStructure(SwingSchedulerDAG *DAG);
297 bool circuit(
int V,
int S, NodeSetType &NodeSets,
bool HasBackedge =
false);
305 RegClassInfo(rci), Topo(SUnits, &ExitSU) {
306 P.MF->getSubtarget().getSMSMutations(Mutations);
309 void schedule()
override;
310 void finishBlock()
override;
313 bool hasNewSchedule() {
return Scheduled; }
316 int getASAP(
SUnit *Node) {
return ScheduleInfo[Node->
NodeNum].ASAP; }
319 int getALAP(
SUnit *Node) {
return ScheduleInfo[Node->
NodeNum].ALAP; }
323 int getMOV(
SUnit *Node) {
return getALAP(Node) - getASAP(Node); }
330 int getZeroLatencyDepth(
SUnit *Node) {
331 return ScheduleInfo[Node->
NodeNum].ZeroLatencyDepth;
339 int getZeroLatencyHeight(
SUnit *Node) {
340 return ScheduleInfo[Node->
NodeNum].ZeroLatencyHeight;
352 bool isLoopCarriedDep(
SUnit *Source,
const SDep &Dep,
bool isSucc =
true);
365 void setMII(
unsigned mii) { MII = mii; }
369 void fixupRegisterOverlaps(std::deque<SUnit *> &Instrs);
373 unsigned getInstrBaseReg(
SUnit *SU) {
375 InstrChanges.
find(SU);
376 if (It != InstrChanges.
end())
377 return It->second.first;
381 void addMutation(std::unique_ptr<ScheduleDAGMutation>
Mutation) {
382 Mutations.push_back(std::move(Mutation));
387 void updatePhiDependences();
388 void changeDependences();
389 unsigned calculateResMII();
390 unsigned calculateRecMII(NodeSetType &RecNodeSets);
391 void findCircuits(NodeSetType &NodeSets);
392 void fuseRecs(NodeSetType &NodeSets);
393 void removeDuplicateNodes(NodeSetType &NodeSets);
394 void computeNodeFunctions(NodeSetType &NodeSets);
395 void registerPressureFilter(NodeSetType &NodeSets);
396 void colocateNodeSets(NodeSetType &NodeSets);
397 void checkNodeSets(NodeSetType &NodeSets);
398 void groupRemainingNodes(NodeSetType &NodeSets);
401 void computeNodeOrder(NodeSetType &NodeSets);
402 void checkValidNodeOrder(
const NodeSetType &Circuits)
const;
403 bool schedulePipeline(SMSchedule &Schedule);
404 void generatePipelinedLoop(SMSchedule &Schedule);
405 void generateProlog(SMSchedule &Schedule,
unsigned LastStage,
407 MBBVectorTy &PrologBBs);
408 void generateEpilog(SMSchedule &Schedule,
unsigned LastStage,
410 MBBVectorTy &EpilogBBs, MBBVectorTy &PrologBBs);
413 SMSchedule &Schedule, ValueMapTy *VRMap,
414 InstrMapTy &InstrMap,
unsigned LastStageNum,
415 unsigned CurStageNum,
bool IsLast);
418 SMSchedule &Schedule, ValueMapTy *VRMap,
419 InstrMapTy &InstrMap,
unsigned LastStageNum,
420 unsigned CurStageNum,
bool IsLast);
422 MBBVectorTy &EpilogBBs);
424 SMSchedule &Schedule);
426 MBBVectorTy &EpilogBBs, SMSchedule &Schedule,
432 unsigned InstStageNum);
434 unsigned InstStageNum,
435 SMSchedule &Schedule);
436 void updateInstruction(
MachineInstr *NewMI,
bool LastDef,
437 unsigned CurStageNum,
unsigned InstrStageNum,
438 SMSchedule &Schedule, ValueMapTy *VRMap);
440 unsigned getPrevMapVal(
unsigned StageNum,
unsigned PhiStage,
unsigned LoopVal,
441 unsigned LoopStage, ValueMapTy *VRMap,
444 SMSchedule &Schedule, ValueMapTy *VRMap,
445 InstrMapTy &InstrMap);
447 InstrMapTy &InstrMap,
unsigned CurStageNum,
449 unsigned OldReg,
unsigned NewReg,
450 unsigned PrevReg = 0);
452 unsigned &OffsetPos,
unsigned &NewBase,
454 void postprocessDAG();
461 bool HasRecurrence =
false;
465 unsigned Colocate = 0;
466 SUnit *ExceedPressure =
nullptr;
473 NodeSet(iterator S, iterator
E) : Nodes(S, E), HasRecurrence(
true) {
475 for (
unsigned i = 0, e = Nodes.
size(); i < e; ++i)
476 for (
const SDep &Succ : Nodes[i]->Succs)
477 if (Nodes.
count(Succ.getSUnit()))
478 Latency += Succ.getLatency();
481 bool insert(
SUnit *SU) {
return Nodes.
insert(SU); }
483 void insert(iterator S, iterator E) { Nodes.
insert(S, E); }
485 template <
typename UnaryPredicate>
bool remove_if(UnaryPredicate P) {
491 bool hasRecurrence() {
return HasRecurrence; };
493 unsigned size()
const {
return Nodes.
size(); }
495 bool empty()
const {
return Nodes.
empty(); }
497 SUnit *getNode(
unsigned i)
const {
return Nodes[i]; };
499 void setRecMII(
unsigned mii) { RecMII = mii; };
501 void setColocate(
unsigned c) { Colocate = c; };
503 void setExceedPressure(
SUnit *SU) { ExceedPressure = SU; }
505 bool isExceedSU(
SUnit *SU) {
return ExceedPressure == SU; }
507 int compareRecMII(
NodeSet &RHS) {
return RecMII - RHS.RecMII; }
509 int getRecMII() {
return RecMII; }
512 void computeNodeSetInfo(SwingSchedulerDAG *SSD) {
513 for (
SUnit *SU : *
this) {
514 MaxMOV =
std::max(MaxMOV, SSD->getMOV(SU));
515 MaxDepth =
std::max(MaxDepth, SSD->getDepth(SU));
521 unsigned getMaxDepth() {
return MaxDepth; }
526 HasRecurrence =
false;
530 ExceedPressure =
nullptr;
540 if (RecMII == RHS.RecMII) {
541 if (Colocate != 0 && RHS.Colocate != 0 && Colocate != RHS.Colocate)
542 return Colocate < RHS.Colocate;
543 if (MaxMOV == RHS.MaxMOV)
544 return MaxDepth > RHS.MaxDepth;
545 return MaxMOV < RHS.MaxMOV;
547 return RecMII > RHS.RecMII;
551 return RecMII == RHS.RecMII && MaxMOV == RHS.MaxMOV &&
552 MaxDepth == RHS.MaxDepth;
558 iterator
end() {
return Nodes.
end(); }
561 os <<
"Num nodes " <<
size() <<
" rec " << RecMII <<
" mov " << MaxMOV
562 <<
" depth " << MaxDepth <<
" col " << Colocate <<
"\n";
563 for (
const auto &
I : Nodes)
564 os <<
" SU(" <<
I->NodeNum <<
") " << *(
I->getInstr());
568 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 587 std::map<SUnit *, int> InstrToCycle;
593 std::map<unsigned, std::pair<unsigned, bool>> RegToStageDiff;
603 int InitiationInterval = 0;
611 std::unique_ptr<DFAPacketizer> Resources;
615 : ST(mf->getSubtarget()), MRI(mf->getRegInfo()),
616 Resources(ST.getInstrInfo()->CreateTargetScheduleState(ST)) {}
619 ScheduledInstrs.
clear();
620 InstrToCycle.clear();
621 RegToStageDiff.clear();
624 InitiationInterval = 0;
628 void setInitiationInterval(
int ii) { InitiationInterval = ii; }
632 int getFirstCycle()
const {
return FirstCycle; }
635 int getFinalCycle()
const {
return FirstCycle + InitiationInterval - 1; }
639 int earliestCycleInChain(
const SDep &Dep);
643 int latestCycleInChain(
const SDep &Dep);
645 void computeStart(
SUnit *SU,
int *MaxEarlyStart,
int *MinLateStart,
646 int *MinEnd,
int *MaxStart,
int II, SwingSchedulerDAG *DAG);
647 bool insert(
SUnit *SU,
int StartCycle,
int EndCycle,
int II);
651 using const_sched_iterator =
655 bool isScheduledAtStage(
SUnit *SU,
unsigned StageNum) {
656 return (stageScheduled(SU) == (
int)StageNum);
661 int stageScheduled(
SUnit *SU)
const {
662 std::map<SUnit *, int>::const_iterator it = InstrToCycle.
find(SU);
663 if (it == InstrToCycle.end())
665 return (it->second - FirstCycle) / InitiationInterval;
670 unsigned cycleScheduled(
SUnit *SU)
const {
671 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SU);
672 assert(it != InstrToCycle.end() &&
"Instruction hasn't been scheduled.");
673 return (it->second - FirstCycle) % InitiationInterval;
677 unsigned getMaxStageCount() {
678 return (LastCycle - FirstCycle) / InitiationInterval;
683 unsigned getStagesForReg(
int Reg,
unsigned CurStage) {
684 std::pair<unsigned, bool> Stages = RegToStageDiff[
Reg];
685 if (CurStage > getMaxStageCount() && Stages.first == 0 && Stages.second)
696 unsigned getStagesForPhi(
int Reg) {
697 std::pair<unsigned, bool> Stages = RegToStageDiff[
Reg];
700 return Stages.first - 1;
704 std::deque<SUnit *> &getInstructions(
int cycle) {
705 return ScheduledInstrs[cycle];
708 bool isValidSchedule(SwingSchedulerDAG *SSD);
709 void finalizeSchedule(SwingSchedulerDAG *SSD);
710 void orderDependence(SwingSchedulerDAG *SSD,
SUnit *SU,
711 std::deque<SUnit *> &Insts);
712 bool isLoopCarried(SwingSchedulerDAG *SSD,
MachineInstr &Phi);
721 unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
724 int MachinePipeliner::NumTries = 0;
729 "Modulo Software Pipelining",
false,
false)
739 if (skipFunction(mf.getFunction()))
745 if (mf.getFunction().getAttributes().hasAttribute(
751 MLI = &getAnalysis<MachineLoopInfo>();
752 MDT = &getAnalysis<MachineDominatorTree>();
766 bool MachinePipeliner::scheduleLoop(
MachineLoop &L) {
767 bool Changed =
false;
768 for (
auto &InnerLoop : L)
769 Changed |= scheduleLoop(*InnerLoop);
781 if (!canPipelineLoop(L))
786 Changed = swingModuloScheduler(L);
794 bool MachinePipeliner::canPipelineLoop(
MachineLoop &L) {
806 LI.LoopInductionVar =
nullptr;
807 LI.LoopCompare =
nullptr;
808 if (TII->
analyzeLoop(L, LI.LoopInductionVar, LI.LoopCompare))
821 SlotIndexes &Slots = *getAnalysis<LiveIntervals>().getSlotIndexes();
828 for (
unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
839 auto Copy =
BuildMI(PredB, At, DL, TII->
get(TargetOpcode::COPY), NewReg)
853 bool MachinePipeliner::swingModuloScheduler(
MachineLoop &L) {
854 assert(L.
getBlocks().size() == 1 &&
"SMS works on single blocks only.");
856 SwingSchedulerDAG SMS(*
this, L, getAnalysis<LiveIntervals>(), RegClassInfo);
876 return SMS.hasNewSchedule();
881 void SwingSchedulerDAG::schedule() {
884 addLoopCarriedDependences(AA);
885 updatePhiDependences();
890 for (
unsigned su = 0, e = SUnits.size(); su != e; ++su)
891 SUnits[su].dumpAll(
this);
894 NodeSetType NodeSets;
895 findCircuits(NodeSets);
896 NodeSetType Circuits = NodeSets;
899 unsigned ResMII = calculateResMII();
900 unsigned RecMII = calculateRecMII(NodeSets);
910 <<
", res=" << ResMII <<
")\n");
920 computeNodeFunctions(NodeSets);
922 registerPressureFilter(NodeSets);
924 colocateNodeSets(NodeSets);
926 checkNodeSets(NodeSets);
929 for (
auto &
I : NodeSets) {
930 dbgs() <<
" Rec NodeSet ";
935 std::stable_sort(NodeSets.begin(), NodeSets.end(), std::greater<NodeSet>());
937 groupRemainingNodes(NodeSets);
939 removeDuplicateNodes(NodeSets);
942 for (
auto &
I : NodeSets) {
943 dbgs() <<
" NodeSet ";
948 computeNodeOrder(NodeSets);
951 checkValidNodeOrder(Circuits);
953 SMSchedule Schedule(Pass.MF);
954 Scheduled = schedulePipeline(Schedule);
959 unsigned numStages = Schedule.getMaxStageCount();
968 generatePipelinedLoop(Schedule);
973 void SwingSchedulerDAG::finishBlock() {
985 unsigned &InitVal,
unsigned &LoopVal) {
996 assert(InitVal != 0 && LoopVal != 0 &&
"Unexpected Phi structure.");
1020 while (!Worklist.
empty()) {
1023 SUnit *SuccSU =
SI.getSUnit();
1025 if (Visited.
count(SuccSU))
1057 for (
Value *V : Objs) {
1070 void SwingSchedulerDAG::addLoopCarriedDependences(
AliasAnalysis *AA) {
1072 Value *UnknownValue =
1074 for (
auto &SU : SUnits) {
1077 PendingLoads.
clear();
1083 for (
auto V : Objs) {
1092 for (
auto V : Objs) {
1094 PendingLoads.
find(V);
1095 if (I == PendingLoads.
end())
1097 for (
auto Load : I->second) {
1104 unsigned BaseReg1, BaseReg2;
1105 int64_t Offset1, Offset2;
1108 if (BaseReg1 == BaseReg2 && (
int)Offset1 < (int)Offset2) {
1110 "What happened to the chain edge?");
1164 void SwingSchedulerDAG::updatePhiDependences() {
1169 for (
SUnit &
I : SUnits) {
1172 unsigned HasPhiUse = 0;
1173 unsigned HasPhiDef = 0;
1178 MOI != MOE; ++MOI) {
1181 unsigned Reg = MOI->getReg();
1189 SUnit *SU = getSUnit(UseMI);
1190 if (SU !=
nullptr && UseMI->
isPHI()) {
1199 if (SU->
NodeNum <
I.NodeNum && !
I.isPred(SU))
1204 }
else if (MOI->isUse()) {
1207 if (DefMI ==
nullptr)
1209 SUnit *SU = getSUnit(DefMI);
1210 if (SU !=
nullptr && DefMI->
isPHI()) {
1220 if (SU->
NodeNum <
I.NodeNum && !
I.isPred(SU))
1229 for (
auto &PI :
I.Preds) {
1232 if (
I.getInstr()->isPHI()) {
1241 for (
int i = 0, e = RemoveDeps.
size(); i != e; ++i)
1242 I.removePred(RemoveDeps[i]);
1248 void SwingSchedulerDAG::changeDependences() {
1252 for (
SUnit &
I : SUnits) {
1253 unsigned BasePos = 0, OffsetPos = 0, NewBase = 0;
1254 int64_t NewOffset = 0;
1255 if (!canUseLastOffsetValue(
I.getInstr(), BasePos, OffsetPos, NewBase,
1260 unsigned OrigBase =
I.getInstr()->getOperand(BasePos).getReg();
1264 SUnit *DefSU = getSUnit(DefMI);
1271 SUnit *LastSU = getSUnit(LastMI);
1282 if (P->getSUnit() == DefSU)
1284 for (
int i = 0, e = Deps.
size(); i != e; i++) {
1286 I.removePred(Deps[i]);
1290 for (
auto &P : LastSU->
Preds)
1293 for (
int i = 0, e = Deps.
size(); i != e; i++) {
1305 InstrChanges[&
I] = std::make_pair(NewBase, NewOffset);
1313 struct FuncUnitSorter {
1322 unsigned minFuncUnits(
const MachineInstr *Inst,
unsigned &
F)
const {
1324 unsigned min = UINT_MAX;
1328 unsigned funcUnits = IS->getUnits();
1330 if (numAlternatives < min) {
1331 min = numAlternatives;
1348 unsigned FuncUnits = IS->getUnits();
1350 Resources[FuncUnits]++;
1356 unsigned F1 = 0, F2 = 0;
1357 unsigned MFUs1 = minFuncUnits(IS1, F1);
1358 unsigned MFUs2 = minFuncUnits(IS2, F2);
1359 if (MFUs1 == 1 && MFUs2 == 1)
1361 return MFUs1 > MFUs2;
1373 unsigned SwingSchedulerDAG::calculateResMII() {
1380 FuncUnitSorter FUS =
1385 FUS.calcCriticalResources(*
I);
1392 FuncUnitOrder.push(&*
I);
1394 while (!FuncUnitOrder.empty()) {
1396 FuncUnitOrder.pop();
1401 unsigned NumCycles = getSUnit(MI)->Latency;
1402 unsigned ReservedCycles = 0;
1405 for (
unsigned C = 0;
C < NumCycles; ++
C)
1407 if ((*RI++)->canReserveResources(*MI)) {
1413 for (
unsigned C = 0;
C < ReservedCycles; ++
C) {
1415 (*RI)->reserveResources(*MI);
1418 for (
unsigned C = ReservedCycles;
C < NumCycles; ++
C) {
1426 int Resmii = Resources.
size();
1442 unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1443 unsigned RecMII = 0;
1445 for (
NodeSet &Nodes : NodeSets) {
1449 unsigned Delay = Nodes.getLatency();
1450 unsigned Distance = 1;
1453 unsigned CurMII = (Delay + Distance - 1) / Distance;
1454 Nodes.setRecMII(CurMII);
1455 if (CurMII > RecMII)
1466 for (
unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1467 SUnit *SU = &SUnits[i];
1472 DepsAdded.
push_back(std::make_pair(SU, *IP));
1476 E = DepsAdded.
end();
1482 unsigned Reg = D.
getReg();
1492 void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1493 SwingSchedulerDAG *DAG) {
1496 for (
int i = 0, e = SUnits.size(); i != e; ++i) {
1499 for (
auto &
SI : SUnits[i].Succs) {
1503 int N =
SI.getSUnit()->NodeNum;
1505 auto Dep = OutputDeps.find(BackEdge);
1506 if (Dep != OutputDeps.end()) {
1507 BackEdge = Dep->second;
1508 OutputDeps.erase(Dep);
1510 OutputDeps[
N] = BackEdge;
1514 if (
SI.getSUnit()->isBoundaryNode() ||
1515 (
SI.getKind() ==
SDep::Anti && !
SI.getSUnit()->getInstr()->isPHI()))
1517 int N =
SI.getSUnit()->NodeNum;
1518 if (!Added.test(N)) {
1525 for (
auto &PI : SUnits[i].Preds) {
1526 if (!SUnits[i].getInstr()->mayStore() ||
1527 !DAG->isLoopCarriedDep(&SUnits[i], PI,
false))
1529 if (PI.getKind() ==
SDep::Order && PI.getSUnit()->getInstr()->mayLoad()) {
1530 int N = PI.getSUnit()->NodeNum;
1531 if (!Added.test(N)) {
1539 for (
auto &OD : OutputDeps)
1540 if (!Added.test(OD.second)) {
1542 Added.set(OD.second);
1548 bool SwingSchedulerDAG::Circuits::circuit(
int V,
int S, NodeSetType &NodeSets,
1550 SUnit *SV = &SUnits[V];
1555 for (
auto W : AdjK[V]) {
1556 if (NumPaths > MaxPaths)
1566 }
else if (!Blocked.
test(
W)) {
1567 if (circuit(
W, S, NodeSets,
W < V ?
true : HasBackedge))
1575 for (
auto W : AdjK[V]) {
1587 void SwingSchedulerDAG::Circuits::unblock(
int U) {
1590 while (!BU.
empty()) {
1592 assert(SI != BU.
end() &&
"Invalid B set.");
1595 if (Blocked.
test(W->NodeNum))
1596 unblock(W->NodeNum);
1602 void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
1607 Circuits Cir(SUnits);
1609 Cir.createAdjacencyStructure(
this);
1610 for (
int i = 0, e = SUnits.size(); i != e; ++i) {
1612 Cir.circuit(i, i, NodeSets);
1634 void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
1635 ScheduleInfo.resize(SUnits.size());
1652 int zeroLatencyDepth = 0;
1655 EP = SU->
Preds.end();
1658 if (IP->getLatency() == 0)
1660 std::max(zeroLatencyDepth, getZeroLatencyDepth(pred) + 1);
1663 asap =
std::max(asap, (
int)(getASAP(pred) + IP->getLatency() -
1664 getDistance(pred, SU, *IP) * MII));
1667 ScheduleInfo[*
I].ASAP = asap;
1668 ScheduleInfo[*
I].ZeroLatencyDepth = zeroLatencyDepth;
1676 int zeroLatencyHeight = 0;
1679 ES = SU->
Succs.end();
1681 SUnit *succ = IS->getSUnit();
1682 if (IS->getLatency() == 0)
1684 std::max(zeroLatencyHeight, getZeroLatencyHeight(succ) + 1);
1687 alap = std::min(alap, (
int)(getALAP(succ) - IS->getLatency() +
1688 getDistance(SU, succ, *IS) * MII));
1691 ScheduleInfo[*
I].ALAP = alap;
1692 ScheduleInfo[*
I].ZeroLatencyHeight = zeroLatencyHeight;
1697 I.computeNodeSetInfo(
this);
1700 for (
unsigned i = 0; i < SUnits.size(); i++) {
1701 dbgs() <<
"\tNode " << i <<
":\n";
1702 dbgs() <<
"\t ASAP = " << getASAP(&SUnits[i]) <<
"\n";
1703 dbgs() <<
"\t ALAP = " << getALAP(&SUnits[i]) <<
"\n";
1704 dbgs() <<
"\t MOV = " << getMOV(&SUnits[i]) <<
"\n";
1705 dbgs() <<
"\t D = " << getDepth(&SUnits[i]) <<
"\n";
1706 dbgs() <<
"\t H = " << getHeight(&SUnits[i]) <<
"\n";
1707 dbgs() <<
"\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) <<
"\n";
1708 dbgs() <<
"\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) <<
"\n";
1724 if (S && S->count(PI->getSUnit()) == 0)
1728 if (NodeOrder.
count(PI->getSUnit()) == 0)
1729 Preds.
insert(PI->getSUnit());
1733 ES = (*I)->Succs.end();
1737 if (S && S->count(IS->getSUnit()) == 0)
1739 if (NodeOrder.
count(IS->getSUnit()) == 0)
1740 Preds.
insert(IS->getSUnit());
1743 return !Preds.
empty();
1757 if (S && S->count(
SI->getSUnit()) == 0)
1761 if (NodeOrder.
count(
SI->getSUnit()) == 0)
1765 PE = (*I)->Preds.end();
1769 if (S && S->count(PI->getSUnit()) == 0)
1771 if (NodeOrder.
count(PI->getSUnit()) == 0)
1772 Succs.
insert(PI->getSUnit());
1775 return !Succs.
empty();
1786 if (Exclude.
count(Cur) != 0)
1788 if (DestNodes.
count(Cur) != 0)
1790 if (!Visited.
insert(Cur).second)
1791 return Path.
count(Cur) != 0;
1792 bool FoundPath =
false;
1794 FoundPath |=
computePath(
SI.getSUnit(), Path, DestNodes, Exclude, Visited);
1795 for (
auto &PI : Cur->
Preds)
1798 computePath(PI.getSUnit(), Path, DestNodes, Exclude, Visited);
1805 template <
class S1Ty,
class S2Ty>
static bool isSubset(S1Ty &Set1, S2Ty &Set2) {
1806 for (
typename S1Ty::iterator
I = Set1.begin(), E = Set1.end();
I !=
E; ++
I)
1807 if (Set2.count(*
I) == 0)
1821 for (
SUnit *SU : NS) {
1826 if (MO.isReg() && MO.isUse()) {
1827 unsigned Reg = MO.getReg();
1835 for (
SUnit *SU : NS)
1837 if (MO.isReg() && MO.isDef() && !MO.isDead()) {
1838 unsigned Reg = MO.getReg();
1840 if (!Uses.
count(Reg))
1845 if (!Uses.
count(*Units))
1855 void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
1856 for (
auto &NS : NodeSets) {
1862 RecRPTracker.
init(&MF, &RegClassInfo, &LIS, BB, BB->end(),
false,
true);
1866 std::vector<SUnit *> SUnits(NS.begin(), NS.end());
1869 return A->
NodeNum > B->NodeNum;
1872 for (
auto &SU : SUnits) {
1878 RecRPTracker.
setPos(std::next(CurInstI));
1887 dbgs() <<
"Excess register pressure: SU(" << SU->
NodeNum <<
") " 1890 NS.setExceedPressure(SU);
1900 void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
1901 unsigned Colocate = 0;
1902 for (
int i = 0, e = NodeSets.size(); i < e; ++i) {
1905 if (N1.empty() || !
succ_L(N1, S1))
1907 for (
int j = i + 1; j < e; ++j) {
1909 if (N1.compareRecMII(N2) != 0)
1912 if (N2.empty() || !
succ_L(N2, S2))
1915 N1.setColocate(++Colocate);
1916 N2.setColocate(Colocate);
1928 void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
1933 for (
auto &NS : NodeSets) {
1934 if (NS.getRecMII() > 2)
1936 if (NS.getMaxDepth() > MII)
1946 void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
1956 for (
SUnit *NI : N) {
1965 if (
succ_L(NodesAdded, N)) {
1967 for (
SUnit *NI : N) {
1974 NodesAdded.
insert(
I.begin(),
I.end());
1981 if (
succ_L(NodesAdded, N))
1983 addConnectedNodes(
I, NewSet, NodesAdded);
1984 if (!NewSet.empty())
1985 NodeSets.push_back(NewSet);
1990 if (
pred_L(NodesAdded, N))
1992 addConnectedNodes(
I, NewSet, NodesAdded);
1993 if (!NewSet.empty())
1994 NodeSets.push_back(NewSet);
1998 for (
unsigned i = 0; i < SUnits.size(); ++i) {
1999 SUnit *SU = &SUnits[i];
2000 if (NodesAdded.
count(SU) == 0) {
2002 addConnectedNodes(SU, NewSet, NodesAdded);
2003 if (!NewSet.empty())
2004 NodeSets.push_back(NewSet);
2010 void SwingSchedulerDAG::addConnectedNodes(
SUnit *SU,
NodeSet &NewSet,
2016 if (!
SI.isArtificial() && NodesAdded.
count(Successor) == 0)
2017 addConnectedNodes(Successor, NewSet, NodesAdded);
2019 for (
auto &PI : SU->
Preds) {
2020 SUnit *Predecessor = PI.getSUnit();
2021 if (!PI.isArtificial() && NodesAdded.
count(Predecessor) == 0)
2022 addConnectedNodes(Predecessor, NewSet, NodesAdded);
2031 for (
unsigned i = 0, e = Set1.
size(); i != e; ++i) {
2032 SUnit *SU = Set1[i];
2033 if (Set2.count(SU) != 0)
2036 return !Result.
empty();
2040 void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
2041 for (NodeSetType::iterator
I = NodeSets.begin(), E = NodeSets.end();
I !=
E;
2044 for (NodeSetType::iterator J =
I + 1; J !=
E;) {
2046 if (NI.getNode(0)->NodeNum == NJ.getNode(0)->NodeNum) {
2047 if (NJ.compareRecMII(NI) > 0)
2048 NI.setRecMII(NJ.getRecMII());
2049 for (NodeSet::iterator NII = J->begin(), ENI = J->end(); NII != ENI;
2062 void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
2063 for (NodeSetType::iterator
I = NodeSets.begin(), E = NodeSets.end();
I !=
E;
2065 for (NodeSetType::iterator J =
I + 1; J !=
E;) {
2066 J->remove_if([&](
SUnit *SUJ) {
return I->count(SUJ); });
2081 void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
2085 for (
auto &Nodes : NodeSets) {
2102 }
else if (NodeSets.size() == 1) {
2103 for (
auto &N : Nodes)
2104 if (N->Succs.
size() == 0)
2110 SUnit *maxASAP =
nullptr;
2111 for (
SUnit *SU : Nodes) {
2112 if (maxASAP ==
nullptr || getASAP(SU) > getASAP(maxASAP) ||
2113 (getASAP(SU) == getASAP(maxASAP) && SU->
NodeNum > maxASAP->
NodeNum))
2121 while (!R.
empty()) {
2122 if (Order == TopDown) {
2126 while (!R.
empty()) {
2127 SUnit *maxHeight =
nullptr;
2129 if (maxHeight ==
nullptr || getHeight(
I) > getHeight(maxHeight))
2131 else if (getHeight(
I) == getHeight(maxHeight) &&
2132 getZeroLatencyHeight(
I) > getZeroLatencyHeight(maxHeight))
2134 else if (getHeight(
I) == getHeight(maxHeight) &&
2135 getZeroLatencyHeight(
I) ==
2136 getZeroLatencyHeight(maxHeight) &&
2137 getMOV(
I) < getMOV(maxHeight))
2140 NodeOrder.
insert(maxHeight);
2142 R.remove(maxHeight);
2143 for (
const auto &
I : maxHeight->
Succs) {
2144 if (Nodes.count(
I.getSUnit()) == 0)
2146 if (NodeOrder.
count(
I.getSUnit()) != 0)
2150 R.insert(
I.getSUnit());
2153 for (
const auto &
I : maxHeight->
Preds) {
2156 if (Nodes.count(
I.getSUnit()) == 0)
2158 if (NodeOrder.
count(
I.getSUnit()) != 0)
2160 R.insert(
I.getSUnit());
2166 if (
pred_L(NodeOrder, N, &Nodes))
2172 while (!R.
empty()) {
2173 SUnit *maxDepth =
nullptr;
2175 if (maxDepth ==
nullptr || getDepth(
I) > getDepth(maxDepth))
2177 else if (getDepth(
I) == getDepth(maxDepth) &&
2178 getZeroLatencyDepth(
I) > getZeroLatencyDepth(maxDepth))
2180 else if (getDepth(
I) == getDepth(maxDepth) &&
2181 getZeroLatencyDepth(
I) == getZeroLatencyDepth(maxDepth) &&
2182 getMOV(
I) < getMOV(maxDepth))
2185 NodeOrder.
insert(maxDepth);
2188 if (Nodes.isExceedSU(maxDepth)) {
2191 R.insert(Nodes.getNode(0));
2194 for (
const auto &
I : maxDepth->
Preds) {
2195 if (Nodes.count(
I.getSUnit()) == 0)
2197 if (NodeOrder.
count(
I.getSUnit()) != 0)
2199 R.insert(
I.getSUnit());
2202 for (
const auto &
I : maxDepth->
Succs) {
2205 if (Nodes.count(
I.getSUnit()) == 0)
2207 if (NodeOrder.
count(
I.getSUnit()) != 0)
2209 R.insert(
I.getSUnit());
2215 if (
succ_L(NodeOrder, N, &Nodes))
2223 dbgs() <<
"Node order: ";
2224 for (
SUnit *
I : NodeOrder)
2225 dbgs() <<
" " <<
I->NodeNum <<
" ";
2232 bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
2233 if (NodeOrder.
empty())
2236 bool scheduleFound =
false;
2238 for (
unsigned II = MII; II < MII + 10 && !scheduleFound; ++II) {
2240 Schedule.setInitiationInterval(II);
2250 int EarlyStart = INT_MIN;
2251 int LateStart = INT_MAX;
2254 int SchedEnd = INT_MAX;
2255 int SchedStart = INT_MIN;
2256 Schedule.computeStart(SU, &EarlyStart, &LateStart, &SchedEnd, &SchedStart,
2264 dbgs() <<
"\tes: " << EarlyStart <<
" ls: " << LateStart
2265 <<
" me: " << SchedEnd <<
" ms: " << SchedStart <<
"\n";
2268 if (EarlyStart > LateStart || SchedEnd < EarlyStart ||
2269 SchedStart > LateStart)
2270 scheduleFound =
false;
2271 else if (EarlyStart != INT_MIN && LateStart == INT_MAX) {
2272 SchedEnd = std::min(SchedEnd, EarlyStart + (
int)II - 1);
2273 scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2274 }
else if (EarlyStart == INT_MIN && LateStart != INT_MAX) {
2275 SchedStart =
std::max(SchedStart, LateStart - (
int)II + 1);
2276 scheduleFound = Schedule.insert(SU, LateStart, SchedStart, II);
2277 }
else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2279 std::min(SchedEnd, std::min(LateStart, EarlyStart + (
int)II - 1));
2284 scheduleFound = Schedule.insert(SU, SchedEnd, EarlyStart, II);
2286 scheduleFound = Schedule.insert(SU, EarlyStart, SchedEnd, II);
2288 int FirstCycle = Schedule.getFirstCycle();
2289 scheduleFound = Schedule.insert(SU, FirstCycle + getASAP(SU),
2290 FirstCycle + getASAP(SU) + II - 1, II);
2297 scheduleFound =
false;
2301 dbgs() <<
"\tCan't schedule\n";
2303 }
while (++NI != NE && scheduleFound);
2307 scheduleFound = Schedule.isValidSchedule(
this);
2310 LLVM_DEBUG(
dbgs() <<
"Schedule Found? " << scheduleFound <<
"\n");
2313 Schedule.finalizeSchedule(
this);
2317 return scheduleFound && Schedule.getMaxStageCount() > 0;
2325 void SwingSchedulerDAG::generatePipelinedLoop(SMSchedule &Schedule) {
2329 unsigned MaxStageCount = Schedule.getMaxStageCount();
2335 ValueMapTy *VRMap =
new ValueMapTy[(MaxStageCount + 1) * 2];
2336 InstrMapTy InstrMap;
2340 generateProlog(Schedule, MaxStageCount, KernelBB, VRMap, PrologBBs);
2341 MF.
insert(BB->getIterator(), KernelBB);
2345 for (
int Cycle = Schedule.getFirstCycle(),
2346 LastCycle = Schedule.getFinalCycle();
2347 Cycle <= LastCycle; ++Cycle) {
2348 std::deque<SUnit *> &CycleInstrs = Schedule.getInstructions(Cycle);
2350 for (
SUnit *CI : CycleInstrs) {
2351 if (CI->getInstr()->isPHI())
2353 unsigned StageNum = Schedule.stageScheduled(getSUnit(CI->getInstr()));
2354 MachineInstr *NewMI = cloneInstr(CI->getInstr(), MaxStageCount, StageNum);
2355 updateInstruction(NewMI,
false, MaxStageCount, StageNum, Schedule, VRMap);
2357 InstrMap[NewMI] = CI->getInstr();
2364 E = BB->instr_end();
2367 updateInstruction(NewMI,
false, MaxStageCount, 0, Schedule, VRMap);
2369 InstrMap[NewMI] = &*
I;
2375 generateExistingPhis(KernelBB, PrologBBs.
back(), KernelBB, KernelBB, Schedule,
2376 VRMap, InstrMap, MaxStageCount, MaxStageCount,
false);
2377 generatePhis(KernelBB, PrologBBs.
back(), KernelBB, KernelBB, Schedule, VRMap,
2378 InstrMap, MaxStageCount, MaxStageCount,
false);
2384 generateEpilog(Schedule, MaxStageCount, KernelBB, VRMap, EpilogBBs,
2389 splitLifetimes(KernelBB, EpilogBBs, Schedule);
2392 removeDeadInstructions(KernelBB, EpilogBBs);
2395 addBranches(PrologBBs, KernelBB, EpilogBBs, Schedule, VRMap);
2401 BB->eraseFromParent();
2407 void SwingSchedulerDAG::generateProlog(SMSchedule &Schedule,
unsigned LastStage,
2410 MBBVectorTy &PrologBBs) {
2412 assert(PreheaderBB !=
nullptr &&
2413 "Need to add code to handle loops w/o preheader");
2415 InstrMapTy InstrMap;
2420 for (
unsigned i = 0; i < LastStage; ++i) {
2425 MF.
insert(BB->getIterator(), NewBB);
2432 for (
int StageNum = i; StageNum >= 0; --StageNum) {
2434 BBE = BB->getFirstTerminator();
2435 BBI != BBE; ++BBI) {
2436 if (Schedule.isScheduledAtStage(getSUnit(&*BBI), (
unsigned)StageNum)) {
2440 cloneAndChangeInstr(&*BBI, i, (
unsigned)StageNum, Schedule);
2441 updateInstruction(NewMI,
false, i, (
unsigned)StageNum, Schedule,
2444 InstrMap[NewMI] = &*BBI;
2448 rewritePhiValues(NewBB, i, Schedule, VRMap, InstrMap);
2450 dbgs() <<
"prolog:\n";
2459 unsigned numBranches = TII->
removeBranch(*PreheaderBB);
2469 void SwingSchedulerDAG::generateEpilog(SMSchedule &Schedule,
unsigned LastStage,
2472 MBBVectorTy &EpilogBBs,
2473 MBBVectorTy &PrologBBs) {
2478 bool checkBranch = TII->
analyzeBranch(*KernelBB, TBB, FBB, Cond);
2479 assert(!checkBranch &&
"generateEpilog must be able to analyze the branch");
2484 if (*LoopExitI == KernelBB)
2486 assert(LoopExitI != KernelBB->
succ_end() &&
"Expecting a successor");
2491 InstrMapTy InstrMap;
2496 int EpilogStage = LastStage + 1;
2497 for (
unsigned i = LastStage; i >= 1; --i, ++EpilogStage) {
2500 MF.
insert(BB->getIterator(), NewBB);
2505 if (EpilogStart == LoopExitBB)
2506 EpilogStart = NewBB;
2510 for (
unsigned StageNum = i; StageNum <= LastStage; ++StageNum) {
2511 for (
auto &BBI : *BB) {
2515 if (Schedule.isScheduledAtStage(getSUnit(In), StageNum)) {
2519 updateInstruction(NewMI, i == 1, EpilogStage, 0, Schedule, VRMap);
2521 InstrMap[NewMI] =
In;
2525 generateExistingPhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule,
2526 VRMap, InstrMap, LastStage, EpilogStage, i == 1);
2527 generatePhis(NewBB, PrologBBs[i - 1], PredBB, KernelBB, Schedule, VRMap,
2528 InstrMap, LastStage, EpilogStage, i == 1);
2532 dbgs() <<
"epilog:\n";
2541 for (
unsigned i = 2, e =
MI.getNumOperands() + 1; i != e; i += 2) {
2553 if (EpilogBBs.size() > 0) {
2585 if (
I->getParent()->getParent() != BB)
2593 void SwingSchedulerDAG::generateExistingPhis(
2596 InstrMapTy &InstrMap,
unsigned LastStageNum,
unsigned CurStageNum,
2601 unsigned PrologStage = 0;
2602 unsigned PrevStage = 0;
2603 bool InKernel = (LastStageNum == CurStageNum);
2605 PrologStage = LastStageNum - 1;
2606 PrevStage = CurStageNum;
2608 PrologStage = LastStageNum - (CurStageNum - LastStageNum);
2609 PrevStage = LastStageNum + (CurStageNum - LastStageNum) - 1;
2613 BBE = BB->getFirstNonPHI();
2614 BBI != BBE; ++BBI) {
2615 unsigned Def = BBI->getOperand(0).getReg();
2617 unsigned InitVal = 0;
2618 unsigned LoopVal = 0;
2621 unsigned PhiOp1 = 0;
2624 unsigned PhiOp2 = LoopVal;
2625 if (VRMap[LastStageNum].
count(LoopVal))
2626 PhiOp2 = VRMap[LastStageNum][LoopVal];
2628 int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2630 Schedule.stageScheduled(getSUnit(MRI.
getVRegDef(LoopVal)));
2631 unsigned NumStages = Schedule.getStagesForReg(Def, CurStageNum);
2632 if (NumStages == 0) {
2635 unsigned NewReg = VRMap[PrevStage][LoopVal];
2636 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, 0, &*BBI,
2637 Def, InitVal, NewReg);
2638 if (VRMap[CurStageNum].
count(LoopVal))
2639 VRMap[CurStageNum][
Def] = VRMap[CurStageNum][LoopVal];
2645 unsigned MaxPhis = PrologStage + 2;
2646 if (!InKernel && (
int)PrologStage <= LoopValStage)
2647 MaxPhis =
std::max((
int)MaxPhis - (
int)LoopValStage, 1);
2648 unsigned NumPhis = std::min(NumStages, MaxPhis);
2650 unsigned NewReg = 0;
2651 unsigned AccessStage = (LoopValStage != -1) ? LoopValStage : StageScheduled;
2658 if (!InKernel && StageScheduled >= LoopValStage && AccessStage == 0 &&
2663 if (InKernel && LoopValStage != -1 && StageScheduled > LoopValStage)
2664 StageDiff = StageScheduled - LoopValStage;
2665 for (
unsigned np = 0; np < NumPhis; ++np) {
2669 if (np > PrologStage || StageScheduled >= (
int)LastStageNum)
2672 else if (PrologStage >= AccessStage + StageDiff + np &&
2673 VRMap[PrologStage - StageDiff - np].
count(LoopVal) != 0)
2674 PhiOp1 = VRMap[PrologStage - StageDiff - np][LoopVal];
2677 else if (PrologStage >= AccessStage + StageDiff + np) {
2683 while (InstOp1 && InstOp1->
isPHI() && InstOp1->
getParent() == BB) {
2684 int PhiStage = Schedule.stageScheduled(getSUnit(InstOp1));
2685 if ((
int)(PrologStage - StageDiff - np) < PhiStage + Indirects)
2690 int PhiOpStage = Schedule.stageScheduled(getSUnit(InstOp1));
2691 int StageAdj = (PhiOpStage != -1 ? PhiStage - PhiOpStage : 0);
2692 if (PhiOpStage != -1 && PrologStage - StageAdj >= Indirects + np &&
2693 VRMap[PrologStage - StageAdj - Indirects - np].
count(PhiOp1)) {
2694 PhiOp1 = VRMap[PrologStage - StageAdj - Indirects - np][PhiOp1];
2704 if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2708 bool LoopDefIsPhi = PhiInst && PhiInst->
isPHI();
2713 int StageDiffAdj = 0;
2714 if (LoopValStage != -1 && StageScheduled > LoopValStage)
2715 StageDiffAdj = StageScheduled - LoopValStage;
2718 if (np == 0 && PrevStage == LastStageNum &&
2719 (StageScheduled != 0 || LoopValStage != 0) &&
2720 VRMap[PrevStage - StageDiffAdj].
count(LoopVal))
2721 PhiOp2 = VRMap[PrevStage - StageDiffAdj][LoopVal];
2724 else if (np > 0 && PrevStage == LastStageNum &&
2725 VRMap[PrevStage - np + 1].
count(Def))
2726 PhiOp2 = VRMap[PrevStage - np + 1][
Def];
2728 else if ((
unsigned)LoopValStage + StageDiffAdj > PrologStage + 1 &&
2729 VRMap[PrevStage - StageDiffAdj - np].
count(LoopVal))
2730 PhiOp2 = VRMap[PrevStage - StageDiffAdj - np][LoopVal];
2733 else if (VRMap[PrevStage - np].
count(Def) &&
2734 (!LoopDefIsPhi || PrevStage != LastStageNum))
2735 PhiOp2 = VRMap[PrevStage - np][
Def];
2742 if (LoopDefIsPhi && (
int)(PrologStage - np) >= StageScheduled) {
2743 int LVNumStages = Schedule.getStagesForPhi(LoopVal);
2744 int StageDiff = (StageScheduled - LoopValStage);
2745 LVNumStages -= StageDiff;
2747 if (LVNumStages > (
int)np && VRMap[CurStageNum].count(LoopVal)) {
2749 unsigned ReuseStage = CurStageNum;
2750 if (Schedule.isLoopCarried(
this, *PhiInst))
2751 ReuseStage -= LVNumStages;
2754 if (VRMap[ReuseStage - np].
count(LoopVal)) {
2755 NewReg = VRMap[ReuseStage - np][LoopVal];
2757 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2758 &*BBI, Def, NewReg);
2760 VRMap[CurStageNum - np][
Def] = NewReg;
2762 if (VRMap[LastStageNum - np - 1].
count(LoopVal))
2763 PhiOp2 = VRMap[LastStageNum - np - 1][LoopVal];
2765 if (IsLast && np == NumPhis - 1)
2769 }
else if (InKernel && StageDiff > 0 &&
2770 VRMap[CurStageNum - StageDiff - np].
count(LoopVal))
2771 PhiOp2 = VRMap[CurStageNum - StageDiff - np][LoopVal];
2779 TII->
get(TargetOpcode::PHI), NewReg);
2783 InstrMap[NewPhi] = &*BBI;
2788 unsigned PrevReg = 0;
2789 if (InKernel && VRMap[PrevStage - np].
count(LoopVal))
2790 PrevReg = VRMap[PrevStage - np][LoopVal];
2791 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2792 Def, NewReg, PrevReg);
2794 if (VRMap[CurStageNum - np].
count(Def)) {
2795 unsigned R = VRMap[CurStageNum - np][
Def];
2796 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np, &*BBI,
2803 if (IsLast && np == NumPhis - 1)
2811 VRMap[CurStageNum - np][
Def] = NewReg;
2814 while (NumPhis++ < NumStages) {
2815 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, NumPhis,
2816 &*BBI, Def, NewReg, 0);
2821 if (NumStages == 0 && IsLast && VRMap[CurStageNum].
count(LoopVal))
2829 void SwingSchedulerDAG::generatePhis(
2832 InstrMapTy &InstrMap,
unsigned LastStageNum,
unsigned CurStageNum,
2836 unsigned PrologStage = 0;
2837 unsigned PrevStage = 0;
2838 unsigned StageDiff = CurStageNum - LastStageNum;
2839 bool InKernel = (StageDiff == 0);
2841 PrologStage = LastStageNum - 1;
2842 PrevStage = CurStageNum;
2844 PrologStage = LastStageNum - StageDiff;
2845 PrevStage = LastStageNum + StageDiff - 1;
2849 BBE = BB->instr_end();
2850 BBI != BBE; ++BBI) {
2851 for (
unsigned i = 0, e = BBI->getNumOperands(); i != e; ++i) {
2857 int StageScheduled = Schedule.stageScheduled(getSUnit(&*BBI));
2858 assert(StageScheduled != -1 &&
"Expecting scheduled instruction.");
2860 unsigned NumPhis = Schedule.getStagesForReg(Def, CurStageNum);
2864 if (!InKernel && NumPhis == 0 && StageScheduled == 0 &&
2867 if (!InKernel && (
unsigned)StageScheduled > PrologStage)
2870 unsigned PhiOp2 = VRMap[PrevStage][
Def];
2872 if (InstOp2->isPHI() && InstOp2->getParent() == NewBB)
2876 if (NumPhis > PrologStage + 1 - StageScheduled)
2877 NumPhis = PrologStage + 1 - StageScheduled;
2878 for (
unsigned np = 0; np < NumPhis; ++np) {
2879 unsigned PhiOp1 = VRMap[PrologStage][
Def];
2880 if (np <= PrologStage)
2881 PhiOp1 = VRMap[PrologStage - np][
Def];
2883 if (InstOp1->isPHI() && InstOp1->getParent() == KernelBB)
2885 if (InstOp1->isPHI() && InstOp1->getParent() == NewBB)
2889 PhiOp2 = VRMap[PrevStage - np][
Def];
2896 TII->
get(TargetOpcode::PHI), NewReg);
2900 InstrMap[NewPhi] = &*BBI;
2905 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2906 &*BBI, PhiOp1, NewReg);
2907 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2908 &*BBI, PhiOp2, NewReg);
2911 VRMap[PrevStage - np - 1][
Def] = NewReg;
2913 VRMap[CurStageNum - np][
Def] = NewReg;
2914 if (np == NumPhis - 1)
2915 rewriteScheduledInstr(NewBB, Schedule, InstrMap, CurStageNum, np,
2916 &*BBI, Def, NewReg);
2918 if (IsLast && np == NumPhis - 1)
2930 MBBVectorTy &EpilogBBs) {
2933 for (MBBVectorTy::reverse_iterator MBB = EpilogBBs.rbegin(),
2934 MBE = EpilogBBs.rend();
2937 ME = (*MBB)->instr_rend();
2940 if (
MI->isInlineAsm()) {
2944 bool SawStore =
false;
2947 if (!
MI->isSafeToMove(
nullptr, SawStore) && !
MI->isPHI()) {
2953 MOE =
MI->operands_end();
2954 MOI != MOE; ++MOI) {
2955 if (!MOI->isReg() || !MOI->isDef())
2957 unsigned reg = MOI->getReg();
2960 used = !MOI->isDead();
2965 unsigned realUses = 0;
2971 if (UI->getParent()->getParent() != BB) {
2983 MI++->eraseFromParent();
3014 MBBVectorTy &EpilogBBs,
3015 SMSchedule &Schedule) {
3017 for (
auto &PHI : KernelBB->
phis()) {
3018 unsigned Def = PHI.getOperand(0).getReg();
3024 if (
I->isPHI() &&
I->getParent() == KernelBB) {
3034 unsigned SplitReg = 0;
3037 if (BBJ.readsRegister(Def)) {
3039 if (SplitReg == 0) {
3042 TII->
get(TargetOpcode::COPY), SplitReg)
3045 BBJ.substituteRegister(Def, SplitReg, 0, *TRI);
3050 for (
auto &Epilog : EpilogBBs)
3051 for (
auto &
I : *Epilog)
3052 if (
I.readsRegister(Def))
3053 I.substituteRegister(Def, SplitReg, 0, *TRI);
3065 for (
unsigned i = 1, e =
MI.getNumOperands(); i != e; i += 2)
3066 if (
MI.getOperand(i + 1).getMBB() == Incoming) {
3067 MI.RemoveOperand(i + 1);
3068 MI.RemoveOperand(i);
3077 void SwingSchedulerDAG::addBranches(MBBVectorTy &PrologBBs,
3079 MBBVectorTy &EpilogBBs,
3080 SMSchedule &Schedule, ValueMapTy *VRMap) {
3081 assert(PrologBBs.size() == EpilogBBs.size() &&
"Prolog/Epilog mismatch");
3090 unsigned MaxIter = PrologBBs.
size() - 1;
3091 unsigned LC = UINT_MAX;
3092 unsigned LCMin = UINT_MAX;
3093 for (
unsigned i = 0, j = MaxIter; i <= MaxIter; ++i, --j) {
3109 if (LCMin == UINT_MAX)
3112 unsigned numAdded = 0;
3116 }
else if (j >= LCMin) {
3123 if (LastPro != LastEpi) {
3137 I != E && numAdded > 0; ++
I, --numAdded)
3138 updateInstruction(&*
I,
false, j, 0, Schedule, VRMap);
3154 if (BaseDef && BaseDef->
isPHI()) {
3172 void SwingSchedulerDAG::updateMemOperands(
MachineInstr &NewMI,
3184 if (MMO->isVolatile() || (MMO->isInvariant() && MMO->isDereferenceable()) ||
3185 (!MMO->getValue())) {
3186 NewMemRefs[Refs++] = MMO;
3191 int64_t AdjOffset = Delta * Num;
3192 NewMemRefs[Refs++] =
3199 NewMI.
setMemRefs(NewMemRefs, NewMemRefs + NumRefs);
3205 unsigned CurStageNum,
3206 unsigned InstStageNum) {
3213 if (MO.isReg() && MO.isUse())
3219 updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
3227 unsigned CurStageNum,
3228 unsigned InstStageNum,
3229 SMSchedule &Schedule) {
3232 InstrChanges.
find(getSUnit(OldMI));
3233 if (It != InstrChanges.
end()) {
3234 std::pair<unsigned, int64_t> RegAndOffset = It->second;
3235 unsigned BasePos, OffsetPos;
3239 MachineInstr *LoopDef = findDefInLoop(RegAndOffset.first);
3240 if (Schedule.stageScheduled(getSUnit(LoopDef)) > (signed)InstStageNum)
3241 NewOffset += RegAndOffset.second * (CurStageNum - InstStageNum);
3244 updateMemOperands(*NewMI, *OldMI, CurStageNum - InstStageNum);
3250 void SwingSchedulerDAG::updateInstruction(
MachineInstr *NewMI,
bool LastDef,
3251 unsigned CurStageNum,
3252 unsigned InstrStageNum,
3253 SMSchedule &Schedule,
3254 ValueMapTy *VRMap) {
3259 unsigned reg = MO.
getReg();
3265 VRMap[CurStageNum][reg] = NewReg;
3268 }
else if (MO.
isUse()) {
3271 int DefStageNum = Schedule.stageScheduled(getSUnit(Def));
3272 unsigned StageNum = CurStageNum;
3273 if (DefStageNum != -1 && (
int)InstrStageNum > DefStageNum) {
3275 unsigned StageDiff = (InstrStageNum - DefStageNum);
3277 StageNum -= StageDiff;
3279 if (VRMap[StageNum].
count(reg))
3280 MO.
setReg(VRMap[StageNum][reg]);
3288 MachineInstr *SwingSchedulerDAG::findDefInLoop(
unsigned Reg) {
3291 while (Def->
isPHI()) {
3292 if (!Visited.
insert(Def).second)
3304 unsigned SwingSchedulerDAG::getPrevMapVal(
unsigned StageNum,
unsigned PhiStage,
3305 unsigned LoopVal,
unsigned LoopStage,
3308 unsigned PrevVal = 0;
3309 if (StageNum > PhiStage) {
3311 if (PhiStage == LoopStage && VRMap[StageNum - 1].
count(LoopVal))
3313 PrevVal = VRMap[StageNum - 1][LoopVal];
3314 else if (VRMap[StageNum].
count(LoopVal))
3317 PrevVal = VRMap[StageNum][LoopVal];
3321 else if (StageNum == PhiStage + 1)
3324 else if (StageNum > PhiStage + 1 && LoopInst->
getParent() == BB)
3327 getPrevMapVal(StageNum - 1, PhiStage,
getLoopPhiReg(*LoopInst, BB),
3328 LoopStage, VRMap, BB);
3339 SMSchedule &Schedule,
3341 InstrMapTy &InstrMap) {
3342 for (
auto &PHI : BB->
phis()) {
3343 unsigned InitVal = 0;
3344 unsigned LoopVal = 0;
3346 unsigned PhiDef = PHI.getOperand(0).getReg();
3350 unsigned LoopStage =
3352 unsigned NumPhis = Schedule.getStagesForPhi(PhiDef);
3353 if (NumPhis > StageNum)
3355 for (
unsigned np = 0; np <= NumPhis; ++np) {
3357 getPrevMapVal(StageNum - np, PhiStage, LoopVal, LoopStage, VRMap, BB);
3360 rewriteScheduledInstr(NewBB, Schedule, InstrMap, StageNum - np, np, &PHI,
3369 void SwingSchedulerDAG::rewriteScheduledInstr(
3371 unsigned CurStageNum,
unsigned PhiNum,
MachineInstr *Phi,
unsigned OldReg,
3372 unsigned NewReg,
unsigned PrevReg) {
3373 bool InProlog = (CurStageNum < Schedule.getMaxStageCount());
3374 int StagePhi = Schedule.stageScheduled(getSUnit(Phi)) + PhiNum;
3385 if (UseMI->
isPHI()) {
3391 InstrMapTy::iterator OrigInstr = InstrMap.find(UseMI);
3392 assert(OrigInstr != InstrMap.end() &&
"Instruction not scheduled.");
3393 SUnit *OrigMISU = getSUnit(OrigInstr->second);
3394 int StageSched = Schedule.stageScheduled(OrigMISU);
3395 int CycleSched = Schedule.cycleScheduled(OrigMISU);
3396 unsigned ReplaceReg = 0;
3398 if (StagePhi == StageSched && Phi->
isPHI()) {
3399 int CyclePhi = Schedule.cycleScheduled(getSUnit(Phi));
3400 if (PrevReg && InProlog)
3401 ReplaceReg = PrevReg;
3402 else if (PrevReg && !Schedule.isLoopCarried(
this, *Phi) &&
3403 (CyclePhi <= CycleSched || OrigMISU->getInstr()->isPHI()))
3404 ReplaceReg = PrevReg;
3406 ReplaceReg = NewReg;
3410 if (!InProlog && StagePhi + 1 == StageSched &&
3411 !Schedule.isLoopCarried(
this, *Phi))
3412 ReplaceReg = NewReg;
3413 if (StagePhi > StageSched && Phi->
isPHI())
3414 ReplaceReg = NewReg;
3415 if (!InProlog && !Phi->
isPHI() && StagePhi < StageSched)
3416 ReplaceReg = NewReg;
3419 UseOp.
setReg(ReplaceReg);
3431 bool SwingSchedulerDAG::canUseLastOffsetValue(
MachineInstr *MI,
3433 unsigned &OffsetPos,
3439 unsigned BasePosLd, OffsetPosLd;
3447 if (!Phi || !Phi->
isPHI())
3456 if (!PrevDef || PrevDef == MI)
3462 unsigned BasePos1 = 0, OffsetPos1 = 0;
3478 BasePos = BasePosLd;
3479 OffsetPos = OffsetPosLd;
3481 Offset = StoreOffset;
3487 void SwingSchedulerDAG::applyInstrChange(
MachineInstr *MI,
3488 SMSchedule &Schedule) {
3489 SUnit *SU = getSUnit(MI);
3491 InstrChanges.
find(SU);
3492 if (It != InstrChanges.
end()) {
3493 std::pair<unsigned, int64_t> RegAndOffset = It->second;
3494 unsigned BasePos, OffsetPos;
3499 int DefStageNum = Schedule.stageScheduled(getSUnit(LoopDef));
3500 int DefCycleNum = Schedule.cycleScheduled(getSUnit(LoopDef));
3501 int BaseStageNum = Schedule.stageScheduled(SU);
3502 int BaseCycleNum = Schedule.cycleScheduled(SU);
3503 if (BaseStageNum < DefStageNum) {
3505 int OffsetDiff = DefStageNum - BaseStageNum;
3506 if (DefCycleNum < BaseCycleNum) {
3515 MISUnitMap[NewMI] = SU;
3524 bool SwingSchedulerDAG::isLoopCarriedDep(
SUnit *Source,
const SDep &Dep,
3540 assert(SI !=
nullptr && DI !=
nullptr &&
"Expecting SUnit with an MI.");
3551 unsigned DeltaS, DeltaD;
3555 unsigned BaseRegS, BaseRegD;
3556 int64_t OffsetS, OffsetD;
3562 if (BaseRegS != BaseRegD)
3568 if (!Def || !Def->
isPHI())
3570 unsigned InitVal = 0;
3571 unsigned LoopVal = 0;
3583 if (OffsetS >= OffsetD)
3584 return OffsetS + AccessSizeS > DeltaS;
3586 return OffsetD + AccessSizeD > DeltaD;
3591 void SwingSchedulerDAG::postprocessDAG() {
3592 for (
auto &M : Mutations)
3601 bool SMSchedule::insert(
SUnit *SU,
int StartCycle,
int EndCycle,
int II) {
3602 bool forward =
true;
3603 if (StartCycle > EndCycle)
3607 int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
3608 for (
int curCycle = StartCycle; curCycle != termCycle;
3609 forward ? ++curCycle : --curCycle) {
3612 Resources->clearResources();
3613 for (
int checkCycle = FirstCycle + ((curCycle - FirstCycle) % II);
3614 checkCycle <= LastCycle; checkCycle += II) {
3615 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[checkCycle];
3617 for (std::deque<SUnit *>::iterator
I = cycleInstrs.begin(),
3618 E = cycleInstrs.end();
3622 assert(Resources->canReserveResources(*(*I)->getInstr()) &&
3623 "These instructions have already been scheduled.");
3624 Resources->reserveResources(*(*I)->getInstr());
3628 Resources->canReserveResources(*SU->
getInstr())) {
3630 dbgs() <<
"\tinsert at cycle " << curCycle <<
" ";
3634 ScheduledInstrs[curCycle].push_back(SU);
3635 InstrToCycle.
insert(std::make_pair(SU, curCycle));
3636 if (curCycle > LastCycle)
3637 LastCycle = curCycle;
3638 if (curCycle < FirstCycle)
3639 FirstCycle = curCycle;
3643 dbgs() <<
"\tfailed to insert at cycle " << curCycle <<
" ";
3651 int SMSchedule::earliestCycleInChain(
const SDep &Dep) {
3655 int EarlyCycle = INT_MAX;
3656 while (!Worklist.
empty()) {
3659 if (Visited.
count(PrevSU))
3661 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(PrevSU);
3662 if (it == InstrToCycle.end())
3664 EarlyCycle = std::min(EarlyCycle, it->second);
3665 for (
const auto &PI : PrevSU->
Preds)
3674 int SMSchedule::latestCycleInChain(
const SDep &Dep) {
3678 int LateCycle = INT_MIN;
3679 while (!Worklist.
empty()) {
3682 if (Visited.
count(SuccSU))
3684 std::map<SUnit *, int>::const_iterator it = InstrToCycle.find(SuccSU);
3685 if (it == InstrToCycle.end())
3687 LateCycle =
std::max(LateCycle, it->second);
3688 for (
const auto &
SI : SuccSU->
Succs)
3700 for (
auto &P : SU->
Preds)
3701 if (DAG->isBackedge(SU, P) && P.getSUnit()->getInstr()->isPHI())
3702 for (
auto &S : P.getSUnit()->Succs)
3703 if (S.getKind() ==
SDep::Data && S.getSUnit()->getInstr()->isPHI())
3704 return P.getSUnit();
3710 void SMSchedule::computeStart(
SUnit *SU,
int *MaxEarlyStart,
int *MinLateStart,
3711 int *MinEnd,
int *MaxStart,
int II,
3712 SwingSchedulerDAG *DAG) {
3716 for (
int cycle = getFirstCycle(); cycle <= LastCycle; ++cycle) {
3719 for (
SUnit *
I : getInstructions(cycle)) {
3722 for (
unsigned i = 0, e = (
unsigned)SU->
Preds.size(); i != e; ++i) {
3725 if (!DAG->isBackedge(SU, Dep)) {
3727 DAG->getDistance(Dep.
getSUnit(), SU, Dep) * II;
3728 *MaxEarlyStart =
std::max(*MaxEarlyStart, EarlyStart);
3729 if (DAG->isLoopCarriedDep(SU, Dep,
false)) {
3730 int End = earliestCycleInChain(Dep) + (II - 1);
3731 *MinEnd = std::min(*MinEnd, End);
3735 DAG->getDistance(SU, Dep.
getSUnit(), Dep) * II;
3736 *MinLateStart = std::min(*MinLateStart, LateStart);
3744 *MinLateStart = std::min(*MinLateStart, cycle);
3746 for (
unsigned i = 0, e = (
unsigned)SU->
Succs.size(); i != e; ++i) {
3747 if (SU->
Succs[i].getSUnit() ==
I) {
3749 if (!DAG->isBackedge(SU, Dep)) {
3751 DAG->getDistance(SU, Dep.
getSUnit(), Dep) * II;
3752 *MinLateStart = std::min(*MinLateStart, LateStart);
3753 if (DAG->isLoopCarriedDep(SU, Dep)) {
3754 int Start = latestCycleInChain(Dep) + 1 - II;
3755 *MaxStart =
std::max(*MaxStart, Start);
3759 DAG->getDistance(Dep.
getSUnit(), SU, Dep) * II;
3760 *MaxEarlyStart =
std::max(*MaxEarlyStart, EarlyStart);
3771 void SMSchedule::orderDependence(SwingSchedulerDAG *SSD,
SUnit *SU,
3772 std::deque<SUnit *> &Insts) {
3774 bool OrderBeforeUse =
false;
3775 bool OrderAfterDef =
false;
3776 bool OrderBeforeDef =
false;
3777 unsigned MoveDef = 0;
3778 unsigned MoveUse = 0;
3779 int StageInst1 = stageScheduled(SU);
3782 for (std::deque<SUnit *>::iterator
I = Insts.begin(), E = Insts.end();
I !=
E;
3789 unsigned Reg = MO.
getReg();
3790 unsigned BasePos, OffsetPos;
3793 if (
unsigned NewReg = SSD->getInstrBaseReg(SU))
3796 std::tie(Reads, Writes) =
3797 (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3798 if (MO.
isDef() && Reads && stageScheduled(*
I) <= StageInst1) {
3799 OrderBeforeUse =
true;
3802 }
else if (MO.
isDef() && Reads && stageScheduled(*
I) > StageInst1) {
3804 OrderAfterDef =
true;
3806 }
else if (MO.
isUse() && Writes && stageScheduled(*
I) == StageInst1) {
3807 if (cycleScheduled(*
I) == cycleScheduled(SU) && !(*I)->isSucc(SU)) {
3808 OrderBeforeUse =
true;
3812 OrderAfterDef =
true;
3815 }
else if (MO.
isUse() && Writes && stageScheduled(*
I) > StageInst1) {
3816 OrderBeforeUse =
true;
3820 OrderAfterDef =
true;
3823 }
else if (MO.
isUse() && Writes && stageScheduled(*
I) < StageInst1) {
3825 OrderBeforeUse =
true;
3828 }
else if (MO.
isUse() && stageScheduled(*
I) == StageInst1 &&
3829 isLoopCarriedDefOfUse(SSD, (*I)->getInstr(), MO)) {
3831 OrderBeforeDef =
true;
3838 for (
auto &S : SU->
Succs) {
3839 if (S.getSUnit() != *
I)
3841 if (S.getKind() ==
SDep::Order && stageScheduled(*
I) == StageInst1) {
3842 OrderBeforeUse =
true;
3847 for (
auto &P : SU->
Preds) {
3848 if (P.getSUnit() != *
I)
3850 if (P.getKind() ==
SDep::Order && stageScheduled(*
I) == StageInst1) {
3851 OrderAfterDef =
true;
3858 if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3859 OrderBeforeUse =
false;
3864 OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3868 if (OrderBeforeUse && OrderAfterDef) {
3869 SUnit *UseSU = Insts.at(MoveUse);
3870 SUnit *DefSU = Insts.at(MoveDef);
3871 if (MoveUse > MoveDef) {
3872 Insts.erase(Insts.begin() + MoveUse);
3873 Insts.erase(Insts.begin() + MoveDef);
3875 Insts.erase(Insts.begin() + MoveDef);
3876 Insts.erase(Insts.begin() + MoveUse);
3878 orderDependence(SSD, UseSU, Insts);
3879 orderDependence(SSD, SU, Insts);
3880 orderDependence(SSD, DefSU, Insts);
3886 Insts.push_front(SU);
3888 Insts.push_back(SU);
3892 bool SMSchedule::isLoopCarried(SwingSchedulerDAG *SSD,
MachineInstr &Phi) {
3896 SUnit *DefSU = SSD->getSUnit(&Phi);
3897 unsigned DefCycle = cycleScheduled(DefSU);
3898 int DefStage = stageScheduled(DefSU);
3900 unsigned InitVal = 0;
3901 unsigned LoopVal = 0;
3906 if (UseSU->getInstr()->isPHI())
3908 unsigned LoopCycle = cycleScheduled(UseSU);
3909 int LoopStage = stageScheduled(UseSU);
3910 return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
3920 bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG *SSD,
3929 if (!isLoopCarried(SSD, *Phi))
3936 if (DMO.
getReg() == LoopReg)
3946 bool SMSchedule::isValidSchedule(SwingSchedulerDAG *SSD) {
3947 for (
int i = 0, e = SSD->SUnits.size(); i < e; ++i) {
3948 SUnit &SU = SSD->SUnits[i];
3951 int StageDef = stageScheduled(&SU);
3952 assert(StageDef != -1 &&
"Instruction should have been scheduled.");
3954 if (
SI.isAssignedRegDep())
3956 if (stageScheduled(
SI.getSUnit()) != StageDef)
3972 void SwingSchedulerDAG::checkValidNodeOrder(
const NodeSetType &Circuits)
const {
3975 typedef std::pair<SUnit *, unsigned> UnitIndex;
3976 std::vector<UnitIndex> Indices(NodeOrder.
size(), std::make_pair(
nullptr, 0));
3978 for (
unsigned i = 0, s = NodeOrder.
size(); i < s; ++i)
3979 Indices.push_back(std::make_pair(NodeOrder[i], i));
3981 auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
3982 return std::get<0>(i1) < std::get<0>(i2);
3986 llvm::sort(Indices.begin(), Indices.end(), CompareKey);
3995 for (
unsigned i = 0, s = NodeOrder.
size(); i < s; ++i) {
3996 SUnit *SU = NodeOrder[i];
3999 bool PredBefore =
false;
4000 bool SuccBefore =
false;
4009 unsigned PredIndex =
4011 std::make_pair(PredSU, 0), CompareKey));
4021 unsigned SuccIndex =
4023 std::make_pair(SuccSU, 0), CompareKey));
4035 Circuits.begin(), Circuits.end(),
4036 [SU](
const NodeSet &Circuit) {
return Circuit.count(SU); });
4041 NumNodeOrderIssues++;
4045 <<
" are scheduled before node " << SU->
NodeNum 4052 dbgs() <<
"Invalid node order found!\n";
4062 void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque<SUnit *> &Instrs) {
4063 unsigned OverlapReg = 0;
4064 unsigned NewBaseReg = 0;
4065 for (
SUnit *SU : Instrs) {
4075 InstrChanges.
find(SU);
4076 if (It != InstrChanges.
end()) {
4077 unsigned BasePos, OffsetPos;
4086 MISUnitMap[NewMI] = SU;
4096 unsigned TiedUseIdx = 0;
4111 void SMSchedule::finalizeSchedule(SwingSchedulerDAG *SSD) {
4113 for (
int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
4114 for (
int stage = 1, lastStage = getMaxStageCount(); stage <= lastStage;
4116 std::deque<SUnit *> &cycleInstrs =
4117 ScheduledInstrs[cycle + (stage * InitiationInterval)];
4118 for (std::deque<SUnit *>::reverse_iterator
I = cycleInstrs.rbegin(),
4119 E = cycleInstrs.rend();
4121 ScheduledInstrs[cycle].push_front(*
I);
4126 for (
auto &
I : InstrToCycle) {
4127 int DefStage = stageScheduled(
I.first);
4134 unsigned Reg = Op.
getReg();
4135 unsigned MaxDiff = 0;
4136 bool PhiIsSwapped =
false;
4142 SUnit *SUnitUse = SSD->getSUnit(UseMI);
4143 int UseStage = stageScheduled(SUnitUse);
4145 if (UseStage != -1 && UseStage >= DefStage)
4146 Diff = UseStage - DefStage;
4148 if (isLoopCarried(SSD, *MI))
4151 PhiIsSwapped =
true;
4155 RegToStageDiff[
Reg] = std::make_pair(MaxDiff, PhiIsSwapped);
4161 for (
int cycle = getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
4162 ScheduledInstrs.
erase(cycle);
4166 for (
int i = 0, e = SSD->SUnits.size(); i != e; ++i) {
4167 SUnit *SU = &SSD->SUnits[i];
4168 SSD->applyInstrChange(SU->
getInstr(), *
this);
4173 for (
int Cycle = getFirstCycle(), E = getFinalCycle(); Cycle <=
E; ++Cycle) {
4174 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
4175 std::deque<SUnit *> newOrderPhi;
4176 for (
unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
4177 SUnit *SU = cycleInstrs[i];
4179 newOrderPhi.push_back(SU);
4181 std::deque<SUnit *> newOrderI;
4182 for (
unsigned i = 0, e = cycleInstrs.size(); i < e; ++i) {
4183 SUnit *SU = cycleInstrs[i];
4185 orderDependence(SSD, SU, newOrderI);
4188 cycleInstrs.swap(newOrderPhi);
4189 cycleInstrs.insert(cycleInstrs.end(), newOrderI.begin(), newOrderI.end());
4190 SSD->fixupRegisterOverlaps(cycleInstrs);
4196 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 4200 for (
int cycle = getFirstCycle(); cycle <= getFinalCycle(); ++cycle) {
4202 const_sched_iterator cycleInstrs = ScheduledInstrs.
find(cycle);
4203 for (
SUnit *CI : cycleInstrs->second) {
4204 os <<
"cycle " << cycle <<
" (" << stageScheduled(CI) <<
") ";
4205 os <<
"(" << CI->
NodeNum <<
") ";
void push_back(const T &Elt)
std::vector< int >::const_reverse_iterator const_reverse_iterator
A parsed version of the target data layout string in and methods for querying it. ...
const_iterator end(StringRef path)
Get end iterator over path.
static cl::opt< bool > SwpIgnoreRecMII("pipeliner-ignore-recmii", cl::ReallyHidden, cl::init(false), cl::ZeroOrMore, cl::desc("Ignore RecMII"))
virtual void finishBlock()
Cleans up after scheduling in the given block.
mop_iterator operands_end()
A common definition of LaneBitmask for use in TableGen and CodeGen.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
instr_iterator instr_begin()
static bool pred_L(SetVector< SUnit *> &NodeOrder, SmallSetVector< SUnit *, 8 > &Preds, const NodeSet *S=nullptr)
Compute the Pred_L(O) set, as defined in the paper.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
static cl::opt< bool > SwpPruneDeps("pipeliner-prune-deps", cl::desc("Prune dependences between unrelated Phi nodes."), cl::Hidden, cl::init(true))
A command line option to disable the pruning of chain dependences due to an unrelated Phi...
static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker, NodeSet &NS)
Compute the live-out registers for the instructions in a node-set.
bool isCall(QueryType Type=AnyInBundle) const
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
instr_iterator instr_end()
MachineBasicBlock * getMBB() const
const TargetRegisterClass * getRegClass(unsigned Reg) const
Return the register class of the specified virtual register.
unsigned getRegState(const MachineOperand &RegOp)
Get all register state flags from machine operand RegOp.
void RemoveMachineInstrFromMaps(MachineInstr &MI)
bool isAllocatable(unsigned PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
Compute iterated dominance frontiers using a linear time algorithm.
const InstrStage * beginStage(unsigned ItinClassIndx) const
Return the first stage of the itinerary.
size_type size() const
Determine the number of elements in the SetVector.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
void dump(const ScheduleDAG *G) const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
unsigned getDepth() const
Returns the depth of this node, which is the length of the maximum path up to any node which has no p...
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
unsigned getReg() const
getReg - Returns the register number.
bool operator>(int64_t V1, const APSInt &V2)
static void getUnderlyingObjects(MachineInstr *MI, SmallVectorImpl< Value *> &Objs, const DataLayout &DL)
Return the underlying objects for the memory references of an instruction.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
virtual bool getIncrementValue(const MachineInstr &MI, int &Value) const
If the instruction is an increment of a constant value, return the amount.
void transferSuccessors(MachineBasicBlock *FromMBB)
Transfers all the successors from MBB to this machine basic block (i.e., copies all the successors Fr...
unsigned getSubReg() const
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
iterator_range< iterator > phis()
Returns a range that iterates over the phis in the basic block.
The two locations do not alias at all.
static cl::opt< bool > EnableSWPOptSize("enable-pipeliner-opt-size", cl::desc("Enable SWP at Os."), cl::Hidden, cl::init(false))
A command line option to enable SWP at -Os.
bool test(unsigned Idx) const
virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const
Insert branch code into the end of the specified MachineBasicBlock.
static void getPhiRegs(MachineInstr &Phi, MachineBasicBlock *Loop, unsigned &InitVal, unsigned &LoopVal)
Return the register values for the operands of a Phi instruction.
This class implements a map that also provides access to all stored values in a deterministic order...
static void dump(StringRef Title, SpillInfo const &Spills)
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
void removePred(const SDep &D)
Removes the specified edge as a pred of the current node if it exists.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
block Block Frequency true
unsigned getReg() const
Returns the register associated with this edge.
iterator_range< mmo_iterator > memoperands()
iterator_range< mop_iterator > operands()
virtual unsigned reduceLoopCount(MachineBasicBlock &MBB, MachineInstr *IndVar, MachineInstr &Cmp, SmallVectorImpl< MachineOperand > &Cond, SmallVectorImpl< MachineInstr *> &PrevInsts, unsigned Iter, unsigned MaxIter) const
Generate code to reduce the loop iteration by one and check if the loop is finished.
virtual unsigned removeBranch(MachineBasicBlock &MBB, int *BytesRemoved=nullptr) const
Remove the branching code at the end of the specific MBB.
iterator end()
Get an iterator to the end of the SetVector.
SmallVectorImpl< SDep >::iterator succ_iterator
SmallVector< SDep, 4 > Preds
All sunit predecessors.
virtual void adjustSchedDependency(SUnit *def, SUnit *use, SDep &dep) const
A register anti-dependence (aka WAR).
void recede(SmallVectorImpl< RegisterMaskPair > *LiveUses=nullptr)
Recede across the previous instruction.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
AAMDNodes getAAInfo() const
Return the AA tags for the memory reference.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
void eraseFromParent()
This method unlinks 'this' from the containing function and deletes it.
A description of a memory reference used in the backend.
static use_iterator use_end()
SmallVectorImpl< SDep >::iterator pred_iterator
static bool isDependenceBarrier(MachineInstr &MI, AliasAnalysis *AA)
Return true if the instruction causes a chain between memory references before and after it...
void closeBottom()
Set the boundary for the bottom of the region and summarize live outs.
unsigned getLatency() const
Returns the latency value for this edge, which roughly means the minimum number of cycles that must e...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
unsigned getNumOperands() const
Access to explicit operands of the instruction.
void setInstr(MachineInstr *MI)
Assigns the instruction for the SUnit.
SmallVectorImpl< SDep >::const_iterator const_pred_iterator
Modulo Software Pipelining
virtual DFAPacketizer * CreateTargetScheduleState(const TargetSubtargetInfo &) const
Create machine specific model for scheduling.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
Regular data dependence (aka true-dependence).
This file contains the simple types necessary to represent the attributes associated with functions a...
bool hasPhysRegDefs
Has physreg defs that are being used.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
void InitDAGTopologicalSorting()
Creates the initial topological ordering from the DAG to be scheduled.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, unsigned base_alignment, const AAMDNodes &AAInfo=AAMDNodes(), const MDNode *Ranges=nullptr, SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
void pop_back()
Remove the last element of the SetVector.
static constexpr LaneBitmask getNone()
static bool ignoreDependence(const SDep &D, bool isPred)
Return true for DAG nodes that we ignore when computing the cost functions.
bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
BlockT * getHeader() const
void assign(size_type NumElts, const T &Elt)
MachineInstr * getVRegDef(unsigned Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
defusechain_iterator - This class provides iterator support for machine operands in the function that...
A register output-dependence (aka WAW).
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
bool insert(const value_type &X)
Insert a new element into the SetVector.
static void swapAntiDependences(std::vector< SUnit > &SUnits)
Swap all the anti dependences in the DAG.
static bool succ_L(SetVector< SUnit *> &NodeOrder, SmallSetVector< SUnit *, 8 > &Succs, const NodeSet *S=nullptr)
Compute the Succ_L(O) set, as defined in the paper.
static bool isSubset(S1Ty &Set1, S2Ty &Set2)
Return true if Set1 is a subset of Set2.
iterator begin()
Get an iterator to the beginning of the SetVector.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Itinerary data supplied by a subtarget to be used by a target.
auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
static cl::opt< bool > EnableSWP("enable-pipeliner", cl::Hidden, cl::init(true), cl::ZeroOrMore, cl::desc("Enable Software Pipelining"))
A command line option to turn software pipelining on or off.
virtual bool getBaseAndOffsetPosition(const MachineInstr &MI, unsigned &BasePos, unsigned &OffsetPos) const
Return true if the instruction contains a base register and offset.
virtual const TargetInstrInfo * getInstrInfo() const
instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
iterator find(const KeyT &Key)
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
virtual bool areMemAccessesTriviallyDisjoint(MachineInstr &MIa, MachineInstr &MIb, AliasAnalysis *AA=nullptr) const
Sometimes, it is possible for the target to tell, even without aliasing information, that two MIs access different memory addresses.
static int getLatency(LLVMDisasmContext *DC, const MCInst &Inst)
Gets latency information for Inst, based on DC information.
bool isDereferenceableInvariantLoad(AliasAnalysis *AA) const
Return true if this load instruction never traps and points to a memory location whose value doesn't ...
const TargetRegisterClass * constrainRegClass(unsigned Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
bool isBoundaryNode() const
Boundary nodes are placeholders for the boundary of the scheduling region.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
virtual const InstrItineraryData * getInstrItineraryData() const
getInstrItineraryData - Returns instruction itinerary data for the target or specific subtarget...
TargetInstrInfo - Interface to description of machine instruction set.
AliasResult
The possible results of an alias query.
const Value * getValue() const
Return the base address of the memory access.
iterator find(const_arg_type_t< KeyT > Val)
static void removePhis(MachineBasicBlock *BB, MachineBasicBlock *Incoming)
Remove the incoming block from the Phis in a basic block.
static unsigned getInitPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB)
Return the Phi register value that comes from the incoming block.
void addLiveRegs(ArrayRef< RegisterMaskPair > Regs)
Force liveness of virtual registers or physical register units.
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
unsigned getSchedClass() const
Return the scheduling class for this instruction.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
initializer< Ty > init(const Ty &Val)
bool erase(const KeyT &Val)
reverse_iterator rbegin()
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
bool isArtificial() const
Tests if this is an Order dependence that is marked as "artificial", meaning it isn't necessary for c...
unsigned const MachineRegisterInfo * MRI
bool hasInterval(unsigned Reg) const
RegisterPressure computed within a region of instructions delimited by TopIdx and BottomIdx...
static bool hasUseAfterLoop(unsigned Reg, MachineBasicBlock *BB, MachineRegisterInfo &MRI)
Return true if the register has a use that occurs outside the specified loop.
virtual bool getMemOpBaseRegImmOfs(MachineInstr &MemOp, unsigned &BaseReg, int64_t &Offset, const TargetRegisterInfo *TRI) const
Get the base register and byte offset of an instruction that reads/writes memory. ...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
MachineInstrBuilder & UseMI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVM_NODISCARD bool empty() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE and DBG_LABEL instructions...
static int64_t computeDelta(SectionEntry *A, SectionEntry *B)
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static bool isIntersect(SmallSetVector< SUnit *, 8 > &Set1, const NodeSet &Set2, SmallSetVector< SUnit *, 8 > &Result)
Return true if Set1 contains elements in Set2.
void setMBB(MachineBasicBlock *MBB)
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
use_instr_iterator use_instr_begin(unsigned RegNo) const
bool hasOneMemOperand() const
Return true if this instruction has exactly one MachineMemOperand.
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Track the current register pressure at some position in the instruction stream, and remember the high...
void setImm(int64_t immVal)
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
void RemovePred(SUnit *M, SUnit *N)
Updates the topological ordering to accommodate an an edge to be removed from the specified node N fr...
void runOnMachineFunction(const MachineFunction &MF)
runOnFunction - Prepare to answer questions about MF.
void print(raw_ostream &OS, bool IsStandalone=true, bool SkipOpers=false, bool SkipDebugLoc=false, bool AddNewLine=true, const TargetInstrInfo *TII=nullptr) const
Print this MI to OS.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
succ_iterator succ_begin()
void DeleteMachineInstr(MachineInstr *MI)
DeleteMachineInstr - Delete the given MachineInstr.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
virtual bool analyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl< MachineOperand > &Cond, bool AllowModify=false) const
Analyze the branching code at the end of MBB, returning true if it cannot be understood (e...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Any other ordering dependency.
INITIALIZE_PASS_BEGIN(MachinePipeliner, DEBUG_TYPE, "Modulo Software Pipelining", false, false) INITIALIZE_PASS_END(MachinePipeliner
typename vector_type::const_iterator const_iterator
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void sort(IteratorTy Start, IteratorTy End)
static void replaceRegUsesAfterLoop(unsigned FromReg, unsigned ToReg, MachineBasicBlock *MBB, MachineRegisterInfo &MRI, LiveIntervals &LIS)
Replace all uses of FromReg that appear outside the specified basic block with ToReg.
An unknown scheduling barrier.
Representation for a specific memory location.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
std::vector< unsigned > MaxSetPressure
Map of max reg pressure indexed by pressure set ID, not class ID.
typename vector_type::const_iterator iterator
A SetVector that performs no allocations if smaller than a certain size.
print lazy value Lazy Value Info Printer Pass
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
unsigned countPopulation(T Value)
Count the number of set bits in a value.
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
reverse_instr_iterator instr_rbegin()
static cl::opt< int > SwpLoopLimit("pipeliner-max", cl::Hidden, cl::init(-1))
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
void dropMemRefs()
Clear this MachineInstr's memory reference descriptor list.
MachineInstr * CloneMachineInstr(const MachineInstr *Orig)
Create a new MachineInstr which is a copy of Orig, identical in all ways except the instruction has n...
static cl::opt< int > SwpMaxStages("pipeliner-max-stages", cl::desc("Maximum stages allowed in the generated scheduled."), cl::Hidden, cl::init(3))
A command line argument to limit the number of stages in the pipeline.
MachineOperand class - Representation of each machine instruction operand.
static cl::opt< int > SwpMaxMii("pipeliner-max-mii", cl::desc("Size limit for the MII."), cl::Hidden, cl::init(27))
A command line argument to limit minimum initial interval for pipelining.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
MachineInstrBuilder MachineInstrBuilder & DefMI
bool canReserveResources(const MCInstrDesc *MID)
char & MachinePipelinerID
This pass performs software pipelining on machine instructions.
LLVM_NODISCARD T pop_back_val()
bool hasOrderedMemoryRef() const
Return true if this instruction may have an ordered or volatile memory reference, or if the informati...
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
MachineInstr * getUniqueVRegDef(unsigned Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static bool isSuccOrder(SUnit *SUa, SUnit *SUb)
Return true if SUb can be reached from SUa following the chain edges.
reverse_instr_iterator instr_rend()
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
std::vector< int >::const_iterator const_iterator
void clear()
Completely clear the SetVector.
bool IsReachable(const SUnit *SU, const SUnit *TargetSU)
Checks if SU is reachable from TargetSU.
static SUnit * multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG)
If an instruction has a use that spans multiple iterations, then return true.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
typename SuperClass::iterator iterator
void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
SmallVectorImpl< SDep >::const_iterator const_succ_iterator
LiveInterval & createEmptyInterval(unsigned Reg)
Interval creation.
static void clear(coro::Shape &Shape)
void setLatency(unsigned Lat)
Sets the latency for this edge.
const MachineBasicBlock * getParent() const
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
void initializeMachinePipelinerPass(PassRegistry &)
TargetSubtargetInfo - Generic base class for all target subtargets.
std::set< NodeId > NodeSet
unsigned getHeight() const
Returns the height of this node, which is the length of the maximum path down to any node which has n...
bool operator!=(uint64_t V1, const APInt &V2)
A ScheduleDAG for scheduling lists of MachineInstr.
Representation of each machine instruction.
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
virtual bool analyzeLoop(MachineLoop &L, MachineInstr *&IndVarInst, MachineInstr *&CmpInst) const
Analyze the loop code, return true if it cannot be understoo.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
use_iterator use_begin(unsigned RegNo) const
LLVM_NODISCARD bool empty() const
These values represent a non-pipelined step in the execution of an instruction.
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
This file provides utility analysis objects describing memory locations.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode...
void setReg(unsigned Reg)
Change the register this operand corresponds to.
const InstrStage * endStage(unsigned ItinClassIndx) const
Return the last+1 stage of the itinerary.
void push_back(MachineInstr *MI)
bool empty() const
Determine if the SetVector is empty or not.
void setSubReg(unsigned subReg)
bool isZeroCost(unsigned Opcode) const
Return true for pseudo instructions that don't consume any machine resources in their current form...
void getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit)
Consider the pressure increase caused by traversing this instruction bottom-up.
iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const MachineInstrBuilder & addReg(unsigned RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Kind getKind() const
Returns an enum value representing the kind of the dependence.
bool isRegTiedToUseOperand(unsigned DefOpIdx, unsigned *UseOpIdx=nullptr) const
Given the index of a register def operand, check if the register def is tied to a source operand...
void removeSuccessor(MachineBasicBlock *Succ, bool NormalizeSuccProbs=false)
Remove successor from the successors list of this MachineBasicBlock.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void init(const MachineFunction *mf, const RegisterClassInfo *rci, const LiveIntervals *lis, const MachineBasicBlock *mbb, MachineBasicBlock::const_iterator pos, bool TrackLaneMasks, bool TrackUntiedDefs)
Setup the RegPressureTracker.
unsigned NodeNum
Entry # of node in the node vector.
void GetUnderlyingObjects(Value *V, SmallVectorImpl< Value *> &Objects, const DataLayout &DL, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to GetUnderlyingObject except that it can look through phi and select instruct...
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
Store the effects of a change in pressure on things that MI scheduler cares about.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void insert(iterator MBBI, MachineBasicBlock *MBB)
bool addPred(const SDep &D, bool Required=true)
Adds the specified edge as a pred of the current node if not already.
int64_t getOffset() const
For normal values, this is a byte offset added to the base address.
LLVM Value Representation.
mop_iterator operands_begin()
A vector that has set insertion semantics.
static use_instr_iterator use_instr_end()
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
SmallVector< SDep, 4 > Succs
All sunit successors.
bool remove_if(UnaryPredicate P)
Remove items from the set vector based on a predicate function.
This class implements an extremely fast bulk output stream that can only output to a stream...
static cl::opt< bool > SwpPruneLoopCarried("pipeliner-prune-loop-carried", cl::desc("Prune loop carried order dependences."), cl::Hidden, cl::init(true))
A command line option to disable the pruning of loop carried order dependences.
bool hasUnmodeledSideEffects() const
Return true if this instruction has side effects that are not modeled by mayLoad / mayStore...
virtual bool isPostIncrement(const MachineInstr &MI) const
Return true for post-incremented instructions.
void setPos(MachineBasicBlock::const_iterator Pos)
bool operator==(uint64_t V1, const APInt &V2)
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned char TargetFlags=0) const
static bool computePath(SUnit *Cur, SetVector< SUnit *> &Path, SetVector< SUnit *> &DestNodes, SetVector< SUnit *> &Exclude, SmallPtrSet< SUnit *, 8 > &Visited)
Return true if there is a path from the specified node to any of the nodes in DestNodes.
PriorityQueue - This class behaves like std::priority_queue and provides a few additional convenience...
This class can compute a topological ordering for SUnits and provides methods for dynamically updatin...
const MachineOperand & getOperand(unsigned i) const
reg_begin/reg_end - Provide iteration support to walk over all definitions and uses of a register wit...
static unsigned getLoopPhiReg(MachineInstr &Phi, MachineBasicBlock *LoopBB)
Return the Phi register value that comes the loop block.
MachineInstr::mmo_iterator allocateMemRefsArray(unsigned long Num)
allocateMemRefsArray - Allocate an array to hold MachineMemOperand pointers.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
void setMemRefs(mmo_iterator NewMemRefs, mmo_iterator NewMemRefsEnd)
Assign this MachineInstr's memory reference descriptor list.
std::vector< MachineBasicBlock * >::iterator succ_iterator
unsigned createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
Scheduling unit. This is a node in the scheduling DAG.
mmo_iterator memoperands_end() const
void reserveResources(const MCInstrDesc *MID)
void tieOperands(unsigned DefIdx, unsigned UseIdx)
Add a tie between the register operands at DefIdx and UseIdx.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
bool isPred(const SUnit *N) const
Tests if node N is a predecessor of this node.