73#include "llvm/Config/llvm-config.h"
101#define DEBUG_TYPE "pipeliner"
103STATISTIC(NumTrytoPipeline,
"Number of loops that we attempt to pipeline");
104STATISTIC(NumPipelined,
"Number of loops software pipelined");
105STATISTIC(NumNodeOrderIssues,
"Number of node order issues found");
106STATISTIC(NumFailBranch,
"Pipeliner abort due to unknown branch");
107STATISTIC(NumFailLoop,
"Pipeliner abort due to unsupported loop");
108STATISTIC(NumFailPreheader,
"Pipeliner abort due to missing preheader");
109STATISTIC(NumFailLargeMaxMII,
"Pipeliner abort due to MaxMII too large");
110STATISTIC(NumFailZeroMII,
"Pipeliner abort due to zero MII");
111STATISTIC(NumFailNoSchedule,
"Pipeliner abort due to no schedule found");
112STATISTIC(NumFailZeroStage,
"Pipeliner abort due to zero stage");
113STATISTIC(NumFailLargeMaxStage,
"Pipeliner abort due to too many stages");
114STATISTIC(NumFailTooManyStores,
"Pipeliner abort due to too many stores");
116unsigned SwingSchedulerDAG::Circuits::MaxPaths = 5;
121 "Modulo Software Pipelining",
false,
false)
163 enum class InstrTag {
172 TaggedSUnit(
SUnit *SU, InstrTag Tag)
175 InstrTag
getTag()
const {
return InstrTag(getInt()); }
180 struct NoBarrierInstsChunk {
190 std::vector<SUnit> &SUnits;
196 std::vector<BitVector> LoopCarried;
209 std::vector<TaggedSUnit> TaggedSUnits;
221 return LoopCarried[Idx];
226 std::optional<InstrTag> getInstrTag(
SUnit *SU)
const;
228 void addLoopCarriedDepenenciesForChunks(
const NoBarrierInstsChunk &From,
229 const NoBarrierInstsChunk &To);
236 void computeDependenciesAux();
238 void setLoopCarriedDep(
const SUnit *Src,
const SUnit *Dst) {
239 LoopCarried[Src->NodeNum].set(Dst->NodeNum);
293 bool useSwingModuloScheduler();
294 bool useWindowScheduler(
bool Changed);
300int MachinePipelinerImpl::NumTries = 0;
314 for (
const auto &L : *
MLI)
341 MachinePipelinerImpl MP(MF, GetMLI(), LIS, GetAA(), GetORE(), GetRCI(),
370 return MDTWrapper ? &MDTWrapper->getDomTree() :
nullptr;
412bool MachinePipelinerImpl::scheduleLoop(
MachineLoop &L) {
414 for (
const auto &InnerLoop : L)
415 Changed |= scheduleLoop(*InnerLoop);
419 int Limit =
Opts.pipeliner_max;
427 setPragmaPipelineOptions(L);
428 if (!canPipelineLoop(L)) {
432 L.getStartLoc(), L.getHeader())
433 <<
"Failed to pipeline loop";
436 LI.LoopPipelinerInfo.reset();
441 if (useSwingModuloScheduler())
442 Changed = swingModuloScheduler(L);
444 if (useWindowScheduler(
Changed))
445 Changed = runWindowScheduler(L);
447#ifdef EXPENSIVE_CHECKS
449 "Dominator tree not updated for the pipelined loop");
452 LI.LoopPipelinerInfo.reset();
456void MachinePipelinerImpl::setPragmaPipelineOptions(MachineLoop &L) {
461 MachineBasicBlock *LBLK =
L.getTopBlock();
471 MDNode *LoopID = TI->
getMetadata(LLVMContext::MD_loop);
472 if (LoopID ==
nullptr)
489 if (S->
getString() ==
"llvm.loop.pipeline.initiationinterval") {
491 "Pipeline initiation interval hint metadata should have two operands.");
495 }
else if (S->
getString() ==
"llvm.loop.pipeline.disable") {
508 auto It = PhiDeps.find(
Reg);
509 if (It == PhiDeps.end())
520 for (
unsigned Dep : It->second) {
535 unsigned DefReg =
MI.getOperand(0).getReg();
539 for (
unsigned I = 1;
I <
MI.getNumOperands();
I += 2)
540 Ins->second.push_back(
MI.getOperand(
I).getReg());
547 for (
const auto &KV : PhiDeps) {
548 unsigned Reg = KV.first;
559bool MachinePipelinerImpl::canPipelineLoop(MachineLoop &L) {
560 if (
L.getNumBlocks() != 1) {
562 return MachineOptimizationRemarkAnalysis(
DEBUG_TYPE,
"canPipelineLoop",
563 L.getStartLoc(),
L.getHeader())
564 <<
"Not a single basic block: "
565 <<
ore::NV(
"NumBlocks",
L.getNumBlocks());
577 return MachineOptimizationRemarkAnalysis(
DEBUG_TYPE,
"canPipelineLoop",
578 L.getStartLoc(),
L.getHeader())
579 <<
"Disabled by Pragma.";
589 if (
TII->analyzeBranch(*
L.getHeader(),
LI.TBB,
LI.FBB,
LI.BrCond)) {
590 LLVM_DEBUG(
dbgs() <<
"Unable to analyzeBranch, can NOT pipeline Loop\n");
593 return MachineOptimizationRemarkAnalysis(
DEBUG_TYPE,
"canPipelineLoop",
594 L.getStartLoc(),
L.getHeader())
595 <<
"The branch can't be understood";
600 LI.LoopInductionVar =
nullptr;
601 LI.LoopCompare =
nullptr;
602 LI.LoopPipelinerInfo =
TII->analyzeLoopForPipelining(
L.getTopBlock());
603 if (!
LI.LoopPipelinerInfo) {
604 LLVM_DEBUG(
dbgs() <<
"Unable to analyzeLoop, can NOT pipeline Loop\n");
607 return MachineOptimizationRemarkAnalysis(
DEBUG_TYPE,
"canPipelineLoop",
608 L.getStartLoc(),
L.getHeader())
609 <<
"The loop structure is not supported";
614 if (!
L.getLoopPreheader()) {
615 LLVM_DEBUG(
dbgs() <<
"Preheader not found, can NOT pipeline Loop\n");
618 return MachineOptimizationRemarkAnalysis(
DEBUG_TYPE,
"canPipelineLoop",
619 L.getStartLoc(),
L.getHeader())
620 <<
"No loop preheader found";
625 unsigned NumStores = 0;
626 for (MachineInstr &
MI : *
L.getHeader())
629 if (NumStores >
Opts.pipeliner_max_num_stores) {
631 NumFailTooManyStores++;
633 return MachineOptimizationRemarkAnalysis(
DEBUG_TYPE,
"canPipelineLoop",
634 L.getStartLoc(),
L.getHeader())
635 <<
"Too many store instructions in the loop: "
636 <<
ore::NV(
"NumStores", NumStores) <<
" > "
637 <<
ore::NV(
"SwpMaxNumStores",
Opts.pipeliner_max_num_stores)
644 preprocessPhiNodes(*
L.getHeader());
648void MachinePipelinerImpl::preprocessPhiNodes(MachineBasicBlock &
B) {
649 MachineRegisterInfo &
MRI =
MF->getRegInfo();
650 SlotIndexes &Slots = *
LIS->getSlotIndexes();
652 for (MachineInstr &PI :
B.phis()) {
653 MachineOperand &DefOp = PI.getOperand(0);
657 for (
unsigned i = 1, n = PI.getNumOperands(); i != n; i += 2) {
658 MachineOperand &RegOp = PI.getOperand(i);
665 MachineBasicBlock &PredB = *PI.getOperand(i+1).getMBB();
682bool MachinePipelinerImpl::swingModuloScheduler(MachineLoop &L) {
683 assert(
L.getBlocks().size() == 1 &&
"SMS works on single blocks only.");
686 LI.LoopPipelinerInfo.get(),
AA,
MDT);
688 MachineBasicBlock *
MBB =
L.getHeader();
706 return SMS.hasNewSchedule();
722bool MachinePipelinerImpl::runWindowScheduler(
MachineLoop &L) {
734bool MachinePipelinerImpl::useSwingModuloScheduler() {
739bool MachinePipelinerImpl::useWindowScheduler(
bool Changed) {
746 "llvm.loop.pipeline.initiationinterval is set.\n");
750 return Opts.window_sched == WindowSchedulingFlag::Force ||
751 (
Opts.window_sched == WindowSchedulingFlag::On && !
Changed);
754void SwingSchedulerDAG::setMII(
unsigned ResMII,
unsigned RecMII) {
755 if (Opts.pipeliner_force_ii > 0)
756 MII = Opts.pipeliner_force_ii;
757 else if (II_setByPragma > 0)
758 MII = II_setByPragma;
760 MII = std::max(ResMII, RecMII);
763void SwingSchedulerDAG::setMAX_II() {
764 if (Opts.pipeliner_force_ii > 0)
765 MAX_II = Opts.pipeliner_force_ii;
766 else if (II_setByPragma > 0)
767 MAX_II = II_setByPragma;
769 MAX_II = MII + Opts.pipeliner_ii_search_range;
781 RegClassInfo(rci), II_setByPragma(
II), LoopPipelinerInfo(PLI),
784 MF.getSubtarget().getSMSMutations(Mutations);
785 if (
Opts.pipeliner_enable_copytophi)
786 Mutations.push_back(std::make_unique<CopyToPhiMutation>());
787 BAA.enableCrossIterationMode();
795 updatePhiDependences();
796 Topo.InitDAGTopologicalSorting();
802 dbgs() <<
"===== Loop Carried Edges Begin =====\n";
805 dbgs() <<
"===== Loop Carried Edges End =====\n";
808 NodeSetType NodeSets;
809 findCircuits(NodeSets);
810 NodeSetType Circuits = NodeSets;
813 unsigned ResMII = calculateResMII();
814 unsigned RecMII = calculateRecMII(NodeSets);
819 if (
Opts.pipeliner_ignore_recmii)
822 setMII(ResMII, RecMII);
826 <<
" (rec=" << RecMII <<
", res=" << ResMII <<
")\n");
834 DEBUG_TYPE,
"schedule", Loop.getStartLoc(), Loop.getHeader())
835 <<
"Invalid Minimal Initiation Interval: 0";
841 if (
Opts.pipeliner_max_mii != -1 && (
int)MII >
Opts.pipeliner_max_mii) {
843 <<
", we don't pipeline large loops\n");
844 NumFailLargeMaxMII++;
847 DEBUG_TYPE,
"schedule", Loop.getStartLoc(), Loop.getHeader())
848 <<
"Minimal Initiation Interval too large: "
849 <<
ore::NV(
"MII", (
int)MII) <<
" > "
850 <<
ore::NV(
"SwpMaxMii",
Opts.pipeliner_max_mii) <<
"."
851 <<
"Refer to -pipeliner-max-mii.";
856 computeNodeFunctions(NodeSets);
858 registerPressureFilter(NodeSets);
860 colocateNodeSets(NodeSets);
862 checkNodeSets(NodeSets);
865 for (
auto &
I : NodeSets) {
866 dbgs() <<
" Rec NodeSet ";
873 groupRemainingNodes(NodeSets);
875 removeDuplicateNodes(NodeSets);
878 for (
auto &
I : NodeSets) {
879 dbgs() <<
" NodeSet ";
884 computeNodeOrder(NodeSets);
887 checkValidNodeOrder(Circuits);
890 Scheduled = schedulePipeline(Schedule);
897 DEBUG_TYPE,
"schedule", Loop.getStartLoc(), Loop.getHeader())
898 <<
"Unable to find schedule";
905 if (numStages == 0) {
910 DEBUG_TYPE,
"schedule", Loop.getStartLoc(), Loop.getHeader())
911 <<
"No need to pipeline - no overlapped iterations in schedule.";
916 if (
Opts.pipeliner_max_stages > -1 &&
917 (
int)numStages >
Opts.pipeliner_max_stages) {
919 <<
Opts.pipeliner_max_stages
920 <<
" : too many stages, abort\n");
921 NumFailLargeMaxStage++;
924 DEBUG_TYPE,
"schedule", Loop.getStartLoc(), Loop.getHeader())
925 <<
"Too many stages in schedule: "
926 <<
ore::NV(
"numStages", (
int)numStages) <<
" > "
927 <<
ore::NV(
"SwpMaxStages",
Opts.pipeliner_max_stages)
928 <<
". Refer to -pipeliner-max-stages.";
936 <<
"Pipelined succesfully!";
941 std::vector<MachineInstr *> OrderedInsts;
945 OrderedInsts.push_back(SU->getInstr());
946 Cycles[SU->getInstr()] = Cycle;
951 for (
auto &KV : NewMIs) {
952 Cycles[KV.first] = Cycles[KV.second];
953 Stages[KV.first] = Stages[KV.second];
954 NewInstrChanges[KV.first] = InstrChanges[
getSUnit(KV.first)];
959 if (
Opts.pipeliner_annotate_for_testing) {
961 "Cannot serialize a schedule with InstrChanges!");
967 if (
Opts.pipeliner_experimental_cg && NewInstrChanges.
empty()) {
970 }
else if (
Opts.pipeliner_mve_cg && NewInstrChanges.
empty() &&
971 LoopPipelinerInfo->isMVEExpanderSupported() &&
985 for (
auto &KV : NewMIs)
986 MF.deleteMachineInstr(KV.second);
997 assert(Phi.isPHI() &&
"Expecting a Phi.");
1001 for (
unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
1002 if (Phi.getOperand(i + 1).getMBB() !=
Loop)
1003 InitVal = Phi.getOperand(i).getReg();
1005 LoopVal = Phi.getOperand(i).getReg();
1007 assert(InitVal && LoopVal &&
"Unexpected Phi structure.");
1013 for (
unsigned i = 1, e = Phi.getNumOperands(); i != e; i += 2)
1014 if (Phi.getOperand(i + 1).getMBB() == LoopBB)
1015 return Phi.getOperand(i).getReg();
1024 while (!Worklist.
empty()) {
1026 for (
const auto &
SI : SU->
Succs) {
1027 SUnit *SuccSU =
SI.getSUnit();
1029 if (Visited.
count(SuccSU))
1042 if (!getUnderlyingObjects())
1067bool SUnitWithMemInfo::getUnderlyingObjects() {
1069 if (!
MI->hasOneMemOperand())
1087 const SUnitWithMemInfo &Dst,
1090 if (Src.isTriviallyDisjoint(Dst))
1106 if (Src.isUnknown() || Dst.isUnknown())
1108 if (Src.MemOpValue == Dst.MemOpValue && Src.MemOpOffset <= Dst.MemOpOffset)
1119 for (
const Value *SrcObj : Src.UnderlyingObjs)
1120 for (
const Value *DstObj : Dst.UnderlyingObjs)
1128void LoopCarriedOrderDepsTracker::NoBarrierInstsChunk::append(SUnit *SU) {
1131 Stores.emplace_back(SU);
1132 else if (
MI->mayLoad())
1133 Loads.emplace_back(SU);
1134 else if (
MI->mayRaiseFPException())
1135 FPExceptions.emplace_back(SU);
1142 : DAG(SSD), BAA(BAA), SUnits(DAG->SUnits), N(SUnits.
size()),
1143 LoopCarried(N,
BitVector(N)), TII(TII) {}
1147 for (
auto &SU : SUnits) {
1148 auto Tagged = getInstrTag(&SU);
1153 TaggedSUnits.emplace_back(&SU, *Tagged);
1156 computeDependenciesAux();
1159std::optional<LoopCarriedOrderDepsTracker::InstrTag>
1160LoopCarriedOrderDepsTracker::getInstrTag(
SUnit *SU)
const {
1162 if (
TII->isGlobalMemoryObject(
MI))
1163 return InstrTag::Barrier;
1165 if (
MI->mayStore() ||
1166 (
MI->mayLoad() && !
MI->isDereferenceableInvariantLoad()))
1167 return InstrTag::LoadOrStore;
1169 if (
MI->mayRaiseFPException())
1170 return InstrTag::FPExceptions;
1172 return std::nullopt;
1175void LoopCarriedOrderDepsTracker::addDependenciesBetweenSUs(
1176 const SUnitWithMemInfo &Src,
const SUnitWithMemInfo &Dst) {
1178 if (Src.SU == Dst.SU)
1182 setLoopCarriedDep(Src.SU, Dst.SU);
1185void LoopCarriedOrderDepsTracker::addLoopCarriedDepenenciesForChunks(
1186 const NoBarrierInstsChunk &From,
const NoBarrierInstsChunk &To) {
1188 for (
const SUnitWithMemInfo &Src : From.Loads)
1189 for (
const SUnitWithMemInfo &Dst : To.Stores)
1190 addDependenciesBetweenSUs(Src, Dst);
1193 for (
const SUnitWithMemInfo &Src : From.Stores)
1194 for (
const SUnitWithMemInfo &Dst : To.Loads)
1195 addDependenciesBetweenSUs(Src, Dst);
1198 for (
const SUnitWithMemInfo &Src : From.Stores)
1199 for (
const SUnitWithMemInfo &Dst : To.Stores)
1200 addDependenciesBetweenSUs(Src, Dst);
1203void LoopCarriedOrderDepsTracker::computeDependenciesAux() {
1205 SUnit *FirstBarrier =
nullptr;
1206 SUnit *LastBarrier =
nullptr;
1207 for (
const auto &TSU : TaggedSUnits) {
1208 InstrTag
Tag = TSU.getTag();
1209 SUnit *SU = TSU.getPointer();
1211 case InstrTag::Barrier:
1215 Chunks.emplace_back();
1217 case InstrTag::LoadOrStore:
1218 case InstrTag::FPExceptions:
1219 Chunks.back().append(SU);
1227 for (
const NoBarrierInstsChunk &Chunk : Chunks)
1228 addLoopCarriedDepenenciesForChunks(Chunk, Chunk);
1257 assert(LastBarrier &&
"Both barriers should be set.");
1260 for (
const SUnitWithMemInfo &Dst : Chunks.front().Loads)
1261 setLoopCarriedDep(LastBarrier, Dst.SU);
1262 for (
const SUnitWithMemInfo &Dst : Chunks.front().Stores)
1263 setLoopCarriedDep(LastBarrier, Dst.SU);
1264 for (
const SUnitWithMemInfo &Dst : Chunks.front().FPExceptions)
1265 setLoopCarriedDep(LastBarrier, Dst.SU);
1268 for (
const SUnitWithMemInfo &Src : Chunks.back().Loads)
1269 setLoopCarriedDep(Src.SU, FirstBarrier);
1270 for (
const SUnitWithMemInfo &Src : Chunks.back().Stores)
1271 setLoopCarriedDep(Src.SU, FirstBarrier);
1272 for (
const SUnitWithMemInfo &Src : Chunks.back().FPExceptions)
1273 setLoopCarriedDep(Src.SU, FirstBarrier);
1276 if (FirstBarrier != LastBarrier)
1277 setLoopCarriedDep(LastBarrier, FirstBarrier);
1286LoopCarriedEdges SwingSchedulerDAG::addLoopCarriedDependences() {
1287 LoopCarriedEdges LCE;
1291 LCODTracker.computeDependencies();
1292 for (
unsigned I = 0;
I != SUnits.size();
I++)
1293 for (
const int Succ : LCODTracker.getLoopCarried(
I).set_bits())
1306void SwingSchedulerDAG::updatePhiDependences() {
1308 const TargetSubtargetInfo &
ST = MF.
getSubtarget<TargetSubtargetInfo>();
1311 for (SUnit &
I : SUnits) {
1316 MachineInstr *
MI =
I.getInstr();
1318 for (
const MachineOperand &MO :
MI->operands()) {
1331 MachineInstr *
UseMI = &*UI;
1332 SUnit *SU = getSUnit(
UseMI);
1358 }
else if (MO.isUse()) {
1361 if (
DefMI ==
nullptr)
1363 SUnit *SU = getSUnit(
DefMI);
1368 ST.adjustSchedDependency(SU, 0, &
I, MO.getOperandNo(), Dep,
1375 if (SU->
NodeNum <
I.NodeNum && !
I.isPred(SU))
1382 if (!Opts.pipeliner_prune_deps)
1384 for (
auto &PI :
I.Preds) {
1385 MachineInstr *PMI = PI.getSUnit()->getInstr();
1387 if (
I.getInstr()->isPHI()) {
1396 for (
const SDep &
D : RemoveDeps)
1403void SwingSchedulerDAG::changeDependences() {
1407 for (SUnit &
I : SUnits) {
1408 unsigned BasePos = 0, OffsetPos = 0;
1410 int64_t NewOffset = 0;
1411 if (!canUseLastOffsetValue(
I.getInstr(), BasePos, OffsetPos, NewBase,
1416 Register OrigBase =
I.getInstr()->getOperand(BasePos).getReg();
1420 SUnit *DefSU = getSUnit(
DefMI);
1427 SUnit *LastSU = getSUnit(LastMI);
1431 if (Topo.IsReachable(&
I, LastSU))
1436 for (
const SDep &
P :
I.Preds)
1437 if (
P.getSUnit() == DefSU)
1439 for (
const SDep &
D : Deps) {
1440 Topo.RemovePred(&
I,
D.getSUnit());
1445 for (
auto &
P : LastSU->
Preds)
1448 for (
const SDep &
D : Deps) {
1449 Topo.RemovePred(LastSU,
D.getSUnit());
1456 Topo.AddPred(LastSU, &
I);
1461 InstrChanges[&
I] = std::make_pair(NewBase, NewOffset);
1472 std::vector<MachineInstr *> &OrderedInsts,
1480 Stage <= LastStage; ++Stage) {
1483 Instrs[Cycle].push_front(SU);
1490 std::deque<SUnit *> &CycleInstrs = Instrs[Cycle];
1492 for (
SUnit *SU : CycleInstrs) {
1494 OrderedInsts.push_back(
MI);
1504struct FuncUnitSorter {
1505 const InstrItineraryData *InstrItins;
1506 const MCSubtargetInfo *STI;
1507 DenseMap<InstrStage::FuncUnits, unsigned>
Resources;
1509 FuncUnitSorter(
const TargetSubtargetInfo &TSI)
1510 : InstrItins(TSI.getInstrItineraryData()), STI(&TSI) {}
1515 unsigned minFuncUnits(
const MachineInstr *Inst,
1518 unsigned min = UINT_MAX;
1519 if (InstrItins && !InstrItins->
isEmpty()) {
1520 for (
const InstrStage &IS :
1522 InstrItins->
endStage(SchedClass))) {
1525 if (numAlternatives <
min) {
1526 min = numAlternatives;
1533 const MCSchedClassDesc *SCDesc =
1540 for (
const MCWriteProcResEntry &PRE :
1543 if (!PRE.ReleaseAtCycle)
1545 const MCProcResourceDesc *ProcResource =
1547 unsigned NumUnits = ProcResource->
NumUnits;
1548 if (NumUnits <
min) {
1550 F = PRE.ProcResourceIdx;
1555 llvm_unreachable(
"Should have non-empty InstrItins or hasInstrSchedModel!");
1563 void calcCriticalResources(MachineInstr &
MI) {
1564 unsigned SchedClass =
MI.getDesc().getSchedClass();
1565 if (InstrItins && !InstrItins->
isEmpty()) {
1566 for (
const InstrStage &IS :
1568 InstrItins->
endStage(SchedClass))) {
1576 const MCSchedClassDesc *SCDesc =
1583 for (
const MCWriteProcResEntry &PRE :
1586 if (!PRE.ReleaseAtCycle)
1592 llvm_unreachable(
"Should have non-empty InstrItins or hasInstrSchedModel!");
1596 bool operator()(
const MachineInstr *IS1,
const MachineInstr *IS2)
const {
1598 unsigned MFUs1 = minFuncUnits(IS1, F1);
1599 unsigned MFUs2 = minFuncUnits(IS2, F2);
1602 return MFUs1 > MFUs2;
1607class HighRegisterPressureDetector {
1608 MachineBasicBlock *OrigMBB;
1609 const MachineRegisterInfo &
MRI;
1610 const TargetRegisterInfo *
TRI;
1612 const unsigned PSetNum;
1618 std::vector<unsigned> InitSetPressure;
1622 std::vector<unsigned> PressureSetLimit;
1624 DenseMap<MachineInstr *, RegisterOperands> ROMap;
1626 using Instr2LastUsesTy = DenseMap<MachineInstr *, SmallSet<VirtRegOrUnit, 4>>;
1629 using OrderedInstsTy = std::vector<MachineInstr *>;
1630 using Instr2StageTy = DenseMap<MachineInstr *, unsigned>;
1633 static void dumpRegisterPressures(
const std::vector<unsigned> &Pressures) {
1634 if (Pressures.size() == 0) {
1638 for (
unsigned P : Pressures) {
1646 void dumpPSet(VirtRegOrUnit VRegOrUnit)
const {
1650 dbgs() << *PSetIter <<
' ';
1655 void increaseRegisterPressure(std::vector<unsigned> &Pressure,
1656 VirtRegOrUnit VRegOrUnit)
const {
1659 for (; PSetIter.isValid(); ++PSetIter)
1660 Pressure[*PSetIter] += Weight;
1663 void decreaseRegisterPressure(std::vector<unsigned> &Pressure,
1664 VirtRegOrUnit VRegOrUnit)
const {
1666 unsigned Weight = PSetIter.getWeight();
1667 for (; PSetIter.isValid(); ++PSetIter) {
1668 auto &
P = Pressure[*PSetIter];
1670 "register pressure must be greater than or equal weight");
1676 bool isReservedRegUnit(VirtRegOrUnit VRegOrUnit)
const {
1681 bool isDefinedInThisLoop(VirtRegOrUnit VRegOrUnit)
const {
1694 void computeLiveIn() {
1695 SmallSet<VirtRegOrUnit, 8>
Used;
1696 for (
auto &
MI : *OrigMBB) {
1697 if (
MI.isDebugInstr())
1699 for (
auto &Use : ROMap[&
MI].
Uses) {
1700 VirtRegOrUnit
Reg =
Use.VRegOrUnit;
1703 if (
MI.isPHI() &&
Reg.isVirtualReg() &&
1706 if (isReservedRegUnit(
Reg))
1708 if (isDefinedInThisLoop(
Reg))
1714 for (
auto LiveIn : Used)
1715 increaseRegisterPressure(InitSetPressure, LiveIn);
1719 void computePressureSetLimit(
const RegisterClassInfo &RCI) {
1720 for (
unsigned PSet = 0; PSet < PSetNum; PSet++)
1735 Instr2LastUsesTy computeLastUses(
const OrderedInstsTy &OrderedInsts,
1736 Instr2StageTy &Stages)
const {
1741 SmallSet<VirtRegOrUnit, 8> TargetRegs;
1742 const auto UpdateTargetRegs = [
this, &TargetRegs](VirtRegOrUnit
Reg) {
1743 if (isDefinedInThisLoop(
Reg))
1746 for (MachineInstr *
MI : OrderedInsts) {
1749 UpdateTargetRegs(VirtRegOrUnit(
Reg));
1751 for (
auto &Use : ROMap.
find(
MI)->getSecond().Uses)
1752 UpdateTargetRegs(
Use.VRegOrUnit);
1756 const auto InstrScore = [&Stages](MachineInstr *
MI) {
1757 return Stages[
MI] +
MI->isPHI();
1760 std::map<VirtRegOrUnit, MachineInstr *> LastUseMI;
1762 for (
auto &Use : ROMap.
find(
MI)->getSecond().Uses) {
1763 VirtRegOrUnit
Reg =
Use.VRegOrUnit;
1768 MachineInstr *Orig = Ite->second;
1769 MachineInstr *
New =
MI;
1770 if (InstrScore(Orig) < InstrScore(New))
1776 Instr2LastUsesTy LastUses;
1777 for (
auto [
Reg,
MI] : LastUseMI)
1778 LastUses[
MI].insert(
Reg);
1794 std::vector<unsigned>
1795 computeMaxSetPressure(
const OrderedInstsTy &OrderedInsts,
1796 Instr2StageTy &Stages,
1797 const unsigned StageCount)
const {
1798 using RegSetTy = SmallSet<VirtRegOrUnit, 16>;
1804 auto CurSetPressure = InitSetPressure;
1805 auto MaxSetPressure = InitSetPressure;
1806 auto LastUses = computeLastUses(OrderedInsts, Stages);
1809 dbgs() <<
"Ordered instructions:\n";
1810 for (MachineInstr *
MI : OrderedInsts) {
1811 dbgs() <<
"Stage " << Stages[
MI] <<
": ";
1816 const auto InsertReg = [
this, &CurSetPressure](RegSetTy &RegSet,
1817 VirtRegOrUnit
Reg) {
1818 if (isReservedRegUnit(
Reg))
1826 increaseRegisterPressure(CurSetPressure,
Reg);
1830 const auto EraseReg = [
this, &CurSetPressure](RegSetTy &RegSet,
1831 VirtRegOrUnit
Reg) {
1832 if (isReservedRegUnit(
Reg))
1836 if (!RegSet.contains(
Reg))
1841 decreaseRegisterPressure(CurSetPressure,
Reg);
1845 for (
unsigned I = 0;
I < StageCount;
I++) {
1846 for (MachineInstr *
MI : OrderedInsts) {
1847 const auto Stage = Stages[
MI];
1851 const unsigned Iter =
I - Stage;
1853 for (
auto &Def : ROMap.
find(
MI)->getSecond().Defs)
1854 InsertReg(LiveRegSets[Iter],
Def.VRegOrUnit);
1856 for (
auto LastUse : LastUses[
MI]) {
1859 EraseReg(LiveRegSets[Iter - 1], LastUse);
1861 EraseReg(LiveRegSets[Iter], LastUse);
1865 for (
unsigned PSet = 0; PSet < PSetNum; PSet++)
1866 MaxSetPressure[PSet] =
1867 std::max(MaxSetPressure[PSet], CurSetPressure[PSet]);
1870 dbgs() <<
"CurSetPressure=";
1871 dumpRegisterPressures(CurSetPressure);
1872 dbgs() <<
" iter=" << Iter <<
" stage=" << Stage <<
":";
1878 return MaxSetPressure;
1882 HighRegisterPressureDetector(MachineBasicBlock *OrigMBB,
1884 : OrigMBB(OrigMBB),
MRI(MF.getRegInfo()),
1885 TRI(MF.getSubtarget().getRegisterInfo()),
1886 PSetNum(
TRI->getNumRegPressureSets()), InitSetPressure(PSetNum, 0),
1887 PressureSetLimit(PSetNum, 0) {}
1891 void init(
const RegisterClassInfo &RCI) {
1892 for (MachineInstr &
MI : *OrigMBB) {
1893 if (
MI.isDebugInstr())
1895 ROMap[&
MI].collect(
MI, *
TRI,
MRI,
false,
true);
1899 computePressureSetLimit(RCI);
1904 bool detect(
const SwingSchedulerDAG *SSD, SMSchedule &Schedule,
1905 const unsigned MaxStage)
const {
1906 const int RegPressureMargin = SSD->
Opts.pipeliner_register_pressure_margin;
1907 assert(0 <= RegPressureMargin && RegPressureMargin <= 100 &&
1908 "the percentage of the margin must be between 0 to 100");
1910 OrderedInstsTy OrderedInsts;
1911 Instr2StageTy Stages;
1913 const auto MaxSetPressure =
1914 computeMaxSetPressure(OrderedInsts, Stages, MaxStage + 1);
1917 dbgs() <<
"Dump MaxSetPressure:\n";
1918 for (
unsigned I = 0;
I < MaxSetPressure.size();
I++) {
1919 dbgs() <<
format(
"MaxSetPressure[%d]=%d\n",
I, MaxSetPressure[
I]);
1924 for (
unsigned PSet = 0; PSet < PSetNum; PSet++) {
1925 unsigned Limit = PressureSetLimit[PSet];
1926 unsigned Margin = Limit * RegPressureMargin / 100;
1928 <<
" Margin=" << Margin <<
"\n");
1929 if (Limit < MaxSetPressure[PSet] + Margin) {
1932 <<
"Rejected the schedule because of too high register pressure\n");
1948unsigned SwingSchedulerDAG::calculateResMII() {
1951 return RM.calculateResMII();
1960unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType &NodeSets) {
1961 unsigned RecMII = 0;
1963 for (NodeSet &Nodes : NodeSets) {
1967 unsigned Delay = Nodes.getLatency();
1968 unsigned Distance = 1;
1971 unsigned CurMII = (Delay + Distance - 1) / Distance;
1972 Nodes.setRecMII(CurMII);
1973 if (CurMII > RecMII)
1981void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1982 SwingSchedulerDDG *DDG) {
1983 BitVector
Added(SUnits.size());
1984 DenseMap<int, int> OutputDeps;
1985 for (
int i = 0, e = SUnits.size(); i != e; ++i) {
1991 if (OE.isOutputDep()) {
1992 int N = OE.getDst()->NodeNum;
1994 auto Dep = OutputDeps.
find(BackEdge);
1995 if (Dep != OutputDeps.
end()) {
1996 BackEdge = Dep->second;
1997 OutputDeps.
erase(Dep);
1999 OutputDeps[
N] = BackEdge;
2002 if (OE.getDst()->isBoundaryNode() || OE.isArtificial())
2014 int N = OE.getDst()->NodeNum;
2016 AdjK[i].push_back(
N);
2023 int N = Dst->NodeNum;
2025 AdjK[i].push_back(
N);
2032 for (
auto &OD : OutputDeps)
2033 if (!
Added.test(OD.second)) {
2034 AdjK[OD.first].push_back(OD.second);
2035 Added.set(OD.second);
2041bool SwingSchedulerDAG::Circuits::circuit(
int V,
int S, NodeSetType &NodeSets,
2042 const SwingSchedulerDAG *DAG,
2044 SUnit *
SV = &SUnits[
V];
2049 for (
auto W : AdjK[
V]) {
2050 if (NumPaths > MaxPaths)
2061 if (!Blocked.test(W)) {
2062 if (circuit(W, S, NodeSets, DAG,
2063 Node2Idx->at(W) < Node2Idx->at(
V) ?
true : HasBackedge))
2071 for (
auto W : AdjK[
V]) {
2082void SwingSchedulerDAG::Circuits::unblock(
int U) {
2084 SmallPtrSet<SUnit *, 4> &BU =
B[
U];
2085 while (!BU.
empty()) {
2086 SmallPtrSet<SUnit *, 4>::iterator
SI = BU.
begin();
2087 assert(SI != BU.
end() &&
"Invalid B set.");
2090 if (Blocked.test(
W->NodeNum))
2091 unblock(
W->NodeNum);
2097void SwingSchedulerDAG::findCircuits(NodeSetType &NodeSets) {
2098 Circuits Cir(SUnits, Topo);
2100 Cir.createAdjacencyStructure(&*DDG);
2101 for (
int I = 0,
E = SUnits.size();
I !=
E; ++
I) {
2103 Cir.circuit(
I,
I, NodeSets,
this);
2125void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs *DAG) {
2126 for (SUnit &SU : DAG->
SUnits) {
2136 for (
auto &Dep : SU.
Preds) {
2137 SUnit *TmpSU = Dep.getSUnit();
2138 MachineInstr *TmpMI = TmpSU->
getInstr();
2149 if (PHISUs.
size() == 0 || SrcSUs.
size() == 0)
2157 for (
auto &Dep : PHISUs[Index]->Succs) {
2161 SUnit *TmpSU = Dep.getSUnit();
2162 MachineInstr *TmpMI = TmpSU->
getInstr();
2171 if (UseSUs.
size() == 0)
2176 for (
auto *
I : UseSUs) {
2177 for (
auto *Src : SrcSUs) {
2193void SwingSchedulerDAG::computeNodeFunctions(NodeSetType &NodeSets) {
2194 ScheduleInfo.resize(SUnits.size());
2197 for (
int I : Topo) {
2198 const SUnit &SU = SUnits[
I];
2205 for (
int I : Topo) {
2207 int zeroLatencyDepth = 0;
2208 SUnit *SU = &SUnits[
I];
2210 SUnit *
Pred =
IE.getSrc();
2211 if (
IE.getLatency() == 0)
2213 std::max(zeroLatencyDepth, getZeroLatencyDepth(
Pred) + 1);
2214 if (
IE.ignoreDependence(
true))
2216 asap = std::max(asap, (
int)(getASAP(
Pred) +
IE.getLatency() -
2217 IE.getDistance() * MII));
2219 maxASAP = std::max(maxASAP, asap);
2220 ScheduleInfo[
I].ASAP = asap;
2221 ScheduleInfo[
I].ZeroLatencyDepth = zeroLatencyDepth;
2227 int zeroLatencyHeight = 0;
2228 SUnit *SU = &SUnits[
I];
2230 SUnit *Succ = OE.getDst();
2233 if (OE.getLatency() == 0)
2235 std::max(zeroLatencyHeight, getZeroLatencyHeight(Succ) + 1);
2236 if (OE.ignoreDependence(
true))
2238 alap = std::min(alap, (
int)(getALAP(Succ) - OE.getLatency() +
2239 OE.getDistance() * MII));
2242 ScheduleInfo[
I].ALAP = alap;
2243 ScheduleInfo[
I].ZeroLatencyHeight = zeroLatencyHeight;
2247 for (NodeSet &
I : NodeSets)
2248 I.computeNodeSetInfo(
this);
2251 for (
unsigned i = 0; i < SUnits.size(); i++) {
2252 dbgs() <<
"\tNode " << i <<
":\n";
2253 dbgs() <<
"\t ASAP = " << getASAP(&SUnits[i]) <<
"\n";
2254 dbgs() <<
"\t ALAP = " << getALAP(&SUnits[i]) <<
"\n";
2255 dbgs() <<
"\t MOV = " << getMOV(&SUnits[i]) <<
"\n";
2256 dbgs() <<
"\t D = " << getDepth(&SUnits[i]) <<
"\n";
2257 dbgs() <<
"\t H = " << getHeight(&SUnits[i]) <<
"\n";
2258 dbgs() <<
"\t ZLD = " << getZeroLatencyDepth(&SUnits[i]) <<
"\n";
2259 dbgs() <<
"\t ZLH = " << getZeroLatencyHeight(&SUnits[i]) <<
"\n";
2274 SUnit *PredSU = IE.getSrc();
2275 if (S && S->count(PredSU) == 0)
2277 if (IE.ignoreDependence(
true))
2288 SUnit *SuccSU = OE.getDst();
2289 if (!OE.isAntiDep())
2291 if (S && S->count(SuccSU) == 0)
2297 return !Preds.
empty();
2310 SUnit *SuccSU = OE.getDst();
2311 if (S && S->count(SuccSU) == 0)
2313 if (OE.ignoreDependence(
false))
2324 SUnit *PredSU = IE.getSrc();
2325 if (!IE.isAntiDep())
2327 if (S && S->count(PredSU) == 0)
2333 return !Succs.
empty();
2349 if (!Visited.
insert(Cur).second)
2350 return Path.contains(Cur);
2351 bool FoundPath =
false;
2353 if (!OE.ignoreDependence(
false))
2355 computePath(OE.getDst(), Path, DestNodes, Exclude, Visited, DDG);
2357 if (IE.isAntiDep() && IE.getDistance() == 0)
2359 computePath(IE.getSrc(), Path, DestNodes, Exclude, Visited, DDG);
2374 for (
SUnit *SU : NS) {
2380 if (
Reg.isVirtual())
2382 else if (
MRI.isAllocatable(
Reg))
2383 for (MCRegUnit Unit :
TRI->regunits(
Reg.asMCReg()))
2387 for (
SUnit *SU : NS)
2391 if (
Reg.isVirtual()) {
2395 }
else if (
MRI.isAllocatable(
Reg)) {
2396 for (MCRegUnit Unit :
TRI->regunits(
Reg.asMCReg()))
2407void SwingSchedulerDAG::registerPressureFilter(NodeSetType &NodeSets) {
2408 for (
auto &NS : NodeSets) {
2412 IntervalPressure RecRegPressure;
2413 RegPressureTracker RecRPTracker(RecRegPressure);
2414 RecRPTracker.init(&MF, &RegClassInfo, &LIS, BB, BB->end(),
false,
true);
2416 RecRPTracker.closeBottom();
2418 std::vector<SUnit *> SUnits(NS.begin(), NS.end());
2419 llvm::sort(SUnits, [](
const SUnit *
A,
const SUnit *
B) {
2420 return A->NodeNum >
B->NodeNum;
2423 for (
auto &SU : SUnits) {
2429 RecRPTracker.setPos(std::next(CurInstI));
2431 RegPressureDelta RPDelta;
2433 RecRPTracker.getMaxUpwardPressureDelta(SU->
getInstr(),
nullptr, RPDelta,
2438 dbgs() <<
"Excess register pressure: " << *SU <<
" "
2441 NS.setExceedPressure(SU);
2444 RecRPTracker.recede();
2451void SwingSchedulerDAG::colocateNodeSets(NodeSetType &NodeSets) {
2452 unsigned Colocate = 0;
2453 for (
int i = 0, e = NodeSets.size(); i < e; ++i) {
2455 SmallSetVector<SUnit *, 8>
S1;
2458 for (
int j = i + 1;
j <
e; ++
j) {
2462 SmallSetVector<SUnit *, 8> S2;
2479void SwingSchedulerDAG::checkNodeSets(NodeSetType &NodeSets) {
2484 for (
auto &NS : NodeSets) {
2485 if (NS.getRecMII() > 2)
2487 if (NS.getMaxDepth() > MII)
2496void SwingSchedulerDAG::groupRemainingNodes(NodeSetType &NodeSets) {
2497 SetVector<SUnit *> NodesAdded;
2498 SmallPtrSet<SUnit *, 8> Visited;
2501 for (NodeSet &
I : NodeSets) {
2502 SmallSetVector<SUnit *, 8>
N;
2505 SetVector<SUnit *>
Path;
2506 for (SUnit *NI :
N) {
2508 computePath(NI, Path, NodesAdded,
I, Visited, DDG.get());
2515 if (
succ_L(NodesAdded,
N, DDG.get())) {
2516 SetVector<SUnit *>
Path;
2517 for (SUnit *NI :
N) {
2519 computePath(NI, Path,
I, NodesAdded, Visited, DDG.get());
2530 SmallSetVector<SUnit *, 8>
N;
2531 if (
succ_L(NodesAdded,
N, DDG.get()))
2533 addConnectedNodes(
I, NewSet, NodesAdded);
2534 if (!NewSet.
empty())
2535 NodeSets.push_back(NewSet);
2540 if (
pred_L(NodesAdded,
N, DDG.get()))
2542 addConnectedNodes(
I, NewSet, NodesAdded);
2543 if (!NewSet.
empty())
2544 NodeSets.push_back(NewSet);
2548 for (SUnit &SU : SUnits) {
2549 if (NodesAdded.
count(&SU) == 0) {
2551 addConnectedNodes(&SU, NewSet, NodesAdded);
2552 if (!NewSet.
empty())
2553 NodeSets.push_back(NewSet);
2559void SwingSchedulerDAG::addConnectedNodes(SUnit *SU, NodeSet &NewSet,
2560 SetVector<SUnit *> &NodesAdded) {
2565 if (!OE.isArtificial() && !
Successor->isBoundaryNode() &&
2567 addConnectedNodes(
Successor, NewSet, NodesAdded);
2570 SUnit *Predecessor =
IE.getSrc();
2571 if (!
IE.isArtificial() && NodesAdded.
count(Predecessor) == 0)
2572 addConnectedNodes(Predecessor, NewSet, NodesAdded);
2581 for (
SUnit *SU : Set1) {
2582 if (Set2.
count(SU) != 0)
2585 return !Result.empty();
2589void SwingSchedulerDAG::fuseRecs(NodeSetType &NodeSets) {
2590 for (NodeSetType::iterator
I = NodeSets.begin(),
E = NodeSets.end();
I !=
E;
2593 for (NodeSetType::iterator J =
I + 1; J !=
E;) {
2598 for (SUnit *SU : *J)
2610void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType &NodeSets) {
2611 for (NodeSetType::iterator
I = NodeSets.begin(),
E = NodeSets.end();
I !=
E;
2613 for (NodeSetType::iterator J =
I + 1; J !=
E;) {
2614 J->remove_if([&](SUnit *SUJ) {
return I->count(SUJ); });
2629void SwingSchedulerDAG::computeNodeOrder(NodeSetType &NodeSets) {
2630 SmallSetVector<SUnit *, 8>
R;
2633 for (
auto &Nodes : NodeSets) {
2636 SmallSetVector<SUnit *, 8>
N;
2651 }
else if (NodeSets.size() == 1) {
2652 for (
const auto &
N : Nodes)
2653 if (
N->Succs.size() == 0)
2659 SUnit *maxASAP =
nullptr;
2660 for (SUnit *SU : Nodes) {
2661 if (maxASAP ==
nullptr || getASAP(SU) > getASAP(maxASAP) ||
2662 (getASAP(SU) == getASAP(maxASAP) && SU->
NodeNum > maxASAP->
NodeNum))
2670 while (!
R.empty()) {
2671 if (Order == TopDown) {
2675 while (!
R.empty()) {
2676 SUnit *maxHeight =
nullptr;
2677 for (SUnit *
I : R) {
2678 if (maxHeight ==
nullptr || getHeight(
I) > getHeight(maxHeight))
2680 else if (getHeight(
I) == getHeight(maxHeight) &&
2681 getZeroLatencyHeight(
I) > getZeroLatencyHeight(maxHeight))
2683 else if (getHeight(
I) == getHeight(maxHeight) &&
2684 getZeroLatencyHeight(
I) ==
2685 getZeroLatencyHeight(maxHeight) &&
2686 getMOV(
I) < getMOV(maxHeight))
2691 R.remove(maxHeight);
2692 for (
const auto &OE : DDG->
getOutEdges(maxHeight)) {
2693 SUnit *SU = OE.getDst();
2694 if (Nodes.count(SU) == 0)
2698 if (OE.ignoreDependence(
false))
2707 for (
const auto &IE : DDG->
getInEdges(maxHeight)) {
2708 SUnit *SU =
IE.getSrc();
2709 if (!
IE.isAntiDep())
2711 if (Nodes.count(SU) == 0)
2720 SmallSetVector<SUnit *, 8>
N;
2727 while (!
R.empty()) {
2728 SUnit *maxDepth =
nullptr;
2729 for (SUnit *
I : R) {
2730 if (maxDepth ==
nullptr || getDepth(
I) > getDepth(maxDepth))
2732 else if (getDepth(
I) == getDepth(maxDepth) &&
2733 getZeroLatencyDepth(
I) > getZeroLatencyDepth(maxDepth))
2735 else if (getDepth(
I) == getDepth(maxDepth) &&
2736 getZeroLatencyDepth(
I) == getZeroLatencyDepth(maxDepth) &&
2737 getMOV(
I) < getMOV(maxDepth))
2743 if (Nodes.isExceedSU(maxDepth)) {
2746 R.insert(Nodes.getNode(0));
2749 for (
const auto &IE : DDG->
getInEdges(maxDepth)) {
2750 SUnit *SU =
IE.getSrc();
2751 if (Nodes.count(SU) == 0)
2762 for (
const auto &OE : DDG->
getOutEdges(maxDepth)) {
2763 SUnit *SU = OE.getDst();
2764 if (!OE.isAntiDep())
2766 if (Nodes.count(SU) == 0)
2775 SmallSetVector<SUnit *, 8>
N;
2784 dbgs() <<
"Node order: ";
2786 dbgs() <<
" " << *
I <<
" ";
2792void SwingSchedulerDAG::initPolicy() {
2796 Policy.ShouldLimitRegPressure =
2797 valueOr(Opts.pipeliner_register_pressure, Policy.ShouldLimitRegPressure);
2802bool SwingSchedulerDAG::schedulePipeline(SMSchedule &Schedule) {
2809 bool scheduleFound =
false;
2810 std::unique_ptr<HighRegisterPressureDetector> HRPDetector;
2811 if (Policy.ShouldLimitRegPressure) {
2813 std::make_unique<HighRegisterPressureDetector>(
Loop.getHeader(), MF);
2814 HRPDetector->init(RegClassInfo);
2817 for (
unsigned II = MII;
II <= MAX_II && !scheduleFound; ++
II) {
2829 int EarlyStart = INT_MIN;
2830 int LateStart = INT_MAX;
2834 dbgs() << *SU <<
" ";
2839 dbgs() <<
format(
"\tes: %8x ls: %8x\n", EarlyStart, LateStart));
2841 if (EarlyStart > LateStart)
2842 scheduleFound =
false;
2843 else if (EarlyStart != INT_MIN && LateStart == INT_MAX)
2845 Schedule.
insert(SU, EarlyStart, EarlyStart + (
int)
II - 1,
II);
2846 else if (EarlyStart == INT_MIN && LateStart != INT_MAX)
2848 Schedule.
insert(SU, LateStart, LateStart - (
int)
II + 1,
II);
2849 else if (EarlyStart != INT_MIN && LateStart != INT_MAX) {
2850 LateStart = std::min(LateStart, EarlyStart + (
int)
II - 1);
2859 scheduleFound = Schedule.
insert(SU, LateStart, EarlyStart,
II);
2861 scheduleFound = Schedule.
insert(SU, EarlyStart, LateStart,
II);
2864 scheduleFound = Schedule.
insert(SU, FirstCycle + getASAP(SU),
2865 FirstCycle + getASAP(SU) +
II - 1,
II);
2871 if (Opts.pipeliner_max_stages > -1 &&
2873 scheduleFound =
false;
2877 dbgs() <<
"\tCan't schedule\n";
2879 }
while (++NI != NE && scheduleFound);
2897 if (scheduleFound && HRPDetector)
2906 if (scheduleFound) {
2907 scheduleFound = LoopPipelinerInfo->shouldUseSchedule(*
this, Schedule);
2912 if (scheduleFound) {
2915 return MachineOptimizationRemarkAnalysis(
2917 <<
"Schedule found with Initiation Interval: "
2919 <<
", MaxStageCount: "
2933 if (!
Reg.isVirtual())
2935 if (
MRI.getDefBlock(
Reg) !=
MI.getParent())
2948 if (!
Op.isReg() || !
Op.getReg().isVirtual())
2973 if (!Def || Def->getParent() != LoopBB)
2976 if (Def->isCopy()) {
2978 if (Def->getOperand(0).getSubReg() || Def->getOperand(1).getSubReg())
2980 CurReg = Def->getOperand(1).getReg();
2981 }
else if (Def->isPHI()) {
2987 }
else if (
TII->getIncrementValue(*Def,
Value)) {
2995 bool OffsetIsScalable;
2996 if (
TII->getMemOperandWithOffset(*Def, BaseOp,
Offset,
2997 OffsetIsScalable)) {
2999 CurReg = BaseOp->
getReg();
3011 if (CurReg == OrgReg)
3027 bool OffsetIsScalable;
3028 if (!
TII.getMemOperandWithOffset(
MI, BaseOp,
Offset, OffsetIsScalable))
3032 if (OffsetIsScalable)
3035 if (!BaseOp->
isReg())
3048bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr *
MI,
3050 unsigned &OffsetPos,
3054 if (
TII->isPostIncrement(*
MI))
3056 unsigned BasePosLd, OffsetPosLd;
3057 if (!
TII->getBaseAndOffsetPosition(*
MI, BasePosLd, OffsetPosLd))
3064 if (!Phi || !
Phi->isPHI())
3073 if (!PrevDef || PrevDef ==
MI)
3076 if (!
TII->isPostIncrement(*PrevDef))
3079 unsigned BasePos1 = 0, OffsetPos1 = 0;
3080 if (!
TII->getBaseAndOffsetPosition(*PrevDef, BasePos1, OffsetPos1))
3087 MachineInstr *NewMI = MF.CloneMachineInstr(
MI);
3090 MF.deleteMachineInstr(NewMI);
3095 BasePos = BasePosLd;
3096 OffsetPos = OffsetPosLd;
3108 InstrChanges.find(SU);
3109 if (It != InstrChanges.
end()) {
3110 std::pair<Register, int64_t> RegAndOffset = It->second;
3111 unsigned BasePos, OffsetPos;
3112 if (!
TII->getBaseAndOffsetPosition(*
MI, BasePos, OffsetPos))
3114 Register BaseReg =
MI->getOperand(BasePos).getReg();
3120 if (BaseStageNum < DefStageNum) {
3122 int OffsetDiff = DefStageNum - BaseStageNum;
3123 if (DefCycleNum < BaseCycleNum) {
3129 MI->getOperand(OffsetPos).getImm() + RegAndOffset.second * OffsetDiff;
3144 while (Def->isPHI()) {
3145 if (!Visited.
insert(Def).second)
3147 for (
unsigned i = 1, e = Def->getNumOperands(); i < e; i += 2)
3148 if (Def->getOperand(i + 1).getMBB() == BB) {
3149 Def =
MRI.getVRegDef(Def->getOperand(i).getReg());
3163 int DeltaB, DeltaO, Delta;
3170 int64_t OffsetB, OffsetO;
3171 bool OffsetBIsScalable, OffsetOIsScalable;
3172 if (!
TII.getMemOperandWithOffset(*BaseMI, BaseOpB, OffsetB,
3173 OffsetBIsScalable) ||
3174 !
TII.getMemOperandWithOffset(*OtherMI, BaseOpO, OffsetO,
3178 if (OffsetBIsScalable || OffsetOIsScalable)
3188 if (!RegB.
isVirtual() || !RegO.isVirtual())
3193 if (!DefB || !DefO || !DefB->
isPHI() || !DefO->
isPHI())
3196 Register InitValB, LoopValB, InitValO, LoopValO;
3197 getPhiRegs(*DefB, LoopBB, InitValB, LoopValB);
3198 getPhiRegs(*DefO, LoopBB, InitValO, LoopValO);
3203 if (!InitDefB || !InitDefO || !InitDefB->
isIdenticalTo(*InitDefO))
3218 dbgs() <<
"Overlap check:\n";
3219 dbgs() <<
" BaseMI: ";
3221 dbgs() <<
" Base + " << OffsetB <<
" + I * " << Delta
3222 <<
", Len: " << AccessSizeB.
getValue() <<
"\n";
3223 dbgs() <<
" OtherMI: ";
3225 dbgs() <<
" Base + " << OffsetO <<
" + I * " << Delta
3226 <<
", Len: " << AccessSizeO.
getValue() <<
"\n";
3234 int64_t BaseMinAddr = OffsetB;
3235 int64_t OhterNextIterMaxAddr = OffsetO + Delta + AccessSizeO.
getValue() - 1;
3236 if (BaseMinAddr > OhterNextIterMaxAddr) {
3241 int64_t BaseMaxAddr = OffsetB + AccessSizeB.
getValue() - 1;
3242 int64_t OtherNextIterMinAddr = OffsetO + Delta;
3243 if (BaseMaxAddr < OtherNextIterMinAddr) {
3252void SwingSchedulerDAG::postProcessDAG() {
3253 for (
auto &M : Mutations)
3263 bool forward =
true;
3265 dbgs() <<
"Trying to insert node between " << StartCycle <<
" and "
3266 << EndCycle <<
" II: " <<
II <<
"\n";
3268 if (StartCycle > EndCycle)
3272 int termCycle = forward ? EndCycle + 1 : EndCycle - 1;
3273 for (
int curCycle = StartCycle; curCycle != termCycle;
3274 forward ? ++curCycle : --curCycle) {
3277 ProcItinResources.canReserveResources(*SU, curCycle)) {
3279 dbgs() <<
"\tinsert at cycle " << curCycle <<
" ";
3284 ProcItinResources.reserveResources(*SU, curCycle);
3285 ScheduledInstrs[curCycle].push_back(SU);
3286 InstrToCycle.insert(std::make_pair(SU, curCycle));
3287 if (curCycle > LastCycle)
3288 LastCycle = curCycle;
3289 if (curCycle < FirstCycle)
3290 FirstCycle = curCycle;
3294 dbgs() <<
"\tfailed to insert at cycle " << curCycle <<
" ";
3305 for (
auto &
P : SU->
Preds)
3306 if (
P.getKind() ==
SDep::Anti &&
P.getSUnit()->getInstr()->isPHI())
3307 for (
auto &S :
P.getSUnit()->Succs)
3308 if (S.getKind() ==
SDep::Data && S.getSUnit()->getInstr()->isPHI())
3309 return P.getSUnit();
3322 for (
int cycle =
getFirstCycle(); cycle <= LastCycle; ++cycle) {
3325 if (IE.getSrc() ==
I) {
3326 int EarlyStart = cycle + IE.getLatency() - IE.getDistance() *
II;
3327 *MaxEarlyStart = std::max(*MaxEarlyStart, EarlyStart);
3332 if (OE.getDst() ==
I) {
3333 int LateStart = cycle - OE.getLatency() + OE.getDistance() *
II;
3334 *MinLateStart = std::min(*MinLateStart, LateStart);
3339 for (
const auto &Dep : SU->
Preds) {
3342 if (BE && Dep.getSUnit() == BE && !SU->
getInstr()->
isPHI() &&
3344 *MinLateStart = std::min(*MinLateStart, cycle);
3354 std::deque<SUnit *> &Insts)
const {
3356 bool OrderBeforeUse =
false;
3357 bool OrderAfterDef =
false;
3358 bool OrderBeforeDef =
false;
3359 unsigned MoveDef = 0;
3360 unsigned MoveUse = 0;
3365 for (std::deque<SUnit *>::iterator
I = Insts.begin(), E = Insts.end();
I != E;
3368 if (!MO.isReg() || !MO.getReg().isVirtual())
3372 unsigned BasePos, OffsetPos;
3373 if (ST.getInstrInfo()->getBaseAndOffsetPosition(*
MI, BasePos, OffsetPos))
3374 if (
MI->getOperand(BasePos).getReg() == Reg)
3378 std::tie(Reads, Writes) =
3379 (*I)->getInstr()->readsWritesVirtualRegister(Reg);
3381 OrderBeforeUse =
true;
3386 OrderAfterDef =
true;
3388 }
else if (MO.isUse() && Writes &&
stageScheduled(*
I) == StageInst1) {
3390 OrderBeforeUse =
true;
3394 OrderAfterDef =
true;
3398 OrderBeforeUse =
true;
3402 OrderAfterDef =
true;
3407 OrderBeforeUse =
true;
3413 OrderBeforeDef =
true;
3421 if (OE.getDst() != *
I)
3424 OrderBeforeUse =
true;
3431 else if ((OE.isAntiDep() || OE.isOutputDep()) &&
3433 OrderBeforeUse =
true;
3434 if ((MoveUse == 0) || (Pos < MoveUse))
3439 if (IE.getSrc() != *
I)
3441 if ((IE.isAntiDep() || IE.isOutputDep() || IE.isOrderDep()) &&
3443 OrderAfterDef =
true;
3450 if (OrderAfterDef && OrderBeforeUse && MoveUse == MoveDef)
3451 OrderBeforeUse =
false;
3456 OrderBeforeUse = !OrderAfterDef || (MoveUse > MoveDef);
3460 if (OrderBeforeUse && OrderAfterDef) {
3461 SUnit *UseSU = Insts.at(MoveUse);
3462 SUnit *DefSU = Insts.at(MoveDef);
3463 if (MoveUse > MoveDef) {
3464 Insts.erase(Insts.begin() + MoveUse);
3465 Insts.erase(Insts.begin() + MoveDef);
3467 Insts.erase(Insts.begin() + MoveDef);
3468 Insts.erase(Insts.begin() + MoveUse);
3478 Insts.push_front(SU);
3480 Insts.push_back(SU);
3488 assert(Phi.isPHI() &&
"Expecting a Phi.");
3495 getPhiRegs(Phi, Phi.getParent(), InitVal, LoopVal);
3503 return (LoopCycle > DefCycle) || (LoopStage <= DefStage);
3521 if (!Phi || !Phi->isPHI() || Phi->getParent() != Def->getParent())
3527 if (DMO.getReg() == LoopReg)
3538 if (InstrToCycle.count(IE.getSrc()))
3549 for (
auto &SU : SSD->
SUnits)
3554 while (!Worklist.
empty()) {
3556 if (DoNotPipeline.
count(SU))
3559 DoNotPipeline.
insert(SU);
3566 if (OE.getDistance() == 1)
3569 return DoNotPipeline;
3578 int NewLastCycle = INT_MIN;
3583 NewLastCycle = std::max(NewLastCycle, InstrToCycle[&SU]);
3590 if (IE.getDistance() == 0)
3591 NewCycle = std::max(InstrToCycle[IE.getSrc()], NewCycle);
3596 if (OE.getDistance() == 1)
3597 NewCycle = std::max(InstrToCycle[OE.getDst()], NewCycle);
3599 int OldCycle = InstrToCycle[&SU];
3600 if (OldCycle != NewCycle) {
3601 InstrToCycle[&SU] = NewCycle;
3605 LLVM_DEBUG(
dbgs() << SU <<
" is not pipelined; moving from cycle "
3606 << OldCycle <<
" to " << NewCycle
3632 if (FirstCycle + InitiationInterval <= NewCycle)
3635 NewLastCycle = std::max(NewLastCycle, NewCycle);
3637 LastCycle = NewLastCycle;
3654 int CycleDef = InstrToCycle[&SU];
3655 assert(StageDef != -1 &&
"Instruction should have been scheduled.");
3657 SUnit *Dst = OE.getDst();
3658 if (OE.isAssignedRegDep() && !Dst->isBoundaryNode())
3659 if (OE.getReg().isPhysical()) {
3662 if (InstrToCycle[Dst] <= CycleDef)
3680void SwingSchedulerDAG::checkValidNodeOrder(
const NodeSetType &Circuits)
const {
3683 typedef std::pair<SUnit *, unsigned> UnitIndex;
3684 std::vector<UnitIndex> Indices(
NodeOrder.size(), std::make_pair(
nullptr, 0));
3686 for (
unsigned i = 0, s =
NodeOrder.size(); i < s; ++i)
3687 Indices.push_back(std::make_pair(
NodeOrder[i], i));
3689 auto CompareKey = [](UnitIndex i1, UnitIndex i2) {
3690 return std::get<0>(i1) < std::get<0>(i2);
3703 for (
unsigned i = 0, s =
NodeOrder.size(); i < s; ++i) {
3707 bool PredBefore =
false;
3708 bool SuccBefore =
false;
3716 SUnit *PredSU = IE.getSrc();
3717 unsigned PredIndex = std::get<1>(
3727 SUnit *SuccSU = OE.getDst();
3733 unsigned SuccIndex = std::get<1>(
3746 Circuits, [SU](
const NodeSet &Circuit) {
return Circuit.
count(SU); });
3751 NumNodeOrderIssues++;
3755 <<
" are scheduled before node " << *SU <<
"\n");
3761 dbgs() <<
"Invalid node order found!\n";
3774 for (
SUnit *SU : Instrs) {
3776 for (
unsigned i = 0, e =
MI->getNumOperands(); i < e; ++i) {
3784 InstrChanges.find(SU);
3785 if (It != InstrChanges.
end()) {
3786 unsigned BasePos, OffsetPos;
3788 if (
TII->getBaseAndOffsetPosition(*
MI, BasePos, OffsetPos)) {
3792 MI->getOperand(OffsetPos).getImm() - It->second.second;
3805 unsigned TiedUseIdx = 0;
3806 if (
MI->isRegTiedToUseOperand(i, &TiedUseIdx)) {
3808 OverlapReg =
MI->getOperand(TiedUseIdx).getReg();
3810 NewBaseReg =
MI->getOperand(i).getReg();
3819 const std::deque<SUnit *> &Instrs)
const {
3820 std::deque<SUnit *> NewOrderPhi;
3821 for (
SUnit *SU : Instrs) {
3823 NewOrderPhi.push_back(SU);
3825 std::deque<SUnit *> NewOrderI;
3826 for (
SUnit *SU : Instrs) {
3842 std::deque<SUnit *> &cycleInstrs =
3843 ScheduledInstrs[cycle + (stage * InitiationInterval)];
3845 ScheduledInstrs[cycle].push_front(SU);
3851 for (
int cycle =
getFinalCycle() + 1; cycle <= LastCycle; ++cycle)
3852 ScheduledInstrs.erase(cycle);
3862 std::deque<SUnit *> &cycleInstrs = ScheduledInstrs[Cycle];
3870#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3872 os <<
"Num nodes " <<
size() <<
" rec " << RecMII <<
" mov " << MaxMOV
3873 <<
" depth " << MaxDepth <<
" col " << Colocate <<
"\n";
3874 for (
const auto &
I : Nodes)
3875 os <<
" " << *
I <<
" " << *(
I->getInstr());
3885 for (
SUnit *CI : cycleInstrs->second) {
3898void ResourceManager::dumpMRT()
const {
3902 std::stringstream SS;
3904 SS << std::setw(4) <<
"Slot";
3905 for (
unsigned I = 1, E = SM.getNumProcResourceKinds();
I < E; ++
I)
3906 SS << std::setw(3) <<
I;
3907 SS << std::setw(7) <<
"#Mops"
3909 for (
int Slot = 0; Slot < InitiationInterval; ++Slot) {
3910 SS << std::setw(4) << Slot;
3911 for (
unsigned I = 1, E = SM.getNumProcResourceKinds();
I < E; ++
I)
3912 SS << std::setw(3) << MRT[Slot][
I];
3913 SS << std::setw(7) << NumScheduledMops[Slot] <<
"\n";
3922 : STI(ST), SM(ST->getSchedModel()), ST(ST), TII(ST->getInstrInfo()),
3923 DAG(DAG), UseDFA(ST->useDFAforSMS()),
3924 ProcResourceMasks(SM.getNumProcResourceKinds(), 0),
3925 IssueWidth(SM.IssueWidth) {
3927 if (IssueWidth <= 0)
3930 if (DAG->Opts.pipeliner_force_issue_width > 0)
3931 IssueWidth = DAG->Opts.pipeliner_force_issue_width;
3936 unsigned ProcResourceID = 0;
3940 assert(SM.getNumProcResourceKinds() < 64 &&
3941 "Too many kinds of resources, unsupported");
3944 Masks.
resize(SM.getNumProcResourceKinds());
3945 for (
unsigned I = 1, E = SM.getNumProcResourceKinds();
I < E; ++
I) {
3947 if (
Desc.SubUnitsIdxBegin)
3949 Masks[
I] = 1ULL << ProcResourceID;
3953 for (
unsigned I = 1, E = SM.getNumProcResourceKinds();
I < E; ++
I) {
3955 if (!
Desc.SubUnitsIdxBegin)
3957 Masks[
I] = 1ULL << ProcResourceID;
3958 for (
unsigned U = 0; U <
Desc.NumUnits; ++U)
3959 Masks[
I] |= Masks[
Desc.SubUnitsIdxBegin[U]];
3963 if (DAG->Opts.pipeliner_show_mask) {
3964 dbgs() <<
"ProcResourceDesc:\n";
3965 for (
unsigned I = 1, E = SM.getNumProcResourceKinds();
I < E; ++
I) {
3967 dbgs() <<
format(
" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3968 ProcResource->
Name,
I, Masks[
I],
3971 dbgs() <<
" -----------------\n";
3978 if (DAG->Opts.pipeliner_dbg_res)
3979 dbgs() <<
"canReserveResources:\n";
3982 return DFAResources[positiveModulo(Cycle, InitiationInterval)]
3988 dbgs() <<
"No valid Schedule Class Desc for schedClass!\n";
3994 reserveResources(SCDesc, Cycle);
3995 bool Result = !isOverbooked();
3996 unreserveResources(SCDesc, Cycle);
3999 <<
"return " << Result <<
"\n\n");
4003void ResourceManager::reserveResources(
SUnit &SU,
int Cycle) {
4005 if (DAG->Opts.pipeliner_dbg_res)
4006 dbgs() <<
"reserveResources:\n";
4009 return DFAResources[positiveModulo(Cycle, InitiationInterval)]
4015 dbgs() <<
"No valid Schedule Class Desc for schedClass!\n";
4021 reserveResources(SCDesc, Cycle);
4024 if (DAG->Opts.pipeliner_dbg_res) {
4026 dbgs() <<
"reserveResources: done!\n\n";
4036 for (
int C = Cycle;
C < Cycle + PRE.ReleaseAtCycle; ++
C)
4037 ++MRT[positiveModulo(
C, InitiationInterval)][PRE.ProcResourceIdx];
4040 ++NumScheduledMops[positiveModulo(
C, InitiationInterval)];
4048 for (
int C = Cycle;
C < Cycle + PRE.ReleaseAtCycle; ++
C)
4049 --MRT[positiveModulo(
C, InitiationInterval)][PRE.ProcResourceIdx];
4052 --NumScheduledMops[positiveModulo(
C, InitiationInterval)];
4055bool ResourceManager::isOverbooked()
const {
4057 for (
int Slot = 0;
Slot < InitiationInterval; ++
Slot) {
4058 for (
unsigned I = 1,
E = SM.getNumProcResourceKinds();
I <
E; ++
I) {
4059 const MCProcResourceDesc *
Desc = SM.getProcResource(
I);
4060 if (MRT[Slot][
I] >
Desc->NumUnits)
4063 if (NumScheduledMops[Slot] > IssueWidth)
4069int ResourceManager::calculateResMIIDFA()
const {
4074 FuncUnitSorter FUS = FuncUnitSorter(*ST);
4075 for (SUnit &SU : DAG->SUnits)
4076 FUS.calcCriticalResources(*SU.
getInstr());
4077 PriorityQueue<MachineInstr *, std::vector<MachineInstr *>, FuncUnitSorter>
4080 for (SUnit &SU : DAG->SUnits)
4085 std::unique_ptr<DFAPacketizer>(TII->CreateTargetScheduleState(*ST)));
4087 while (!FuncUnitOrder.empty()) {
4088 MachineInstr *
MI = FuncUnitOrder.top();
4089 FuncUnitOrder.pop();
4090 if (TII->isZeroCost(
MI->getOpcode()))
4095 unsigned NumCycles = DAG->getSUnit(
MI)->Latency;
4096 unsigned ReservedCycles = 0;
4100 dbgs() <<
"Trying to reserve resource for " << NumCycles
4101 <<
" cycles for \n";
4104 for (
unsigned C = 0;
C < NumCycles; ++
C)
4106 if ((*RI)->canReserveResources(*
MI)) {
4107 (*RI)->reserveResources(*
MI);
4114 <<
", NumCycles:" << NumCycles <<
"\n");
4116 for (
unsigned C = ReservedCycles;
C < NumCycles; ++
C) {
4118 <<
"NewResource created to reserve resources"
4120 auto *NewResource = TII->CreateTargetScheduleState(*ST);
4121 assert(NewResource->canReserveResources(*
MI) &&
"Reserve error.");
4122 NewResource->reserveResources(*
MI);
4123 Resources.push_back(std::unique_ptr<DFAPacketizer>(NewResource));
4134 return calculateResMIIDFA();
4141 for (
SUnit &SU : DAG->SUnits) {
4150 if (DAG->Opts.pipeliner_dbg_res) {
4153 <<
" WriteProcRes: ";
4158 make_range(STI->getWriteProcResBegin(SCDesc),
4159 STI->getWriteProcResEnd(SCDesc))) {
4161 if (DAG->Opts.pipeliner_dbg_res) {
4163 SM.getProcResource(PRE.ProcResourceIdx);
4164 dbgs() <<
Desc->Name <<
": " << PRE.ReleaseAtCycle <<
", ";
4167 ResourceCount[PRE.ProcResourceIdx] += PRE.ReleaseAtCycle;
4172 int Result = (NumMops + IssueWidth - 1) / IssueWidth;
4174 if (DAG->Opts.pipeliner_dbg_res)
4175 dbgs() <<
"#Mops: " << NumMops <<
", "
4176 <<
"IssueWidth: " << IssueWidth <<
", "
4177 <<
"Cycles: " << Result <<
"\n";
4181 if (DAG->Opts.pipeliner_dbg_res) {
4182 std::stringstream SS;
4183 SS << std::setw(2) <<
"ID" << std::setw(16) <<
"Name" << std::setw(10)
4184 <<
"Units" << std::setw(10) <<
"Consumed" << std::setw(10) <<
"Cycles"
4189 for (
unsigned I = 1, E = SM.getNumProcResourceKinds();
I < E; ++
I) {
4191 int Cycles = (ResourceCount[
I] +
Desc->NumUnits - 1) /
Desc->NumUnits;
4193 if (DAG->Opts.pipeliner_dbg_res) {
4194 std::stringstream SS;
4195 SS << std::setw(2) <<
I << std::setw(16) <<
Desc->Name << std::setw(10)
4196 <<
Desc->NumUnits << std::setw(10) << ResourceCount[
I]
4197 << std::setw(10) << Cycles <<
"\n";
4201 if (Cycles > Result)
4208 InitiationInterval =
II;
4209 DFAResources.clear();
4210 DFAResources.resize(
II);
4211 for (
auto &
I : DFAResources)
4212 I.reset(ST->getInstrInfo()->CreateTargetScheduleState(*ST));
4215 NumScheduledMops.clear();
4216 NumScheduledMops.resize(
II);
4220 if (Pred.isArtificial() || Dst->isBoundaryNode())
4225 return IgnoreAnti && (Pred.getKind() ==
SDep::Kind::Anti || Distance != 0);
4228SwingSchedulerDDG::SwingSchedulerDDGEdges &
4229SwingSchedulerDDG::getEdges(
const SUnit *SU) {
4231 return EntrySUEdges;
4237const SwingSchedulerDDG::SwingSchedulerDDGEdges &
4238SwingSchedulerDDG::getEdges(
const SUnit *SU)
const {
4240 return EntrySUEdges;
4246void SwingSchedulerDDG::addEdge(
const SUnit *SU,
4249 "Validation-only edges are not expected here.");
4251 auto &Edges = getEdges(SU);
4252 if (
Edge.getSrc() == SU)
4253 Edges.Succs.push_back(
Edge);
4255 Edges.Preds.push_back(
Edge);
4258void SwingSchedulerDDG::initEdges(
SUnit *SU) {
4259 for (
const auto &PI : SU->
Preds) {
4260 SwingSchedulerDDGEdge
Edge(SU, PI,
false,
4265 for (
const auto &SI : SU->
Succs) {
4266 SwingSchedulerDDGEdge
Edge(SU, SI,
true,
4274 : EntrySU(EntrySU), ExitSU(ExitSU) {
4275 EdgesVec.resize(SUnits.size());
4280 for (
auto &SU : SUnits)
4284 for (
SUnit &SU : SUnits) {
4289 for (
SUnit *Dst : *OD) {
4292 Edge.setDistance(1);
4293 ValidationOnlyEdges.push_back(Edge);
4305 bool UseAsExtraEdge = [&]() {
4306 if (Edge.getDistance() == 0 || !Edge.isOrderDep())
4309 SUnit *Src = Edge.getSrc();
4310 SUnit *Dst = Edge.getDst();
4311 if (Src->NodeNum < Dst->NodeNum)
4319 getEdges(Edge.getSrc()).ExtraSuccs.push_back(Edge.getDst());
4325const SwingSchedulerDDG::EdgesType &
4327 return getEdges(SU).Preds;
4330const SwingSchedulerDDG::EdgesType &
4332 return getEdges(SU).Succs;
4336 return getEdges(SU).ExtraSuccs;
4343 auto ExpandCycle = [&](
SUnit *SU) {
4346 return Cycle + (Stage *
II);
4350 SUnit *Src = Edge.getSrc();
4351 SUnit *Dst = Edge.getDst();
4352 if (!Src->isInstr() || !Dst->isInstr())
4354 int CycleSrc = ExpandCycle(Src);
4355 int CycleDst = ExpandCycle(Dst);
4356 int MaxLateStart = CycleDst + Edge.getDistance() *
II - Edge.getLatency();
4357 if (CycleSrc > MaxLateStart) {
4359 dbgs() <<
"Validation failed for edge from " << *Src <<
" to " << *Dst
4370 for (
SUnit &SU : SUnits) {
4399 !
TII->isGlobalMemoryObject(FromMI) &&
4410#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4419 const auto DumpSU = [](
const SUnit *SU) {
4426 dbgs() <<
" Loop carried edges from " << DumpSU(SU) <<
"\n"
4428 for (
SUnit *Dst : *Order)
4429 dbgs() <<
" " << DumpSU(Dst) <<
"\n";
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
static std::optional< unsigned > getTag(const TargetRegisterInfo *TRI, const MachineInstr &MI, const LoadInfo &LI)
Ops append({Chain, DAG.getConstant(SVEStores[NumParts - 2], DL, MVT::i32)})
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
DXIL Remove Unused Resources
This file defines the DenseMap class.
A common definition of LaneBitmask for use in TableGen and CodeGen.
static bool hasPHICycleDFS(unsigned Reg, const DenseMap< unsigned, SmallVector< unsigned, 2 > > &PhiDeps, SmallSet< unsigned, 8 > &Visited, SmallSet< unsigned, 8 > &RecStack)
Depth-first search to detect cycles among PHI dependencies.
static void computeLiveOuts(MachineFunction &MF, RegPressureTracker &RPTracker, NodeSet &NS)
Compute the live-out registers for the instructions in a node-set.
static void computeScheduledInsts(const SwingSchedulerDAG *SSD, SMSchedule &Schedule, std::vector< MachineInstr * > &OrderedInsts, DenseMap< MachineInstr *, unsigned > &Stages)
Create an instruction stream that represents a single iteration and stage of each instruction.
static bool findLoopIncrementValue(const MachineInstr &MI, const MachineOperand &Op, int &Value)
When Op is a value that is incremented recursively in a loop and there is a unique instruction that i...
static Register getLoopPhiReg(const MachineInstr &Phi, const MachineBasicBlock *LoopBB)
Return the Phi register value that comes the loop block.
static bool hasLoopCarriedMemDep(const SUnitWithMemInfo &Src, const SUnitWithMemInfo &Dst, BatchAAResults &BAA, const TargetInstrInfo *TII)
Returns true if there is a loop-carried order dependency from Src to Dst.
static bool isIntersect(SmallSetVector< SUnit *, 8 > &Set1, const NodeSet &Set2, SmallSetVector< SUnit *, 8 > &Result)
Return true if Set1 contains elements in Set2.
static bool computeDelta(const MachineInstr &MI, const TargetInstrInfo &TII, int &Delta)
Return true if we can compute the amount the instruction changes during each iteration.
static bool isSuccOrder(SUnit *SUa, SUnit *SUb)
Return true if SUb can be reached from SUa following the chain edges.
static bool hasPHICycle(const MachineBasicBlock *LoopHeader, const MachineRegisterInfo &MRI)
static bool runMachinePipeliner(MachineFunction &MF, function_ref< const MachineLoopInfo &()> GetMLI, function_ref< LiveIntervals &()> GetLIS, function_ref< AAResults &()> GetAA, function_ref< MachineOptimizationRemarkEmitter &()> GetORE, function_ref< RegisterClassInfo &()> GetRCI, function_ref< MachineDominatorTree *()> GetMDT)
static bool pred_L(SetVector< SUnit * > &NodeOrder, SmallSetVector< SUnit *, 8 > &Preds, SwingSchedulerDDG *DDG, const NodeSet *S=nullptr)
Compute the Pred_L(O) set, as defined in the paper.
static bool computePath(SUnit *Cur, SetVector< SUnit * > &Path, SetVector< SUnit * > &DestNodes, SetVector< SUnit * > &Exclude, SmallPtrSet< SUnit *, 8 > &Visited, SwingSchedulerDDG *DDG)
Return true if there is a path from the specified node to any of the nodes in DestNodes.
static bool succ_L(SetVector< SUnit * > &NodeOrder, SmallSetVector< SUnit *, 8 > &Succs, SwingSchedulerDDG *DDG, const NodeSet *S=nullptr)
Compute the Succ_L(O) set, as defined in the paper.
static SUnit * multipleIterations(SUnit *SU, SwingSchedulerDAG *DAG)
If an instruction has a use that spans multiple iterations, then return true.
static Register findUniqueOperandDefinedInLoop(const MachineInstr &MI)
static void getPhiRegs(const MachineInstr &Phi, const MachineBasicBlock *Loop, Register &InitVal, Register &LoopVal)
Return the register values for the operands of a Phi instruction.
Register const TargetRegisterInfo * TRI
Promote Memory to Register
This file provides utility analysis objects describing memory locations.
uint64_t IntrinsicInst * II
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the PriorityQueue class.
MachineRegisterInfo & MRI
Remove Loads Into Fake Uses
std::pair< BasicBlock *, BasicBlock * > Edge
This file defines generic set operations that may be used on set's of different types,...
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Target-Independent Code Generator Pass Configuration Options pass.
Add loop-carried chain dependencies.
void computeDependencies()
The main function to compute loop-carried order-dependencies.
LoopCarriedOrderDepsTracker(SwingSchedulerDAG *SSD, BatchAAResults *BAA, const TargetInstrInfo *TII)
const BitVector & getLoopCarried(unsigned Idx) const
MachineOptimizationRemarkEmitter * ORE
const TargetInstrInfo * TII
bool run()
Run the software pipeliner over all loops in the function.
MachineDominatorTree * MDT
const MachineLoopInfo * MLI
MachinePipelinerImpl(MachineFunction &MF, const MachineLoopInfo &MLI, LiveIntervals &LIS, AAResults &AA, MachineOptimizationRemarkEmitter &ORE, RegisterClassInfo &RegClassInfo, MachineDominatorTree *MDT)
const InstrItineraryData * InstrItins
const CodeGenOptions & Opts
RegisterClassInfo * RegClassInfo
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
bool areMemAccessesTriviallyDisjoint(const MachineInstr &MIa, const MachineInstr &MIb) const override
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
iterator find(const_arg_type_t< KeyT > Val)
bool erase(const KeyT &Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
AttributeList getAttributes() const
Return the attribute list for this Function.
Itinerary data supplied by a subtarget to be used by a target.
const InstrStage * beginStage(unsigned ItinClassIndx) const
Return the first stage of the itinerary.
const InstrStage * endStage(unsigned ItinClassIndx) const
Return the last+1 stage of the itinerary.
bool isEmpty() const
Returns true if there are no itineraries.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
TypeSize getValue() const
Represents a single loop in the control flow graph.
unsigned getSchedClass() const
Return the scheduling class for this instruction.
const MCWriteProcResEntry * getWriteProcResEnd(const MCSchedClassDesc *SC) const
const MCWriteProcResEntry * getWriteProcResBegin(const MCSchedClassDesc *SC) const
Return an iterator at the first process resource consumed by the given scheduling class.
const MCSchedModel & getSchedModel() const
Get the machine model for this subtarget's CPU.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
LLVM_ABI StringRef getString() const
MachineInstrBundleIterator< const MachineInstr > const_iterator
iterator_range< iterator > phis()
Returns a range that iterates over the phis in the basic block.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
instr_iterator instr_end()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
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.
Function & getFunction()
Return the LLVM function that this machine code represents.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
bool memoperands_empty() const
Return true if we don't have any memory operands which described the memory access done by this instr...
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
bool isRegSequence() const
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
LLVM_ABI bool isIdenticalTo(const MachineInstr &Other, MICheckType Check=CheckDefs) const
Return true if this instruction is identical to Other.
LLVM_ABI 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.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
bool isPseudo(QueryType Type=IgnoreBundle) const
Return true if this is a pseudo instruction that doesn't correspond to a real machine instruction.
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
Analysis pass that exposes the MachineLoopInfo for a machine function.
A description of a memory reference used in the backend.
AAMDNodes getAAInfo() const
Return the AA tags for the memory reference.
const Value * getValue() const
Return the base address of the memory access.
int64_t getOffset() const
For normal values, this is a byte offset added to the base address.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
void setImm(int64_t immVal)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
Register getReg() const
getReg - Returns the register number.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
defusechain_instr_iterator< true, false, false, true > use_instr_iterator
use_instr_iterator/use_instr_begin/use_instr_end - Walk all uses of the specified register,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
use_instr_iterator use_instr_begin(Register RegNo) const
PSetIterator getPressureSets(VirtRegOrUnit VRegOrUnit) const
Get an iterator over the pressure sets affected by the virtual register or register unit.
MachineBasicBlock * getDefBlock(Register Reg) const
Return the machine basic block in which the specified virtual register is defined,...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
static use_instr_iterator use_instr_end()
const MachineFunction & getMF() const
LLVM_ABI bool isReservedRegUnit(MCRegUnit Unit) const
Returns true when the given register unit is considered reserved.
LLVM_ABI LLVM_READONLY MachineInstr * getUniqueVRegDef(Register Reg) const
getUniqueVRegDef - Return the unique machine instr that defines the specified virtual register or nul...
static MemoryLocation getBeforeOrAfter(const Value *Ptr, const AAMDNodes &AATags=AAMDNodes())
Return a location that may access any location before or after Ptr, while remaining within the underl...
Expand the kernel using modulo variable expansion algorithm (MVE).
static LLVM_ABI bool canApply(MachineLoop &L)
Check if ModuloScheduleExpanderMVE can be applied to L.
The ModuloScheduleExpander takes a ModuloSchedule and expands it in-place, rewriting the old loop and...
LLVM_ABI void cleanup()
Performs final cleanup after expansion.
LLVM_ABI void expand()
Performs the actual expansion.
Expander that simply annotates each scheduled instruction with a post-instr symbol that can be consum...
LLVM_ABI void annotate()
Performs the annotation.
Represents a schedule for a single-block loop.
A NodeSet contains a set of SUnit DAG nodes with additional information that assigns a priority to th...
SUnit * getNode(unsigned i) const
LLVM_ABI void print(raw_ostream &os) const
void setRecMII(unsigned mii)
unsigned count(SUnit *SU) const
void setColocate(unsigned c)
int compareRecMII(NodeSet &RHS)
LLVM_DUMP_METHOD void dump() const
unsigned getWeight() const
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
A reimplementation of ModuloScheduleExpander.
PointerIntPair - This class implements a pair of a pointer and small integer.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Track the current register pressure at some position in the instruction stream, and remember the high...
LLVM_ABI void addLiveRegs(ArrayRef< VRegMaskOrUnit > Regs)
Force liveness of virtual registers or physical register units.
unsigned getRegPressureSetLimit(unsigned Idx) const
Get the register unit limit for the given pressure set index.
Wrapper class representing virtual and physical registers.
constexpr bool isValid() const
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
LLVM_ABI int calculateResMII() const
LLVM_ABI void initProcResourceVectors(const MCSchedModel &SM, SmallVectorImpl< uint64_t > &Masks)
LLVM_ABI ResourceManager(const TargetSubtargetInfo *ST, ScheduleDAGInstrs *DAG)
LLVM_ABI void init(int II)
Initialize resources with the initiation interval II.
LLVM_ABI bool canReserveResources(SUnit &SU, int Cycle)
Check if the resources occupied by a machine instruction are available in the current state.
Kind
These are the different kinds of scheduling dependencies.
@ Order
Any other ordering dependency.
@ Anti
A register anti-dependence (aka WAR).
@ Data
Regular data dependence (aka true-dependence).
void setLatency(unsigned Lat)
Sets the latency for this edge.
@ Barrier
An unknown scheduling barrier.
@ Artificial
Arbitrary strong DAG edge (no real dependence).
This class represents the scheduled code.
LLVM_ABI std::deque< SUnit * > reorderInstructions(const SwingSchedulerDAG *SSD, const std::deque< SUnit * > &Instrs) const
void setInitiationInterval(int ii)
Set the initiation interval for this schedule.
LLVM_ABI void dump() const
Utility function used for debugging to print the schedule.
LLVM_ABI bool insert(SUnit *SU, int StartCycle, int EndCycle, int II)
Try to schedule the node at the specified StartCycle and continue until the node is schedule or the E...
unsigned getMaxStageCount()
Return the maximum stage count needed for this schedule.
LLVM_ABI void print(raw_ostream &os) const
Print the schedule information to the given output.
LLVM_ABI bool onlyHasLoopCarriedOutputOrOrderPreds(SUnit *SU, const SwingSchedulerDDG *DDG) const
Return true if all scheduled predecessors are loop-carried output/order dependencies.
int stageScheduled(SUnit *SU) const
Return the stage for a scheduled instruction.
LLVM_ABI void orderDependence(const SwingSchedulerDAG *SSD, SUnit *SU, std::deque< SUnit * > &Insts) const
Order the instructions within a cycle so that the definitions occur before the uses.
LLVM_ABI bool isValidSchedule(SwingSchedulerDAG *SSD)
int getInitiationInterval() const
Return the initiation interval for this schedule.
std::deque< SUnit * > & getInstructions(int cycle)
Return the instructions that are scheduled at the specified cycle.
int getFirstCycle() const
Return the first cycle in the completed schedule.
DenseMap< int, std::deque< SUnit * > >::const_iterator const_sched_iterator
LLVM_ABI bool isLoopCarriedDefOfUse(const SwingSchedulerDAG *SSD, MachineInstr *Def, MachineOperand &MO) const
Return true if the instruction is a definition that is loop carried and defines the use on the next i...
unsigned cycleScheduled(SUnit *SU) const
Return the cycle for a scheduled instruction.
LLVM_ABI SmallPtrSet< SUnit *, 8 > computeUnpipelineableNodes(SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI)
Determine transitive dependences of unpipelineable instructions.
LLVM_ABI void computeStart(SUnit *SU, int *MaxEarlyStart, int *MinLateStart, int II, SwingSchedulerDAG *DAG)
Compute the scheduling start slot for the instruction.
LLVM_ABI bool normalizeNonPipelinedInstructions(SwingSchedulerDAG *SSD, TargetInstrInfo::PipelinerLoopInfo *PLI)
LLVM_ABI bool isLoopCarried(const SwingSchedulerDAG *SSD, MachineInstr &Phi) const
Return true if the scheduled Phi has a loop carried operand.
int getFinalCycle() const
Return the last cycle in the finalized schedule.
LLVM_ABI void finalizeSchedule(SwingSchedulerDAG *SSD)
After the schedule has been formed, call this function to combine the instructions from the different...
Scheduling unit. This is a node in the scheduling DAG.
bool isInstr() const
Returns true if this SUnit refers to a machine instruction as opposed to an SDNode.
unsigned NodeNum
Entry # of node in the node vector.
void setInstr(MachineInstr *MI)
Assigns the instruction for the SUnit.
LLVM_ABI void removePred(const SDep &D)
Removes the specified edge as a pred of the current node if it exists.
bool isPred(const SUnit *N) const
Tests if node N is a predecessor of this node.
bool isBoundaryNode() const
Boundary nodes are placeholders for the boundary of the scheduling region.
bool hasPhysRegDefs
Has physreg defs that are being used.
SmallVector< SDep, 4 > Succs
All sunit successors.
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.
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
A ScheduleDAG for scheduling lists of MachineInstr.
DenseMap< MachineInstr *, SUnit * > MISUnitMap
After calling BuildSchedGraph, each machine instruction in the current scheduling region is mapped to...
virtual void finishBlock()
Cleans up after scheduling in the given block.
const CodeGenOptions & Opts
ScheduleDAGInstrs(MachineFunction &mf, const MachineLoopInfo *mli, bool RemoveKillFlags=false)
void buildSchedGraph(AAResults *AA, RegPressureTracker *RPTracker=nullptr, PressureDiffs *PDiffs=nullptr, LiveIntervals *LIS=nullptr, bool TrackLaneMasks=false)
Builds SUnits for the current region.
SUnit * getSUnit(MachineInstr *MI) const
Returns an existing SUnit for this MI, or nullptr.
const MachineLoopInfo * MLI
void dump() const override
LLVM_ABI void AddPred(SUnit *Y, SUnit *X)
Updates the topological ordering to accommodate an edge to be added from SUnit X to SUnit Y.
LLVM_ABI bool IsReachable(const SUnit *SU, const SUnit *TargetSU)
Checks if SU is reachable from TargetSU.
MachineRegisterInfo & MRI
Virtual/real register map.
const TargetInstrInfo * TII
Target instruction information.
std::vector< SUnit > SUnits
The scheduling units.
const TargetRegisterInfo * TRI
Target processor register info.
SUnit EntrySU
Special node for the region entry.
MachineFunction & MF
Machine function.
SUnit ExitSU
Special node for the region exit.
A vector that has set insertion semantics.
size_type size() const
Determine the number of elements in the SetVector.
void insert_range(Range &&R)
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
typename vector_type::const_iterator iterator
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
void clear()
Completely clear the SetVector.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
bool contains(const T &V) const
Check if the SmallSet contains the given element.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
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.
This class builds the dependence graph for the instructions in a loop, and attempts to schedule the i...
SwingSchedulerDAG(MachineFunction &MF, const MachineLoopInfo *MLI, MachineOptimizationRemarkEmitter *ORE, MachineLoop &L, LiveIntervals &lis, const RegisterClassInfo &rci, unsigned II, TargetInstrInfo::PipelinerLoopInfo *PLI, AliasAnalysis *AA, MachineDominatorTree *MDT=nullptr)
void applyInstrChange(MachineInstr *MI, SMSchedule &Schedule)
Apply changes to the instruction if needed.
const SwingSchedulerDDG * getDDG() const
void finishBlock() override
Clean up after the software pipeliner runs.
void fixupRegisterOverlaps(std::deque< SUnit * > &Instrs)
Attempt to fix the degenerate cases when the instruction serialization causes the register lifetimes ...
void schedule() override
We override the schedule function in ScheduleDAGInstrs to implement the scheduling part of the Swing ...
Register getInstrBaseReg(SUnit *SU) const
Return the new base register that was stored away for the changed instruction.
Represents a dependence between two instruction.
LLVM_ABI bool ignoreDependence(bool IgnoreAnti) const
Returns true for DDG nodes that we ignore when computing the cost functions.
This class provides APIs to retrieve edges from/to an SUnit node, with a particular focus on loop-car...
LLVM_ABI SwingSchedulerDDG(std::vector< SUnit > &SUnits, SUnit *EntrySU, SUnit *ExitSU, const LoopCarriedEdges &LCE)
LLVM_ABI ArrayRef< SUnit * > getExtraOutEdges(const SUnit *SU) const
LLVM_ABI const EdgesType & getInEdges(const SUnit *SU) const
LLVM_ABI bool isValidSchedule(const SMSchedule &Schedule) const
Check if Schedule doesn't violate the validation-only dependencies.
LLVM_ABI const EdgesType & getOutEdges(const SUnit *SU) const
Object returned by analyzeLoopForPipelining.
virtual bool shouldIgnoreForPipelining(const MachineInstr *MI) const =0
Return true if the given instruction should not be pipelined and should be ignored.
TargetInstrInfo - Interface to description of machine instruction set.
Primary interface to the complete machine description for the target machine.
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual void overridePipelinerPolicy(MachinePipelinerPolicy &Policy) const
Override generic software pipelining policy.
virtual bool enableMachinePipeliner() const
True if the subtarget should run MachinePipeliner.
virtual bool useDFAforSMS() const
Default to DFA for resource management, return false when target will use ProcResource in InstrSchedM...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const InstrItineraryData * getInstrItineraryData() const
getInstrItineraryData - Returns instruction itinerary data for the target or specific subtarget.
A Use represents the edge between a Value definition and its users.
LLVM Value Representation.
Wrapper class representing a virtual register or register unit.
constexpr bool isVirtualReg() const
constexpr MCRegUnit asMCRegUnit() const
constexpr Register asVirtualReg() const
The main class in the implementation of the target independent window scheduler.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
@ BasicBlock
Various leaf nodes.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< DefNode * > Def
NodeAddr< PhiNode * > Phi
NodeAddr< UseNode * > Use
std::set< NodeId > NodeSet
friend class Instruction
Iterator for Instructions in a `BasicBlock.
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
void stable_sort(R &&Range)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
constexpr NextUseDistance min(NextUseDistance A, NextUseDistance B)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
auto reverse(ContainerTy &&C)
@ Force
Turn off window algorithm.
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
RegState getRegState(const MachineOperand &RegOp)
Get all register state flags from machine operand RegOp.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
LLVM_ABI bool mayOverlapInLaterIter(const MachineInstr *BaseMI, const MachineInstr *OtherMI, const MachineBasicBlock *LoopBB, const MachineRegisterInfo &MRI, const TargetInstrInfo &TII)
Return true if BaseMI and OtherMI may access overlapping memory in a later iteration of the loop Loop...
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
LLVM_ABI char & MachinePipelinerID
This pass performs software pipelining on machine instructions.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
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.
constexpr bool valueOr(BoolOrDefault X, bool Default)
@ Increment
Incrementally increasing token ID.
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI Printable printVRegOrUnit(VirtRegOrUnit VRegOrUnit, const TargetRegisterInfo *TRI)
Create Printable object to print virtual registers and physical registers on a raw_ostream.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Cache the target analysis information about the loop.
std::unique_ptr< TargetInstrInfo::PipelinerLoopInfo > LoopPipelinerInfo
SmallVector< MachineOperand, 4 > BrCond
MachineInstr * LoopCompare
MachineInstr * LoopInductionVar
This class holds an SUnit corresponding to a memory operation and other information related to the in...
const Value * MemOpValue
The value of a memory operand.
SmallVector< const Value *, 2 > UnderlyingObjs
bool isTriviallyDisjoint(const SUnitWithMemInfo &Other) const
int64_t MemOpOffset
The offset of a memory operand.
bool IsAllIdentified
True if all the underlying objects are identified.
SUnitWithMemInfo(SUnit *SU)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
uint64_t FuncUnits
Bitmask representing a set of functional units.
static constexpr LaneBitmask getNone()
Represents loop-carried dependencies.
SmallSetVector< SUnit *, 8 > OrderDep
LLVM_ABI void dump(SUnit *SU, const TargetRegisterInfo *TRI, const MachineRegisterInfo *MRI) const
const OrderDep * getOrderDepOrNull(SUnit *Key) const
LLVM_ABI void modifySUnits(std::vector< SUnit > &SUnits, const TargetInstrInfo *TII)
Adds some edges to the original DAG that correspond to loop-carried dependencies.
Define a kind of processor resource that will be modeled by the scheduler.
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Machine model for scheduling, bundling, and heuristics.
const MCSchedClassDesc * getSchedClassDesc(unsigned SchedClassIdx) const
bool hasInstrSchedModel() const
Does this machine model include instruction-level scheduling.
const MCProcResourceDesc * getProcResource(unsigned ProcResourceIdx) const
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
std::vector< unsigned > MaxSetPressure
Map of max reg pressure indexed by pressure set ID, not class ID.