1 //===- MachinePipeliner.cpp - Machine Software Pipeliner Pass -------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // An implementation of the Swing Modulo Scheduling (SMS) software pipeliner.
11 // This SMS implementation is a target-independent back-end pass. When enabled,
12 // the pass runs just prior to the register allocation pass, while the machine
13 // IR is in SSA form. If software pipelining is successful, then the original
14 // loop is replaced by the optimized loop. The optimized loop contains one or
15 // more prolog blocks, the pipelined kernel, and one or more epilog blocks. If
16 // the instructions cannot be scheduled in a given MII, we increase the MII by
19 // The SMS implementation is an extension of the ScheduleDAGInstrs class. We
20 // represent loop carried dependences in the DAG as order edges to the Phi
21 // nodes. We also perform several passes over the DAG to eliminate unnecessary
22 // edges that inhibit the ability to pipeline. The implementation uses the
23 // DFAPacketizer class to compute the minimum initiation interval and the check
24 // where an instruction may be inserted in the pipelined schedule.
26 // In order for the SMS pass to work, several target specific hooks need to be
27 // implemented to get information about the loop structure and to rewrite
30 //===----------------------------------------------------------------------===//
32 #include "llvm/CodeGen/MachinePipeliner.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/BitVector.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/MapVector.h"
37 #include "llvm/ADT/PriorityQueue.h"
38 #include "llvm/ADT/SetOperations.h"
39 #include "llvm/ADT/SetVector.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/iterator_range.h"
45 #include "llvm/Analysis/AliasAnalysis.h"
46 #include "llvm/Analysis/CycleAnalysis.h"
47 #include "llvm/Analysis/MemoryLocation.h"
48 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/CodeGen/DFAPacketizer.h"
51 #include "llvm/CodeGen/LiveIntervals.h"
52 #include "llvm/CodeGen/MachineBasicBlock.h"
53 #include "llvm/CodeGen/MachineDominators.h"
54 #include "llvm/CodeGen/MachineFunction.h"
55 #include "llvm/CodeGen/MachineFunctionPass.h"
56 #include "llvm/CodeGen/MachineInstr.h"
57 #include "llvm/CodeGen/MachineInstrBuilder.h"
58 #include "llvm/CodeGen/MachineLoopInfo.h"
59 #include "llvm/CodeGen/MachineMemOperand.h"
60 #include "llvm/CodeGen/MachineOperand.h"
61 #include "llvm/CodeGen/MachineRegisterInfo.h"
62 #include "llvm/CodeGen/ModuloSchedule.h"
63 #include "llvm/CodeGen/RegisterPressure.h"
64 #include "llvm/CodeGen/ScheduleDAG.h"
65 #include "llvm/CodeGen/ScheduleDAGMutation.h"
66 #include "llvm/CodeGen/TargetOpcodes.h"
67 #include "llvm/CodeGen/TargetRegisterInfo.h"
68 #include "llvm/CodeGen/TargetSubtargetInfo.h"
69 #include "llvm/Config/llvm-config.h"
70 #include "llvm/IR/Attributes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/MC/LaneBitmask.h"
73 #include "llvm/MC/MCInstrDesc.h"
74 #include "llvm/MC/MCInstrItineraries.h"
75 #include "llvm/MC/MCRegisterInfo.h"
76 #include "llvm/Pass.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Compiler.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/MathExtras.h"
81 #include "llvm/Support/raw_ostream.h"
99 #define DEBUG_TYPE "pipeliner"
101 STATISTIC(NumTrytoPipeline
, "Number of loops that we attempt to pipeline");
102 STATISTIC(NumPipelined
, "Number of loops software pipelined");
103 STATISTIC(NumNodeOrderIssues
, "Number of node order issues found");
104 STATISTIC(NumFailBranch
, "Pipeliner abort due to unknown branch");
105 STATISTIC(NumFailLoop
, "Pipeliner abort due to unsupported loop");
106 STATISTIC(NumFailPreheader
, "Pipeliner abort due to missing preheader");
107 STATISTIC(NumFailLargeMaxMII
, "Pipeliner abort due to MaxMII too large");
108 STATISTIC(NumFailZeroMII
, "Pipeliner abort due to zero MII");
109 STATISTIC(NumFailNoSchedule
, "Pipeliner abort due to no schedule found");
110 STATISTIC(NumFailZeroStage
, "Pipeliner abort due to zero stage");
111 STATISTIC(NumFailLargeMaxStage
, "Pipeliner abort due to too many stages");
113 /// A command line option to turn software pipelining on or off.
114 static cl::opt
<bool> EnableSWP("enable-pipeliner", cl::Hidden
, cl::init(true),
115 cl::desc("Enable Software Pipelining"));
117 /// A command line option to enable SWP at -Os.
118 static cl::opt
<bool> EnableSWPOptSize("enable-pipeliner-opt-size",
119 cl::desc("Enable SWP at Os."), cl::Hidden
,
122 /// A command line argument to limit minimum initial interval for pipelining.
123 static cl::opt
<int> SwpMaxMii("pipeliner-max-mii",
124 cl::desc("Size limit for the MII."),
125 cl::Hidden
, cl::init(27));
127 /// A command line argument to force pipeliner to use specified initial
129 static cl::opt
<int> SwpForceII("pipeliner-force-ii",
130 cl::desc("Force pipeliner to use specified II."),
131 cl::Hidden
, cl::init(-1));
133 /// A command line argument to limit the number of stages in the pipeline.
135 SwpMaxStages("pipeliner-max-stages",
136 cl::desc("Maximum stages allowed in the generated scheduled."),
137 cl::Hidden
, cl::init(3));
139 /// A command line option to disable the pruning of chain dependences due to
140 /// an unrelated Phi.
142 SwpPruneDeps("pipeliner-prune-deps",
143 cl::desc("Prune dependences between unrelated Phi nodes."),
144 cl::Hidden
, cl::init(true));
146 /// A command line option to disable the pruning of loop carried order
149 SwpPruneLoopCarried("pipeliner-prune-loop-carried",
150 cl::desc("Prune loop carried order dependences."),
151 cl::Hidden
, cl::init(true));
154 static cl::opt
<int> SwpLoopLimit("pipeliner-max", cl::Hidden
, cl::init(-1));
157 static cl::opt
<bool> SwpIgnoreRecMII("pipeliner-ignore-recmii",
159 cl::desc("Ignore RecMII"));
161 static cl::opt
<bool> SwpShowResMask("pipeliner-show-mask", cl::Hidden
,
163 static cl::opt
<bool> SwpDebugResource("pipeliner-dbg-res", cl::Hidden
,
166 static cl::opt
<bool> EmitTestAnnotations(
167 "pipeliner-annotate-for-testing", cl::Hidden
, cl::init(false),
168 cl::desc("Instead of emitting the pipelined code, annotate instructions "
169 "with the generated schedule for feeding into the "
170 "-modulo-schedule-test pass"));
172 static cl::opt
<bool> ExperimentalCodeGen(
173 "pipeliner-experimental-cg", cl::Hidden
, cl::init(false),
175 "Use the experimental peeling code generator for software pipelining"));
179 // A command line option to enable the CopyToPhi DAG mutation.
180 cl::opt
<bool> SwpEnableCopyToPhi("pipeliner-enable-copytophi", cl::ReallyHidden
,
182 cl::desc("Enable CopyToPhi DAG Mutation"));
184 /// A command line argument to force pipeliner to use specified issue
186 cl::opt
<int> SwpForceIssueWidth(
187 "pipeliner-force-issue-width",
188 cl::desc("Force pipeliner to use specified issue width."), cl::Hidden
,
191 } // end namespace llvm
193 unsigned SwingSchedulerDAG::Circuits::MaxPaths
= 5;
194 char MachinePipeliner::ID
= 0;
196 int MachinePipeliner::NumTries
= 0;
198 char &llvm::MachinePipelinerID
= MachinePipeliner::ID
;
200 INITIALIZE_PASS_BEGIN(MachinePipeliner
, DEBUG_TYPE
,
201 "Modulo Software Pipelining", false, false)
202 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
203 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo
)
204 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree
)
205 INITIALIZE_PASS_DEPENDENCY(LiveIntervals
)
206 INITIALIZE_PASS_END(MachinePipeliner
, DEBUG_TYPE
,
207 "Modulo Software Pipelining", false, false)
209 /// The "main" function for implementing Swing Modulo Scheduling.
210 bool MachinePipeliner::runOnMachineFunction(MachineFunction
&mf
) {
211 if (skipFunction(mf
.getFunction()))
217 if (mf
.getFunction().getAttributes().hasFnAttr(Attribute::OptimizeForSize
) &&
218 !EnableSWPOptSize
.getPosition())
221 if (!mf
.getSubtarget().enableMachinePipeliner())
224 // Cannot pipeline loops without instruction itineraries if we are using
225 // DFA for the pipeliner.
226 if (mf
.getSubtarget().useDFAforSMS() &&
227 (!mf
.getSubtarget().getInstrItineraryData() ||
228 mf
.getSubtarget().getInstrItineraryData()->isEmpty()))
232 MLI
= &getAnalysis
<MachineLoopInfo
>();
233 MDT
= &getAnalysis
<MachineDominatorTree
>();
234 ORE
= &getAnalysis
<MachineOptimizationRemarkEmitterPass
>().getORE();
235 TII
= MF
->getSubtarget().getInstrInfo();
236 RegClassInfo
.runOnMachineFunction(*MF
);
238 for (const auto &L
: *MLI
)
244 /// Attempt to perform the SMS algorithm on the specified loop. This function is
245 /// the main entry point for the algorithm. The function identifies candidate
246 /// loops, calculates the minimum initiation interval, and attempts to schedule
248 bool MachinePipeliner::scheduleLoop(MachineLoop
&L
) {
249 bool Changed
= false;
250 for (const auto &InnerLoop
: L
)
251 Changed
|= scheduleLoop(*InnerLoop
);
254 // Stop trying after reaching the limit (if any).
255 int Limit
= SwpLoopLimit
;
257 if (NumTries
>= SwpLoopLimit
)
263 setPragmaPipelineOptions(L
);
264 if (!canPipelineLoop(L
)) {
265 LLVM_DEBUG(dbgs() << "\n!!! Can not pipeline loop.\n");
267 return MachineOptimizationRemarkMissed(DEBUG_TYPE
, "canPipelineLoop",
268 L
.getStartLoc(), L
.getHeader())
269 << "Failed to pipeline loop";
272 LI
.LoopPipelinerInfo
.reset();
278 Changed
= swingModuloScheduler(L
);
280 LI
.LoopPipelinerInfo
.reset();
284 void MachinePipeliner::setPragmaPipelineOptions(MachineLoop
&L
) {
285 // Reset the pragma for the next loop in iteration.
286 disabledByPragma
= false;
289 MachineBasicBlock
*LBLK
= L
.getTopBlock();
294 const BasicBlock
*BBLK
= LBLK
->getBasicBlock();
298 const Instruction
*TI
= BBLK
->getTerminator();
302 MDNode
*LoopID
= TI
->getMetadata(LLVMContext::MD_loop
);
303 if (LoopID
== nullptr)
306 assert(LoopID
->getNumOperands() > 0 && "requires atleast one operand");
307 assert(LoopID
->getOperand(0) == LoopID
&& "invalid loop");
309 for (unsigned i
= 1, e
= LoopID
->getNumOperands(); i
< e
; ++i
) {
310 MDNode
*MD
= dyn_cast
<MDNode
>(LoopID
->getOperand(i
));
315 MDString
*S
= dyn_cast
<MDString
>(MD
->getOperand(0));
320 if (S
->getString() == "llvm.loop.pipeline.initiationinterval") {
321 assert(MD
->getNumOperands() == 2 &&
322 "Pipeline initiation interval hint metadata should have two operands.");
324 mdconst::extract
<ConstantInt
>(MD
->getOperand(1))->getZExtValue();
325 assert(II_setByPragma
>= 1 && "Pipeline initiation interval must be positive.");
326 } else if (S
->getString() == "llvm.loop.pipeline.disable") {
327 disabledByPragma
= true;
332 /// Return true if the loop can be software pipelined. The algorithm is
333 /// restricted to loops with a single basic block. Make sure that the
334 /// branch in the loop can be analyzed.
335 bool MachinePipeliner::canPipelineLoop(MachineLoop
&L
) {
336 if (L
.getNumBlocks() != 1) {
338 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "canPipelineLoop",
339 L
.getStartLoc(), L
.getHeader())
340 << "Not a single basic block: "
341 << ore::NV("NumBlocks", L
.getNumBlocks());
346 if (disabledByPragma
) {
348 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "canPipelineLoop",
349 L
.getStartLoc(), L
.getHeader())
350 << "Disabled by Pragma.";
355 // Check if the branch can't be understood because we can't do pipelining
356 // if that's the case.
360 if (TII
->analyzeBranch(*L
.getHeader(), LI
.TBB
, LI
.FBB
, LI
.BrCond
)) {
361 LLVM_DEBUG(dbgs() << "Unable to analyzeBranch, can NOT pipeline Loop\n");
364 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "canPipelineLoop",
365 L
.getStartLoc(), L
.getHeader())
366 << "The branch can't be understood";
371 LI
.LoopInductionVar
= nullptr;
372 LI
.LoopCompare
= nullptr;
373 LI
.LoopPipelinerInfo
= TII
->analyzeLoopForPipelining(L
.getTopBlock());
374 if (!LI
.LoopPipelinerInfo
) {
375 LLVM_DEBUG(dbgs() << "Unable to analyzeLoop, can NOT pipeline Loop\n");
378 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "canPipelineLoop",
379 L
.getStartLoc(), L
.getHeader())
380 << "The loop structure is not supported";
385 if (!L
.getLoopPreheader()) {
386 LLVM_DEBUG(dbgs() << "Preheader not found, can NOT pipeline Loop\n");
389 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE
, "canPipelineLoop",
390 L
.getStartLoc(), L
.getHeader())
391 << "No loop preheader found";
396 // Remove any subregisters from inputs to phi nodes.
397 preprocessPhiNodes(*L
.getHeader());
401 void MachinePipeliner::preprocessPhiNodes(MachineBasicBlock
&B
) {
402 MachineRegisterInfo
&MRI
= MF
->getRegInfo();
403 SlotIndexes
&Slots
= *getAnalysis
<LiveIntervals
>().getSlotIndexes();
405 for (MachineInstr
&PI
: B
.phis()) {
406 MachineOperand
&DefOp
= PI
.getOperand(0);
407 assert(DefOp
.getSubReg() == 0);
408 auto *RC
= MRI
.getRegClass(DefOp
.getReg());
410 for (unsigned i
= 1, n
= PI
.getNumOperands(); i
!= n
; i
+= 2) {
411 MachineOperand
&RegOp
= PI
.getOperand(i
);
412 if (RegOp
.getSubReg() == 0)
415 // If the operand uses a subregister, replace it with a new register
416 // without subregisters, and generate a copy to the new register.
417 Register NewReg
= MRI
.createVirtualRegister(RC
);
418 MachineBasicBlock
&PredB
= *PI
.getOperand(i
+1).getMBB();
419 MachineBasicBlock::iterator At
= PredB
.getFirstTerminator();
420 const DebugLoc
&DL
= PredB
.findDebugLoc(At
);
421 auto Copy
= BuildMI(PredB
, At
, DL
, TII
->get(TargetOpcode::COPY
), NewReg
)
422 .addReg(RegOp
.getReg(), getRegState(RegOp
),
424 Slots
.insertMachineInstrInMaps(*Copy
);
425 RegOp
.setReg(NewReg
);
431 /// The SMS algorithm consists of the following main steps:
432 /// 1. Computation and analysis of the dependence graph.
433 /// 2. Ordering of the nodes (instructions).
434 /// 3. Attempt to Schedule the loop.
435 bool MachinePipeliner::swingModuloScheduler(MachineLoop
&L
) {
436 assert(L
.getBlocks().size() == 1 && "SMS works on single blocks only.");
438 SwingSchedulerDAG
SMS(*this, L
, getAnalysis
<LiveIntervals
>(), RegClassInfo
,
439 II_setByPragma
, LI
.LoopPipelinerInfo
.get());
441 MachineBasicBlock
*MBB
= L
.getHeader();
442 // The kernel should not include any terminator instructions. These
443 // will be added back later.
446 // Compute the number of 'real' instructions in the basic block by
447 // ignoring terminators.
448 unsigned size
= MBB
->size();
449 for (MachineBasicBlock::iterator I
= MBB
->getFirstTerminator(),
450 E
= MBB
->instr_end();
454 SMS
.enterRegion(MBB
, MBB
->begin(), MBB
->getFirstTerminator(), size
);
459 return SMS
.hasNewSchedule();
462 void MachinePipeliner::getAnalysisUsage(AnalysisUsage
&AU
) const {
463 AU
.addRequired
<AAResultsWrapperPass
>();
464 AU
.addPreserved
<AAResultsWrapperPass
>();
465 AU
.addRequired
<MachineLoopInfo
>();
466 AU
.addRequired
<MachineDominatorTree
>();
467 AU
.addRequired
<LiveIntervals
>();
468 AU
.addRequired
<MachineOptimizationRemarkEmitterPass
>();
469 MachineFunctionPass::getAnalysisUsage(AU
);
472 void SwingSchedulerDAG::setMII(unsigned ResMII
, unsigned RecMII
) {
475 else if (II_setByPragma
> 0)
476 MII
= II_setByPragma
;
478 MII
= std::max(ResMII
, RecMII
);
481 void SwingSchedulerDAG::setMAX_II() {
484 else if (II_setByPragma
> 0)
485 MAX_II
= II_setByPragma
;
490 /// We override the schedule function in ScheduleDAGInstrs to implement the
491 /// scheduling part of the Swing Modulo Scheduling algorithm.
492 void SwingSchedulerDAG::schedule() {
493 AliasAnalysis
*AA
= &Pass
.getAnalysis
<AAResultsWrapperPass
>().getAAResults();
495 addLoopCarriedDependences(AA
);
496 updatePhiDependences();
497 Topo
.InitDAGTopologicalSorting();
502 NodeSetType NodeSets
;
503 findCircuits(NodeSets
);
504 NodeSetType Circuits
= NodeSets
;
506 // Calculate the MII.
507 unsigned ResMII
= calculateResMII();
508 unsigned RecMII
= calculateRecMII(NodeSets
);
512 // This flag is used for testing and can cause correctness problems.
516 setMII(ResMII
, RecMII
);
519 LLVM_DEBUG(dbgs() << "MII = " << MII
<< " MAX_II = " << MAX_II
520 << " (rec=" << RecMII
<< ", res=" << ResMII
<< ")\n");
522 // Can't schedule a loop without a valid MII.
524 LLVM_DEBUG(dbgs() << "Invalid Minimal Initiation Interval: 0\n");
526 Pass
.ORE
->emit([&]() {
527 return MachineOptimizationRemarkAnalysis(
528 DEBUG_TYPE
, "schedule", Loop
.getStartLoc(), Loop
.getHeader())
529 << "Invalid Minimal Initiation Interval: 0";
534 // Don't pipeline large loops.
535 if (SwpMaxMii
!= -1 && (int)MII
> SwpMaxMii
) {
536 LLVM_DEBUG(dbgs() << "MII > " << SwpMaxMii
537 << ", we don't pipeline large loops\n");
538 NumFailLargeMaxMII
++;
539 Pass
.ORE
->emit([&]() {
540 return MachineOptimizationRemarkAnalysis(
541 DEBUG_TYPE
, "schedule", Loop
.getStartLoc(), Loop
.getHeader())
542 << "Minimal Initiation Interval too large: "
543 << ore::NV("MII", (int)MII
) << " > "
544 << ore::NV("SwpMaxMii", SwpMaxMii
) << "."
545 << "Refer to -pipeliner-max-mii.";
550 computeNodeFunctions(NodeSets
);
552 registerPressureFilter(NodeSets
);
554 colocateNodeSets(NodeSets
);
556 checkNodeSets(NodeSets
);
559 for (auto &I
: NodeSets
) {
560 dbgs() << " Rec NodeSet ";
565 llvm::stable_sort(NodeSets
, std::greater
<NodeSet
>());
567 groupRemainingNodes(NodeSets
);
569 removeDuplicateNodes(NodeSets
);
572 for (auto &I
: NodeSets
) {
573 dbgs() << " NodeSet ";
578 computeNodeOrder(NodeSets
);
580 // check for node order issues
581 checkValidNodeOrder(Circuits
);
583 SMSchedule
Schedule(Pass
.MF
, this);
584 Scheduled
= schedulePipeline(Schedule
);
587 LLVM_DEBUG(dbgs() << "No schedule found, return\n");
589 Pass
.ORE
->emit([&]() {
590 return MachineOptimizationRemarkAnalysis(
591 DEBUG_TYPE
, "schedule", Loop
.getStartLoc(), Loop
.getHeader())
592 << "Unable to find schedule";
597 unsigned numStages
= Schedule
.getMaxStageCount();
598 // No need to generate pipeline if there are no overlapped iterations.
599 if (numStages
== 0) {
600 LLVM_DEBUG(dbgs() << "No overlapped iterations, skip.\n");
602 Pass
.ORE
->emit([&]() {
603 return MachineOptimizationRemarkAnalysis(
604 DEBUG_TYPE
, "schedule", Loop
.getStartLoc(), Loop
.getHeader())
605 << "No need to pipeline - no overlapped iterations in schedule.";
609 // Check that the maximum stage count is less than user-defined limit.
610 if (SwpMaxStages
> -1 && (int)numStages
> SwpMaxStages
) {
611 LLVM_DEBUG(dbgs() << "numStages:" << numStages
<< ">" << SwpMaxStages
612 << " : too many stages, abort\n");
613 NumFailLargeMaxStage
++;
614 Pass
.ORE
->emit([&]() {
615 return MachineOptimizationRemarkAnalysis(
616 DEBUG_TYPE
, "schedule", Loop
.getStartLoc(), Loop
.getHeader())
617 << "Too many stages in schedule: "
618 << ore::NV("numStages", (int)numStages
) << " > "
619 << ore::NV("SwpMaxStages", SwpMaxStages
)
620 << ". Refer to -pipeliner-max-stages.";
625 Pass
.ORE
->emit([&]() {
626 return MachineOptimizationRemark(DEBUG_TYPE
, "schedule", Loop
.getStartLoc(),
628 << "Pipelined succesfully!";
631 // Generate the schedule as a ModuloSchedule.
632 DenseMap
<MachineInstr
*, int> Cycles
, Stages
;
633 std::vector
<MachineInstr
*> OrderedInsts
;
634 for (int Cycle
= Schedule
.getFirstCycle(); Cycle
<= Schedule
.getFinalCycle();
636 for (SUnit
*SU
: Schedule
.getInstructions(Cycle
)) {
637 OrderedInsts
.push_back(SU
->getInstr());
638 Cycles
[SU
->getInstr()] = Cycle
;
639 Stages
[SU
->getInstr()] = Schedule
.stageScheduled(SU
);
642 DenseMap
<MachineInstr
*, std::pair
<unsigned, int64_t>> NewInstrChanges
;
643 for (auto &KV
: NewMIs
) {
644 Cycles
[KV
.first
] = Cycles
[KV
.second
];
645 Stages
[KV
.first
] = Stages
[KV
.second
];
646 NewInstrChanges
[KV
.first
] = InstrChanges
[getSUnit(KV
.first
)];
649 ModuloSchedule
MS(MF
, &Loop
, std::move(OrderedInsts
), std::move(Cycles
),
651 if (EmitTestAnnotations
) {
652 assert(NewInstrChanges
.empty() &&
653 "Cannot serialize a schedule with InstrChanges!");
654 ModuloScheduleTestAnnotater
MSTI(MF
, MS
);
658 // The experimental code generator can't work if there are InstChanges.
659 if (ExperimentalCodeGen
&& NewInstrChanges
.empty()) {
660 PeelingModuloScheduleExpander
MSE(MF
, MS
, &LIS
);
663 ModuloScheduleExpander
MSE(MF
, MS
, LIS
, std::move(NewInstrChanges
));
670 /// Clean up after the software pipeliner runs.
671 void SwingSchedulerDAG::finishBlock() {
672 for (auto &KV
: NewMIs
)
673 MF
.deleteMachineInstr(KV
.second
);
676 // Call the superclass.
677 ScheduleDAGInstrs::finishBlock();
680 /// Return the register values for the operands of a Phi instruction.
681 /// This function assume the instruction is a Phi.
682 static void getPhiRegs(MachineInstr
&Phi
, MachineBasicBlock
*Loop
,
683 unsigned &InitVal
, unsigned &LoopVal
) {
684 assert(Phi
.isPHI() && "Expecting a Phi.");
688 for (unsigned i
= 1, e
= Phi
.getNumOperands(); i
!= e
; i
+= 2)
689 if (Phi
.getOperand(i
+ 1).getMBB() != Loop
)
690 InitVal
= Phi
.getOperand(i
).getReg();
692 LoopVal
= Phi
.getOperand(i
).getReg();
694 assert(InitVal
!= 0 && LoopVal
!= 0 && "Unexpected Phi structure.");
697 /// Return the Phi register value that comes the loop block.
698 static unsigned getLoopPhiReg(MachineInstr
&Phi
, MachineBasicBlock
*LoopBB
) {
699 for (unsigned i
= 1, e
= Phi
.getNumOperands(); i
!= e
; i
+= 2)
700 if (Phi
.getOperand(i
+ 1).getMBB() == LoopBB
)
701 return Phi
.getOperand(i
).getReg();
705 /// Return true if SUb can be reached from SUa following the chain edges.
706 static bool isSuccOrder(SUnit
*SUa
, SUnit
*SUb
) {
707 SmallPtrSet
<SUnit
*, 8> Visited
;
708 SmallVector
<SUnit
*, 8> Worklist
;
709 Worklist
.push_back(SUa
);
710 while (!Worklist
.empty()) {
711 const SUnit
*SU
= Worklist
.pop_back_val();
712 for (const auto &SI
: SU
->Succs
) {
713 SUnit
*SuccSU
= SI
.getSUnit();
714 if (SI
.getKind() == SDep::Order
) {
715 if (Visited
.count(SuccSU
))
719 Worklist
.push_back(SuccSU
);
720 Visited
.insert(SuccSU
);
727 /// Return true if the instruction causes a chain between memory
728 /// references before and after it.
729 static bool isDependenceBarrier(MachineInstr
&MI
) {
730 return MI
.isCall() || MI
.mayRaiseFPException() ||
731 MI
.hasUnmodeledSideEffects() ||
732 (MI
.hasOrderedMemoryRef() &&
733 (!MI
.mayLoad() || !MI
.isDereferenceableInvariantLoad()));
736 /// Return the underlying objects for the memory references of an instruction.
737 /// This function calls the code in ValueTracking, but first checks that the
738 /// instruction has a memory operand.
739 static void getUnderlyingObjects(const MachineInstr
*MI
,
740 SmallVectorImpl
<const Value
*> &Objs
) {
741 if (!MI
->hasOneMemOperand())
743 MachineMemOperand
*MM
= *MI
->memoperands_begin();
746 getUnderlyingObjects(MM
->getValue(), Objs
);
747 for (const Value
*V
: Objs
) {
748 if (!isIdentifiedObject(V
)) {
756 /// Add a chain edge between a load and store if the store can be an
757 /// alias of the load on a subsequent iteration, i.e., a loop carried
758 /// dependence. This code is very similar to the code in ScheduleDAGInstrs
759 /// but that code doesn't create loop carried dependences.
760 void SwingSchedulerDAG::addLoopCarriedDependences(AliasAnalysis
*AA
) {
761 MapVector
<const Value
*, SmallVector
<SUnit
*, 4>> PendingLoads
;
762 Value
*UnknownValue
=
763 UndefValue::get(Type::getVoidTy(MF
.getFunction().getContext()));
764 for (auto &SU
: SUnits
) {
765 MachineInstr
&MI
= *SU
.getInstr();
766 if (isDependenceBarrier(MI
))
767 PendingLoads
.clear();
768 else if (MI
.mayLoad()) {
769 SmallVector
<const Value
*, 4> Objs
;
770 ::getUnderlyingObjects(&MI
, Objs
);
772 Objs
.push_back(UnknownValue
);
773 for (const auto *V
: Objs
) {
774 SmallVector
<SUnit
*, 4> &SUs
= PendingLoads
[V
];
777 } else if (MI
.mayStore()) {
778 SmallVector
<const Value
*, 4> Objs
;
779 ::getUnderlyingObjects(&MI
, Objs
);
781 Objs
.push_back(UnknownValue
);
782 for (const auto *V
: Objs
) {
783 MapVector
<const Value
*, SmallVector
<SUnit
*, 4>>::iterator I
=
784 PendingLoads
.find(V
);
785 if (I
== PendingLoads
.end())
787 for (auto *Load
: I
->second
) {
788 if (isSuccOrder(Load
, &SU
))
790 MachineInstr
&LdMI
= *Load
->getInstr();
791 // First, perform the cheaper check that compares the base register.
792 // If they are the same and the load offset is less than the store
793 // offset, then mark the dependence as loop carried potentially.
794 const MachineOperand
*BaseOp1
, *BaseOp2
;
795 int64_t Offset1
, Offset2
;
796 bool Offset1IsScalable
, Offset2IsScalable
;
797 if (TII
->getMemOperandWithOffset(LdMI
, BaseOp1
, Offset1
,
798 Offset1IsScalable
, TRI
) &&
799 TII
->getMemOperandWithOffset(MI
, BaseOp2
, Offset2
,
800 Offset2IsScalable
, TRI
)) {
801 if (BaseOp1
->isIdenticalTo(*BaseOp2
) &&
802 Offset1IsScalable
== Offset2IsScalable
&&
803 (int)Offset1
< (int)Offset2
) {
804 assert(TII
->areMemAccessesTriviallyDisjoint(LdMI
, MI
) &&
805 "What happened to the chain edge?");
806 SDep
Dep(Load
, SDep::Barrier
);
812 // Second, the more expensive check that uses alias analysis on the
813 // base registers. If they alias, and the load offset is less than
814 // the store offset, the mark the dependence as loop carried.
816 SDep
Dep(Load
, SDep::Barrier
);
821 MachineMemOperand
*MMO1
= *LdMI
.memoperands_begin();
822 MachineMemOperand
*MMO2
= *MI
.memoperands_begin();
823 if (!MMO1
->getValue() || !MMO2
->getValue()) {
824 SDep
Dep(Load
, SDep::Barrier
);
829 if (MMO1
->getValue() == MMO2
->getValue() &&
830 MMO1
->getOffset() <= MMO2
->getOffset()) {
831 SDep
Dep(Load
, SDep::Barrier
);
837 MemoryLocation::getAfter(MMO1
->getValue(), MMO1
->getAAInfo()),
838 MemoryLocation::getAfter(MMO2
->getValue(),
839 MMO2
->getAAInfo()))) {
840 SDep
Dep(Load
, SDep::Barrier
);
850 /// Update the phi dependences to the DAG because ScheduleDAGInstrs no longer
851 /// processes dependences for PHIs. This function adds true dependences
852 /// from a PHI to a use, and a loop carried dependence from the use to the
853 /// PHI. The loop carried dependence is represented as an anti dependence
854 /// edge. This function also removes chain dependences between unrelated
856 void SwingSchedulerDAG::updatePhiDependences() {
857 SmallVector
<SDep
, 4> RemoveDeps
;
858 const TargetSubtargetInfo
&ST
= MF
.getSubtarget
<TargetSubtargetInfo
>();
860 // Iterate over each DAG node.
861 for (SUnit
&I
: SUnits
) {
863 // Set to true if the instruction has an operand defined by a Phi.
864 unsigned HasPhiUse
= 0;
865 unsigned HasPhiDef
= 0;
866 MachineInstr
*MI
= I
.getInstr();
867 // Iterate over each operand, and we process the definitions.
868 for (const MachineOperand
&MO
: MI
->operands()) {
871 Register Reg
= MO
.getReg();
873 // If the register is used by a Phi, then create an anti dependence.
874 for (MachineRegisterInfo::use_instr_iterator
875 UI
= MRI
.use_instr_begin(Reg
),
876 UE
= MRI
.use_instr_end();
878 MachineInstr
*UseMI
= &*UI
;
879 SUnit
*SU
= getSUnit(UseMI
);
880 if (SU
!= nullptr && UseMI
->isPHI()) {
882 SDep
Dep(SU
, SDep::Anti
, Reg
);
887 // Add a chain edge to a dependent Phi that isn't an existing
889 if (SU
->NodeNum
< I
.NodeNum
&& !I
.isPred(SU
))
890 I
.addPred(SDep(SU
, SDep::Barrier
));
894 } else if (MO
.isUse()) {
895 // If the register is defined by a Phi, then create a true dependence.
896 MachineInstr
*DefMI
= MRI
.getUniqueVRegDef(Reg
);
897 if (DefMI
== nullptr)
899 SUnit
*SU
= getSUnit(DefMI
);
900 if (SU
!= nullptr && DefMI
->isPHI()) {
902 SDep
Dep(SU
, SDep::Data
, Reg
);
904 ST
.adjustSchedDependency(SU
, 0, &I
, MO
.getOperandNo(), Dep
);
908 // Add a chain edge to a dependent Phi that isn't an existing
910 if (SU
->NodeNum
< I
.NodeNum
&& !I
.isPred(SU
))
911 I
.addPred(SDep(SU
, SDep::Barrier
));
916 // Remove order dependences from an unrelated Phi.
919 for (auto &PI
: I
.Preds
) {
920 MachineInstr
*PMI
= PI
.getSUnit()->getInstr();
921 if (PMI
->isPHI() && PI
.getKind() == SDep::Order
) {
922 if (I
.getInstr()->isPHI()) {
923 if (PMI
->getOperand(0).getReg() == HasPhiUse
)
925 if (getLoopPhiReg(*PMI
, PMI
->getParent()) == HasPhiDef
)
928 RemoveDeps
.push_back(PI
);
931 for (int i
= 0, e
= RemoveDeps
.size(); i
!= e
; ++i
)
932 I
.removePred(RemoveDeps
[i
]);
936 /// Iterate over each DAG node and see if we can change any dependences
937 /// in order to reduce the recurrence MII.
938 void SwingSchedulerDAG::changeDependences() {
939 // See if an instruction can use a value from the previous iteration.
940 // If so, we update the base and offset of the instruction and change
942 for (SUnit
&I
: SUnits
) {
943 unsigned BasePos
= 0, OffsetPos
= 0, NewBase
= 0;
944 int64_t NewOffset
= 0;
945 if (!canUseLastOffsetValue(I
.getInstr(), BasePos
, OffsetPos
, NewBase
,
949 // Get the MI and SUnit for the instruction that defines the original base.
950 Register OrigBase
= I
.getInstr()->getOperand(BasePos
).getReg();
951 MachineInstr
*DefMI
= MRI
.getUniqueVRegDef(OrigBase
);
954 SUnit
*DefSU
= getSUnit(DefMI
);
957 // Get the MI and SUnit for the instruction that defins the new base.
958 MachineInstr
*LastMI
= MRI
.getUniqueVRegDef(NewBase
);
961 SUnit
*LastSU
= getSUnit(LastMI
);
965 if (Topo
.IsReachable(&I
, LastSU
))
968 // Remove the dependence. The value now depends on a prior iteration.
969 SmallVector
<SDep
, 4> Deps
;
970 for (const SDep
&P
: I
.Preds
)
971 if (P
.getSUnit() == DefSU
)
973 for (int i
= 0, e
= Deps
.size(); i
!= e
; i
++) {
974 Topo
.RemovePred(&I
, Deps
[i
].getSUnit());
975 I
.removePred(Deps
[i
]);
977 // Remove the chain dependence between the instructions.
979 for (auto &P
: LastSU
->Preds
)
980 if (P
.getSUnit() == &I
&& P
.getKind() == SDep::Order
)
982 for (int i
= 0, e
= Deps
.size(); i
!= e
; i
++) {
983 Topo
.RemovePred(LastSU
, Deps
[i
].getSUnit());
984 LastSU
->removePred(Deps
[i
]);
987 // Add a dependence between the new instruction and the instruction
988 // that defines the new base.
989 SDep
Dep(&I
, SDep::Anti
, NewBase
);
990 Topo
.AddPred(LastSU
, &I
);
991 LastSU
->addPred(Dep
);
993 // Remember the base and offset information so that we can update the
994 // instruction during code generation.
995 InstrChanges
[&I
] = std::make_pair(NewBase
, NewOffset
);
1001 // FuncUnitSorter - Comparison operator used to sort instructions by
1002 // the number of functional unit choices.
1003 struct FuncUnitSorter
{
1004 const InstrItineraryData
*InstrItins
;
1005 const MCSubtargetInfo
*STI
;
1006 DenseMap
<InstrStage::FuncUnits
, unsigned> Resources
;
1008 FuncUnitSorter(const TargetSubtargetInfo
&TSI
)
1009 : InstrItins(TSI
.getInstrItineraryData()), STI(&TSI
) {}
1011 // Compute the number of functional unit alternatives needed
1012 // at each stage, and take the minimum value. We prioritize the
1013 // instructions by the least number of choices first.
1014 unsigned minFuncUnits(const MachineInstr
*Inst
,
1015 InstrStage::FuncUnits
&F
) const {
1016 unsigned SchedClass
= Inst
->getDesc().getSchedClass();
1017 unsigned min
= UINT_MAX
;
1018 if (InstrItins
&& !InstrItins
->isEmpty()) {
1019 for (const InstrStage
&IS
:
1020 make_range(InstrItins
->beginStage(SchedClass
),
1021 InstrItins
->endStage(SchedClass
))) {
1022 InstrStage::FuncUnits funcUnits
= IS
.getUnits();
1023 unsigned numAlternatives
= llvm::popcount(funcUnits
);
1024 if (numAlternatives
< min
) {
1025 min
= numAlternatives
;
1031 if (STI
&& STI
->getSchedModel().hasInstrSchedModel()) {
1032 const MCSchedClassDesc
*SCDesc
=
1033 STI
->getSchedModel().getSchedClassDesc(SchedClass
);
1034 if (!SCDesc
->isValid())
1035 // No valid Schedule Class Desc for schedClass, should be
1036 // Pseudo/PostRAPseudo
1039 for (const MCWriteProcResEntry
&PRE
:
1040 make_range(STI
->getWriteProcResBegin(SCDesc
),
1041 STI
->getWriteProcResEnd(SCDesc
))) {
1044 const MCProcResourceDesc
*ProcResource
=
1045 STI
->getSchedModel().getProcResource(PRE
.ProcResourceIdx
);
1046 unsigned NumUnits
= ProcResource
->NumUnits
;
1047 if (NumUnits
< min
) {
1049 F
= PRE
.ProcResourceIdx
;
1054 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1057 // Compute the critical resources needed by the instruction. This
1058 // function records the functional units needed by instructions that
1059 // must use only one functional unit. We use this as a tie breaker
1060 // for computing the resource MII. The instrutions that require
1061 // the same, highly used, functional unit have high priority.
1062 void calcCriticalResources(MachineInstr
&MI
) {
1063 unsigned SchedClass
= MI
.getDesc().getSchedClass();
1064 if (InstrItins
&& !InstrItins
->isEmpty()) {
1065 for (const InstrStage
&IS
:
1066 make_range(InstrItins
->beginStage(SchedClass
),
1067 InstrItins
->endStage(SchedClass
))) {
1068 InstrStage::FuncUnits FuncUnits
= IS
.getUnits();
1069 if (llvm::popcount(FuncUnits
) == 1)
1070 Resources
[FuncUnits
]++;
1074 if (STI
&& STI
->getSchedModel().hasInstrSchedModel()) {
1075 const MCSchedClassDesc
*SCDesc
=
1076 STI
->getSchedModel().getSchedClassDesc(SchedClass
);
1077 if (!SCDesc
->isValid())
1078 // No valid Schedule Class Desc for schedClass, should be
1079 // Pseudo/PostRAPseudo
1082 for (const MCWriteProcResEntry
&PRE
:
1083 make_range(STI
->getWriteProcResBegin(SCDesc
),
1084 STI
->getWriteProcResEnd(SCDesc
))) {
1087 Resources
[PRE
.ProcResourceIdx
]++;
1091 llvm_unreachable("Should have non-empty InstrItins or hasInstrSchedModel!");
1094 /// Return true if IS1 has less priority than IS2.
1095 bool operator()(const MachineInstr
*IS1
, const MachineInstr
*IS2
) const {
1096 InstrStage::FuncUnits F1
= 0, F2
= 0;
1097 unsigned MFUs1
= minFuncUnits(IS1
, F1
);
1098 unsigned MFUs2
= minFuncUnits(IS2
, F2
);
1100 return Resources
.lookup(F1
) < Resources
.lookup(F2
);
1101 return MFUs1
> MFUs2
;
1105 } // end anonymous namespace
1107 /// Calculate the resource constrained minimum initiation interval for the
1108 /// specified loop. We use the DFA to model the resources needed for
1109 /// each instruction, and we ignore dependences. A different DFA is created
1110 /// for each cycle that is required. When adding a new instruction, we attempt
1111 /// to add it to each existing DFA, until a legal space is found. If the
1112 /// instruction cannot be reserved in an existing DFA, we create a new one.
1113 unsigned SwingSchedulerDAG::calculateResMII() {
1114 LLVM_DEBUG(dbgs() << "calculateResMII:\n");
1115 ResourceManager
RM(&MF
.getSubtarget(), this);
1116 return RM
.calculateResMII();
1119 /// Calculate the recurrence-constrainted minimum initiation interval.
1120 /// Iterate over each circuit. Compute the delay(c) and distance(c)
1121 /// for each circuit. The II needs to satisfy the inequality
1122 /// delay(c) - II*distance(c) <= 0. For each circuit, choose the smallest
1123 /// II that satisfies the inequality, and the RecMII is the maximum
1124 /// of those values.
1125 unsigned SwingSchedulerDAG::calculateRecMII(NodeSetType
&NodeSets
) {
1126 unsigned RecMII
= 0;
1128 for (NodeSet
&Nodes
: NodeSets
) {
1132 unsigned Delay
= Nodes
.getLatency();
1133 unsigned Distance
= 1;
1135 // ii = ceil(delay / distance)
1136 unsigned CurMII
= (Delay
+ Distance
- 1) / Distance
;
1137 Nodes
.setRecMII(CurMII
);
1138 if (CurMII
> RecMII
)
1145 /// Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1146 /// but we do this to find the circuits, and then change them back.
1147 static void swapAntiDependences(std::vector
<SUnit
> &SUnits
) {
1148 SmallVector
<std::pair
<SUnit
*, SDep
>, 8> DepsAdded
;
1149 for (SUnit
&SU
: SUnits
) {
1150 for (SDep
&Pred
: SU
.Preds
)
1151 if (Pred
.getKind() == SDep::Anti
)
1152 DepsAdded
.push_back(std::make_pair(&SU
, Pred
));
1154 for (std::pair
<SUnit
*, SDep
> &P
: DepsAdded
) {
1155 // Remove this anti dependency and add one in the reverse direction.
1156 SUnit
*SU
= P
.first
;
1158 SUnit
*TargetSU
= D
.getSUnit();
1159 unsigned Reg
= D
.getReg();
1160 unsigned Lat
= D
.getLatency();
1162 SDep
Dep(SU
, SDep::Anti
, Reg
);
1163 Dep
.setLatency(Lat
);
1164 TargetSU
->addPred(Dep
);
1168 /// Create the adjacency structure of the nodes in the graph.
1169 void SwingSchedulerDAG::Circuits::createAdjacencyStructure(
1170 SwingSchedulerDAG
*DAG
) {
1171 BitVector
Added(SUnits
.size());
1172 DenseMap
<int, int> OutputDeps
;
1173 for (int i
= 0, e
= SUnits
.size(); i
!= e
; ++i
) {
1175 // Add any successor to the adjacency matrix and exclude duplicates.
1176 for (auto &SI
: SUnits
[i
].Succs
) {
1177 // Only create a back-edge on the first and last nodes of a dependence
1178 // chain. This records any chains and adds them later.
1179 if (SI
.getKind() == SDep::Output
) {
1180 int N
= SI
.getSUnit()->NodeNum
;
1182 auto Dep
= OutputDeps
.find(BackEdge
);
1183 if (Dep
!= OutputDeps
.end()) {
1184 BackEdge
= Dep
->second
;
1185 OutputDeps
.erase(Dep
);
1187 OutputDeps
[N
] = BackEdge
;
1189 // Do not process a boundary node, an artificial node.
1190 // A back-edge is processed only if it goes to a Phi.
1191 if (SI
.getSUnit()->isBoundaryNode() || SI
.isArtificial() ||
1192 (SI
.getKind() == SDep::Anti
&& !SI
.getSUnit()->getInstr()->isPHI()))
1194 int N
= SI
.getSUnit()->NodeNum
;
1195 if (!Added
.test(N
)) {
1196 AdjK
[i
].push_back(N
);
1200 // A chain edge between a store and a load is treated as a back-edge in the
1201 // adjacency matrix.
1202 for (auto &PI
: SUnits
[i
].Preds
) {
1203 if (!SUnits
[i
].getInstr()->mayStore() ||
1204 !DAG
->isLoopCarriedDep(&SUnits
[i
], PI
, false))
1206 if (PI
.getKind() == SDep::Order
&& PI
.getSUnit()->getInstr()->mayLoad()) {
1207 int N
= PI
.getSUnit()->NodeNum
;
1208 if (!Added
.test(N
)) {
1209 AdjK
[i
].push_back(N
);
1215 // Add back-edges in the adjacency matrix for the output dependences.
1216 for (auto &OD
: OutputDeps
)
1217 if (!Added
.test(OD
.second
)) {
1218 AdjK
[OD
.first
].push_back(OD
.second
);
1219 Added
.set(OD
.second
);
1223 /// Identify an elementary circuit in the dependence graph starting at the
1225 bool SwingSchedulerDAG::Circuits::circuit(int V
, int S
, NodeSetType
&NodeSets
,
1227 SUnit
*SV
= &SUnits
[V
];
1232 for (auto W
: AdjK
[V
]) {
1233 if (NumPaths
> MaxPaths
)
1239 NodeSets
.push_back(NodeSet(Stack
.begin(), Stack
.end()));
1243 } else if (!Blocked
.test(W
)) {
1244 if (circuit(W
, S
, NodeSets
,
1245 Node2Idx
->at(W
) < Node2Idx
->at(V
) ? true : HasBackedge
))
1253 for (auto W
: AdjK
[V
]) {
1263 /// Unblock a node in the circuit finding algorithm.
1264 void SwingSchedulerDAG::Circuits::unblock(int U
) {
1266 SmallPtrSet
<SUnit
*, 4> &BU
= B
[U
];
1267 while (!BU
.empty()) {
1268 SmallPtrSet
<SUnit
*, 4>::iterator SI
= BU
.begin();
1269 assert(SI
!= BU
.end() && "Invalid B set.");
1272 if (Blocked
.test(W
->NodeNum
))
1273 unblock(W
->NodeNum
);
1277 /// Identify all the elementary circuits in the dependence graph using
1278 /// Johnson's circuit algorithm.
1279 void SwingSchedulerDAG::findCircuits(NodeSetType
&NodeSets
) {
1280 // Swap all the anti dependences in the DAG. That means it is no longer a DAG,
1281 // but we do this to find the circuits, and then change them back.
1282 swapAntiDependences(SUnits
);
1284 Circuits
Cir(SUnits
, Topo
);
1285 // Create the adjacency structure.
1286 Cir
.createAdjacencyStructure(this);
1287 for (int i
= 0, e
= SUnits
.size(); i
!= e
; ++i
) {
1289 Cir
.circuit(i
, i
, NodeSets
);
1292 // Change the dependences back so that we've created a DAG again.
1293 swapAntiDependences(SUnits
);
1296 // Create artificial dependencies between the source of COPY/REG_SEQUENCE that
1297 // is loop-carried to the USE in next iteration. This will help pipeliner avoid
1298 // additional copies that are needed across iterations. An artificial dependence
1299 // edge is added from USE to SOURCE of COPY/REG_SEQUENCE.
1301 // PHI-------Anti-Dep-----> COPY/REG_SEQUENCE (loop-carried)
1302 // SRCOfCopY------True-Dep---> COPY/REG_SEQUENCE
1303 // PHI-------True-Dep------> USEOfPhi
1305 // The mutation creates
1306 // USEOfPHI -------Artificial-Dep---> SRCOfCopy
1308 // This overall will ensure, the USEOfPHI is scheduled before SRCOfCopy
1309 // (since USE is a predecessor), implies, the COPY/ REG_SEQUENCE is scheduled
1310 // late to avoid additional copies across iterations. The possible scheduling
1312 // USEOfPHI --- SRCOfCopy--- COPY/REG_SEQUENCE.
1314 void SwingSchedulerDAG::CopyToPhiMutation::apply(ScheduleDAGInstrs
*DAG
) {
1315 for (SUnit
&SU
: DAG
->SUnits
) {
1316 // Find the COPY/REG_SEQUENCE instruction.
1317 if (!SU
.getInstr()->isCopy() && !SU
.getInstr()->isRegSequence())
1320 // Record the loop carried PHIs.
1321 SmallVector
<SUnit
*, 4> PHISUs
;
1322 // Record the SrcSUs that feed the COPY/REG_SEQUENCE instructions.
1323 SmallVector
<SUnit
*, 4> SrcSUs
;
1325 for (auto &Dep
: SU
.Preds
) {
1326 SUnit
*TmpSU
= Dep
.getSUnit();
1327 MachineInstr
*TmpMI
= TmpSU
->getInstr();
1328 SDep::Kind DepKind
= Dep
.getKind();
1329 // Save the loop carried PHI.
1330 if (DepKind
== SDep::Anti
&& TmpMI
->isPHI())
1331 PHISUs
.push_back(TmpSU
);
1332 // Save the source of COPY/REG_SEQUENCE.
1333 // If the source has no pre-decessors, we will end up creating cycles.
1334 else if (DepKind
== SDep::Data
&& !TmpMI
->isPHI() && TmpSU
->NumPreds
> 0)
1335 SrcSUs
.push_back(TmpSU
);
1338 if (PHISUs
.size() == 0 || SrcSUs
.size() == 0)
1341 // Find the USEs of PHI. If the use is a PHI or REG_SEQUENCE, push back this
1342 // SUnit to the container.
1343 SmallVector
<SUnit
*, 8> UseSUs
;
1344 // Do not use iterator based loop here as we are updating the container.
1345 for (size_t Index
= 0; Index
< PHISUs
.size(); ++Index
) {
1346 for (auto &Dep
: PHISUs
[Index
]->Succs
) {
1347 if (Dep
.getKind() != SDep::Data
)
1350 SUnit
*TmpSU
= Dep
.getSUnit();
1351 MachineInstr
*TmpMI
= TmpSU
->getInstr();
1352 if (TmpMI
->isPHI() || TmpMI
->isRegSequence()) {
1353 PHISUs
.push_back(TmpSU
);
1356 UseSUs
.push_back(TmpSU
);
1360 if (UseSUs
.size() == 0)
1363 SwingSchedulerDAG
*SDAG
= cast
<SwingSchedulerDAG
>(DAG
);
1364 // Add the artificial dependencies if it does not form a cycle.
1365 for (auto *I
: UseSUs
) {
1366 for (auto *Src
: SrcSUs
) {
1367 if (!SDAG
->Topo
.IsReachable(I
, Src
) && Src
!= I
) {
1368 Src
->addPred(SDep(I
, SDep::Artificial
));
1369 SDAG
->Topo
.AddPred(Src
, I
);
1376 /// Return true for DAG nodes that we ignore when computing the cost functions.
1377 /// We ignore the back-edge recurrence in order to avoid unbounded recursion
1378 /// in the calculation of the ASAP, ALAP, etc functions.
1379 static bool ignoreDependence(const SDep
&D
, bool isPred
) {
1380 if (D
.isArtificial() || D
.getSUnit()->isBoundaryNode())
1382 return D
.getKind() == SDep::Anti
&& isPred
;
1385 /// Compute several functions need to order the nodes for scheduling.
1386 /// ASAP - Earliest time to schedule a node.
1387 /// ALAP - Latest time to schedule a node.
1388 /// MOV - Mobility function, difference between ALAP and ASAP.
1389 /// D - Depth of each node.
1390 /// H - Height of each node.
1391 void SwingSchedulerDAG::computeNodeFunctions(NodeSetType
&NodeSets
) {
1392 ScheduleInfo
.resize(SUnits
.size());
1395 for (int I
: Topo
) {
1396 const SUnit
&SU
= SUnits
[I
];
1402 // Compute ASAP and ZeroLatencyDepth.
1403 for (int I
: Topo
) {
1405 int zeroLatencyDepth
= 0;
1406 SUnit
*SU
= &SUnits
[I
];
1407 for (const SDep
&P
: SU
->Preds
) {
1408 SUnit
*pred
= P
.getSUnit();
1409 if (P
.getLatency() == 0)
1411 std::max(zeroLatencyDepth
, getZeroLatencyDepth(pred
) + 1);
1412 if (ignoreDependence(P
, true))
1414 asap
= std::max(asap
, (int)(getASAP(pred
) + P
.getLatency() -
1415 getDistance(pred
, SU
, P
) * MII
));
1417 maxASAP
= std::max(maxASAP
, asap
);
1418 ScheduleInfo
[I
].ASAP
= asap
;
1419 ScheduleInfo
[I
].ZeroLatencyDepth
= zeroLatencyDepth
;
1422 // Compute ALAP, ZeroLatencyHeight, and MOV.
1423 for (int I
: llvm::reverse(Topo
)) {
1425 int zeroLatencyHeight
= 0;
1426 SUnit
*SU
= &SUnits
[I
];
1427 for (const SDep
&S
: SU
->Succs
) {
1428 SUnit
*succ
= S
.getSUnit();
1429 if (succ
->isBoundaryNode())
1431 if (S
.getLatency() == 0)
1433 std::max(zeroLatencyHeight
, getZeroLatencyHeight(succ
) + 1);
1434 if (ignoreDependence(S
, true))
1436 alap
= std::min(alap
, (int)(getALAP(succ
) - S
.getLatency() +
1437 getDistance(SU
, succ
, S
) * MII
));
1440 ScheduleInfo
[I
].ALAP
= alap
;
1441 ScheduleInfo
[I
].ZeroLatencyHeight
= zeroLatencyHeight
;
1444 // After computing the node functions, compute the summary for each node set.
1445 for (NodeSet
&I
: NodeSets
)
1446 I
.computeNodeSetInfo(this);
1449 for (unsigned i
= 0; i
< SUnits
.size(); i
++) {
1450 dbgs() << "\tNode " << i
<< ":\n";
1451 dbgs() << "\t ASAP = " << getASAP(&SUnits
[i
]) << "\n";
1452 dbgs() << "\t ALAP = " << getALAP(&SUnits
[i
]) << "\n";
1453 dbgs() << "\t MOV = " << getMOV(&SUnits
[i
]) << "\n";
1454 dbgs() << "\t D = " << getDepth(&SUnits
[i
]) << "\n";
1455 dbgs() << "\t H = " << getHeight(&SUnits
[i
]) << "\n";
1456 dbgs() << "\t ZLD = " << getZeroLatencyDepth(&SUnits
[i
]) << "\n";
1457 dbgs() << "\t ZLH = " << getZeroLatencyHeight(&SUnits
[i
]) << "\n";
1462 /// Compute the Pred_L(O) set, as defined in the paper. The set is defined
1463 /// as the predecessors of the elements of NodeOrder that are not also in
1465 static bool pred_L(SetVector
<SUnit
*> &NodeOrder
,
1466 SmallSetVector
<SUnit
*, 8> &Preds
,
1467 const NodeSet
*S
= nullptr) {
1469 for (const SUnit
*SU
: NodeOrder
) {
1470 for (const SDep
&Pred
: SU
->Preds
) {
1471 if (S
&& S
->count(Pred
.getSUnit()) == 0)
1473 if (ignoreDependence(Pred
, true))
1475 if (NodeOrder
.count(Pred
.getSUnit()) == 0)
1476 Preds
.insert(Pred
.getSUnit());
1478 // Back-edges are predecessors with an anti-dependence.
1479 for (const SDep
&Succ
: SU
->Succs
) {
1480 if (Succ
.getKind() != SDep::Anti
)
1482 if (S
&& S
->count(Succ
.getSUnit()) == 0)
1484 if (NodeOrder
.count(Succ
.getSUnit()) == 0)
1485 Preds
.insert(Succ
.getSUnit());
1488 return !Preds
.empty();
1491 /// Compute the Succ_L(O) set, as defined in the paper. The set is defined
1492 /// as the successors of the elements of NodeOrder that are not also in
1494 static bool succ_L(SetVector
<SUnit
*> &NodeOrder
,
1495 SmallSetVector
<SUnit
*, 8> &Succs
,
1496 const NodeSet
*S
= nullptr) {
1498 for (const SUnit
*SU
: NodeOrder
) {
1499 for (const SDep
&Succ
: SU
->Succs
) {
1500 if (S
&& S
->count(Succ
.getSUnit()) == 0)
1502 if (ignoreDependence(Succ
, false))
1504 if (NodeOrder
.count(Succ
.getSUnit()) == 0)
1505 Succs
.insert(Succ
.getSUnit());
1507 for (const SDep
&Pred
: SU
->Preds
) {
1508 if (Pred
.getKind() != SDep::Anti
)
1510 if (S
&& S
->count(Pred
.getSUnit()) == 0)
1512 if (NodeOrder
.count(Pred
.getSUnit()) == 0)
1513 Succs
.insert(Pred
.getSUnit());
1516 return !Succs
.empty();
1519 /// Return true if there is a path from the specified node to any of the nodes
1520 /// in DestNodes. Keep track and return the nodes in any path.
1521 static bool computePath(SUnit
*Cur
, SetVector
<SUnit
*> &Path
,
1522 SetVector
<SUnit
*> &DestNodes
,
1523 SetVector
<SUnit
*> &Exclude
,
1524 SmallPtrSet
<SUnit
*, 8> &Visited
) {
1525 if (Cur
->isBoundaryNode())
1527 if (Exclude
.contains(Cur
))
1529 if (DestNodes
.contains(Cur
))
1531 if (!Visited
.insert(Cur
).second
)
1532 return Path
.contains(Cur
);
1533 bool FoundPath
= false;
1534 for (auto &SI
: Cur
->Succs
)
1535 if (!ignoreDependence(SI
, false))
1537 computePath(SI
.getSUnit(), Path
, DestNodes
, Exclude
, Visited
);
1538 for (auto &PI
: Cur
->Preds
)
1539 if (PI
.getKind() == SDep::Anti
)
1541 computePath(PI
.getSUnit(), Path
, DestNodes
, Exclude
, Visited
);
1547 /// Compute the live-out registers for the instructions in a node-set.
1548 /// The live-out registers are those that are defined in the node-set,
1549 /// but not used. Except for use operands of Phis.
1550 static void computeLiveOuts(MachineFunction
&MF
, RegPressureTracker
&RPTracker
,
1552 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
1553 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
1554 SmallVector
<RegisterMaskPair
, 8> LiveOutRegs
;
1555 SmallSet
<unsigned, 4> Uses
;
1556 for (SUnit
*SU
: NS
) {
1557 const MachineInstr
*MI
= SU
->getInstr();
1560 for (const MachineOperand
&MO
: MI
->all_uses()) {
1561 Register Reg
= MO
.getReg();
1562 if (Reg
.isVirtual())
1564 else if (MRI
.isAllocatable(Reg
))
1565 for (MCRegUnit Unit
: TRI
->regunits(Reg
.asMCReg()))
1569 for (SUnit
*SU
: NS
)
1570 for (const MachineOperand
&MO
: SU
->getInstr()->all_defs())
1572 Register Reg
= MO
.getReg();
1573 if (Reg
.isVirtual()) {
1574 if (!Uses
.count(Reg
))
1575 LiveOutRegs
.push_back(RegisterMaskPair(Reg
,
1576 LaneBitmask::getNone()));
1577 } else if (MRI
.isAllocatable(Reg
)) {
1578 for (MCRegUnit Unit
: TRI
->regunits(Reg
.asMCReg()))
1579 if (!Uses
.count(Unit
))
1580 LiveOutRegs
.push_back(
1581 RegisterMaskPair(Unit
, LaneBitmask::getNone()));
1584 RPTracker
.addLiveRegs(LiveOutRegs
);
1587 /// A heuristic to filter nodes in recurrent node-sets if the register
1588 /// pressure of a set is too high.
1589 void SwingSchedulerDAG::registerPressureFilter(NodeSetType
&NodeSets
) {
1590 for (auto &NS
: NodeSets
) {
1591 // Skip small node-sets since they won't cause register pressure problems.
1594 IntervalPressure RecRegPressure
;
1595 RegPressureTracker
RecRPTracker(RecRegPressure
);
1596 RecRPTracker
.init(&MF
, &RegClassInfo
, &LIS
, BB
, BB
->end(), false, true);
1597 computeLiveOuts(MF
, RecRPTracker
, NS
);
1598 RecRPTracker
.closeBottom();
1600 std::vector
<SUnit
*> SUnits(NS
.begin(), NS
.end());
1601 llvm::sort(SUnits
, [](const SUnit
*A
, const SUnit
*B
) {
1602 return A
->NodeNum
> B
->NodeNum
;
1605 for (auto &SU
: SUnits
) {
1606 // Since we're computing the register pressure for a subset of the
1607 // instructions in a block, we need to set the tracker for each
1608 // instruction in the node-set. The tracker is set to the instruction
1609 // just after the one we're interested in.
1610 MachineBasicBlock::const_iterator CurInstI
= SU
->getInstr();
1611 RecRPTracker
.setPos(std::next(CurInstI
));
1613 RegPressureDelta RPDelta
;
1614 ArrayRef
<PressureChange
> CriticalPSets
;
1615 RecRPTracker
.getMaxUpwardPressureDelta(SU
->getInstr(), nullptr, RPDelta
,
1617 RecRegPressure
.MaxSetPressure
);
1618 if (RPDelta
.Excess
.isValid()) {
1620 dbgs() << "Excess register pressure: SU(" << SU
->NodeNum
<< ") "
1621 << TRI
->getRegPressureSetName(RPDelta
.Excess
.getPSet())
1622 << ":" << RPDelta
.Excess
.getUnitInc() << "\n");
1623 NS
.setExceedPressure(SU
);
1626 RecRPTracker
.recede();
1631 /// A heuristic to colocate node sets that have the same set of
1633 void SwingSchedulerDAG::colocateNodeSets(NodeSetType
&NodeSets
) {
1634 unsigned Colocate
= 0;
1635 for (int i
= 0, e
= NodeSets
.size(); i
< e
; ++i
) {
1636 NodeSet
&N1
= NodeSets
[i
];
1637 SmallSetVector
<SUnit
*, 8> S1
;
1638 if (N1
.empty() || !succ_L(N1
, S1
))
1640 for (int j
= i
+ 1; j
< e
; ++j
) {
1641 NodeSet
&N2
= NodeSets
[j
];
1642 if (N1
.compareRecMII(N2
) != 0)
1644 SmallSetVector
<SUnit
*, 8> S2
;
1645 if (N2
.empty() || !succ_L(N2
, S2
))
1647 if (llvm::set_is_subset(S1
, S2
) && S1
.size() == S2
.size()) {
1648 N1
.setColocate(++Colocate
);
1649 N2
.setColocate(Colocate
);
1656 /// Check if the existing node-sets are profitable. If not, then ignore the
1657 /// recurrent node-sets, and attempt to schedule all nodes together. This is
1658 /// a heuristic. If the MII is large and all the recurrent node-sets are small,
1659 /// then it's best to try to schedule all instructions together instead of
1660 /// starting with the recurrent node-sets.
1661 void SwingSchedulerDAG::checkNodeSets(NodeSetType
&NodeSets
) {
1662 // Look for loops with a large MII.
1665 // Check if the node-set contains only a simple add recurrence.
1666 for (auto &NS
: NodeSets
) {
1667 if (NS
.getRecMII() > 2)
1669 if (NS
.getMaxDepth() > MII
)
1673 LLVM_DEBUG(dbgs() << "Clear recurrence node-sets\n");
1676 /// Add the nodes that do not belong to a recurrence set into groups
1677 /// based upon connected components.
1678 void SwingSchedulerDAG::groupRemainingNodes(NodeSetType
&NodeSets
) {
1679 SetVector
<SUnit
*> NodesAdded
;
1680 SmallPtrSet
<SUnit
*, 8> Visited
;
1681 // Add the nodes that are on a path between the previous node sets and
1682 // the current node set.
1683 for (NodeSet
&I
: NodeSets
) {
1684 SmallSetVector
<SUnit
*, 8> N
;
1685 // Add the nodes from the current node set to the previous node set.
1687 SetVector
<SUnit
*> Path
;
1688 for (SUnit
*NI
: N
) {
1690 computePath(NI
, Path
, NodesAdded
, I
, Visited
);
1693 I
.insert(Path
.begin(), Path
.end());
1695 // Add the nodes from the previous node set to the current node set.
1697 if (succ_L(NodesAdded
, N
)) {
1698 SetVector
<SUnit
*> Path
;
1699 for (SUnit
*NI
: N
) {
1701 computePath(NI
, Path
, I
, NodesAdded
, Visited
);
1704 I
.insert(Path
.begin(), Path
.end());
1706 NodesAdded
.insert(I
.begin(), I
.end());
1709 // Create a new node set with the connected nodes of any successor of a node
1710 // in a recurrent set.
1712 SmallSetVector
<SUnit
*, 8> N
;
1713 if (succ_L(NodesAdded
, N
))
1715 addConnectedNodes(I
, NewSet
, NodesAdded
);
1716 if (!NewSet
.empty())
1717 NodeSets
.push_back(NewSet
);
1719 // Create a new node set with the connected nodes of any predecessor of a node
1720 // in a recurrent set.
1722 if (pred_L(NodesAdded
, N
))
1724 addConnectedNodes(I
, NewSet
, NodesAdded
);
1725 if (!NewSet
.empty())
1726 NodeSets
.push_back(NewSet
);
1728 // Create new nodes sets with the connected nodes any remaining node that
1729 // has no predecessor.
1730 for (SUnit
&SU
: SUnits
) {
1731 if (NodesAdded
.count(&SU
) == 0) {
1733 addConnectedNodes(&SU
, NewSet
, NodesAdded
);
1734 if (!NewSet
.empty())
1735 NodeSets
.push_back(NewSet
);
1740 /// Add the node to the set, and add all of its connected nodes to the set.
1741 void SwingSchedulerDAG::addConnectedNodes(SUnit
*SU
, NodeSet
&NewSet
,
1742 SetVector
<SUnit
*> &NodesAdded
) {
1744 NodesAdded
.insert(SU
);
1745 for (auto &SI
: SU
->Succs
) {
1746 SUnit
*Successor
= SI
.getSUnit();
1747 if (!SI
.isArtificial() && !Successor
->isBoundaryNode() &&
1748 NodesAdded
.count(Successor
) == 0)
1749 addConnectedNodes(Successor
, NewSet
, NodesAdded
);
1751 for (auto &PI
: SU
->Preds
) {
1752 SUnit
*Predecessor
= PI
.getSUnit();
1753 if (!PI
.isArtificial() && NodesAdded
.count(Predecessor
) == 0)
1754 addConnectedNodes(Predecessor
, NewSet
, NodesAdded
);
1758 /// Return true if Set1 contains elements in Set2. The elements in common
1759 /// are returned in a different container.
1760 static bool isIntersect(SmallSetVector
<SUnit
*, 8> &Set1
, const NodeSet
&Set2
,
1761 SmallSetVector
<SUnit
*, 8> &Result
) {
1763 for (SUnit
*SU
: Set1
) {
1764 if (Set2
.count(SU
) != 0)
1767 return !Result
.empty();
1770 /// Merge the recurrence node sets that have the same initial node.
1771 void SwingSchedulerDAG::fuseRecs(NodeSetType
&NodeSets
) {
1772 for (NodeSetType::iterator I
= NodeSets
.begin(), E
= NodeSets
.end(); I
!= E
;
1775 for (NodeSetType::iterator J
= I
+ 1; J
!= E
;) {
1777 if (NI
.getNode(0)->NodeNum
== NJ
.getNode(0)->NodeNum
) {
1778 if (NJ
.compareRecMII(NI
) > 0)
1779 NI
.setRecMII(NJ
.getRecMII());
1780 for (SUnit
*SU
: *J
)
1791 /// Remove nodes that have been scheduled in previous NodeSets.
1792 void SwingSchedulerDAG::removeDuplicateNodes(NodeSetType
&NodeSets
) {
1793 for (NodeSetType::iterator I
= NodeSets
.begin(), E
= NodeSets
.end(); I
!= E
;
1795 for (NodeSetType::iterator J
= I
+ 1; J
!= E
;) {
1796 J
->remove_if([&](SUnit
*SUJ
) { return I
->count(SUJ
); });
1807 /// Compute an ordered list of the dependence graph nodes, which
1808 /// indicates the order that the nodes will be scheduled. This is a
1809 /// two-level algorithm. First, a partial order is created, which
1810 /// consists of a list of sets ordered from highest to lowest priority.
1811 void SwingSchedulerDAG::computeNodeOrder(NodeSetType
&NodeSets
) {
1812 SmallSetVector
<SUnit
*, 8> R
;
1815 for (auto &Nodes
: NodeSets
) {
1816 LLVM_DEBUG(dbgs() << "NodeSet size " << Nodes
.size() << "\n");
1818 SmallSetVector
<SUnit
*, 8> N
;
1819 if (pred_L(NodeOrder
, N
) && llvm::set_is_subset(N
, Nodes
)) {
1820 R
.insert(N
.begin(), N
.end());
1822 LLVM_DEBUG(dbgs() << " Bottom up (preds) ");
1823 } else if (succ_L(NodeOrder
, N
) && llvm::set_is_subset(N
, Nodes
)) {
1824 R
.insert(N
.begin(), N
.end());
1826 LLVM_DEBUG(dbgs() << " Top down (succs) ");
1827 } else if (isIntersect(N
, Nodes
, R
)) {
1828 // If some of the successors are in the existing node-set, then use the
1829 // top-down ordering.
1831 LLVM_DEBUG(dbgs() << " Top down (intersect) ");
1832 } else if (NodeSets
.size() == 1) {
1833 for (const auto &N
: Nodes
)
1834 if (N
->Succs
.size() == 0)
1837 LLVM_DEBUG(dbgs() << " Bottom up (all) ");
1839 // Find the node with the highest ASAP.
1840 SUnit
*maxASAP
= nullptr;
1841 for (SUnit
*SU
: Nodes
) {
1842 if (maxASAP
== nullptr || getASAP(SU
) > getASAP(maxASAP
) ||
1843 (getASAP(SU
) == getASAP(maxASAP
) && SU
->NodeNum
> maxASAP
->NodeNum
))
1848 LLVM_DEBUG(dbgs() << " Bottom up (default) ");
1851 while (!R
.empty()) {
1852 if (Order
== TopDown
) {
1853 // Choose the node with the maximum height. If more than one, choose
1854 // the node wiTH the maximum ZeroLatencyHeight. If still more than one,
1855 // choose the node with the lowest MOV.
1856 while (!R
.empty()) {
1857 SUnit
*maxHeight
= nullptr;
1858 for (SUnit
*I
: R
) {
1859 if (maxHeight
== nullptr || getHeight(I
) > getHeight(maxHeight
))
1861 else if (getHeight(I
) == getHeight(maxHeight
) &&
1862 getZeroLatencyHeight(I
) > getZeroLatencyHeight(maxHeight
))
1864 else if (getHeight(I
) == getHeight(maxHeight
) &&
1865 getZeroLatencyHeight(I
) ==
1866 getZeroLatencyHeight(maxHeight
) &&
1867 getMOV(I
) < getMOV(maxHeight
))
1870 NodeOrder
.insert(maxHeight
);
1871 LLVM_DEBUG(dbgs() << maxHeight
->NodeNum
<< " ");
1872 R
.remove(maxHeight
);
1873 for (const auto &I
: maxHeight
->Succs
) {
1874 if (Nodes
.count(I
.getSUnit()) == 0)
1876 if (NodeOrder
.contains(I
.getSUnit()))
1878 if (ignoreDependence(I
, false))
1880 R
.insert(I
.getSUnit());
1882 // Back-edges are predecessors with an anti-dependence.
1883 for (const auto &I
: maxHeight
->Preds
) {
1884 if (I
.getKind() != SDep::Anti
)
1886 if (Nodes
.count(I
.getSUnit()) == 0)
1888 if (NodeOrder
.contains(I
.getSUnit()))
1890 R
.insert(I
.getSUnit());
1894 LLVM_DEBUG(dbgs() << "\n Switching order to bottom up ");
1895 SmallSetVector
<SUnit
*, 8> N
;
1896 if (pred_L(NodeOrder
, N
, &Nodes
))
1897 R
.insert(N
.begin(), N
.end());
1899 // Choose the node with the maximum depth. If more than one, choose
1900 // the node with the maximum ZeroLatencyDepth. If still more than one,
1901 // choose the node with the lowest MOV.
1902 while (!R
.empty()) {
1903 SUnit
*maxDepth
= nullptr;
1904 for (SUnit
*I
: R
) {
1905 if (maxDepth
== nullptr || getDepth(I
) > getDepth(maxDepth
))
1907 else if (getDepth(I
) == getDepth(maxDepth
) &&
1908 getZeroLatencyDepth(I
) > getZeroLatencyDepth(maxDepth
))
1910 else if (getDepth(I
) == getDepth(maxDepth
) &&
1911 getZeroLatencyDepth(I
) == getZeroLatencyDepth(maxDepth
) &&
1912 getMOV(I
) < getMOV(maxDepth
))
1915 NodeOrder
.insert(maxDepth
);
1916 LLVM_DEBUG(dbgs() << maxDepth
->NodeNum
<< " ");
1918 if (Nodes
.isExceedSU(maxDepth
)) {
1921 R
.insert(Nodes
.getNode(0));
1924 for (const auto &I
: maxDepth
->Preds
) {
1925 if (Nodes
.count(I
.getSUnit()) == 0)
1927 if (NodeOrder
.contains(I
.getSUnit()))
1929 R
.insert(I
.getSUnit());
1931 // Back-edges are predecessors with an anti-dependence.
1932 for (const auto &I
: maxDepth
->Succs
) {
1933 if (I
.getKind() != SDep::Anti
)
1935 if (Nodes
.count(I
.getSUnit()) == 0)
1937 if (NodeOrder
.contains(I
.getSUnit()))
1939 R
.insert(I
.getSUnit());
1943 LLVM_DEBUG(dbgs() << "\n Switching order to top down ");
1944 SmallSetVector
<SUnit
*, 8> N
;
1945 if (succ_L(NodeOrder
, N
, &Nodes
))
1946 R
.insert(N
.begin(), N
.end());
1949 LLVM_DEBUG(dbgs() << "\nDone with Nodeset\n");
1953 dbgs() << "Node order: ";
1954 for (SUnit
*I
: NodeOrder
)
1955 dbgs() << " " << I
->NodeNum
<< " ";
1960 /// Process the nodes in the computed order and create the pipelined schedule
1961 /// of the instructions, if possible. Return true if a schedule is found.
1962 bool SwingSchedulerDAG::schedulePipeline(SMSchedule
&Schedule
) {
1964 if (NodeOrder
.empty()){
1965 LLVM_DEBUG(dbgs() << "NodeOrder is empty! abort scheduling\n" );
1969 bool scheduleFound
= false;
1970 // Keep increasing II until a valid schedule is found.
1971 for (unsigned II
= MII
; II
<= MAX_II
&& !scheduleFound
; ++II
) {
1973 Schedule
.setInitiationInterval(II
);
1974 LLVM_DEBUG(dbgs() << "Try to schedule with " << II
<< "\n");
1976 SetVector
<SUnit
*>::iterator NI
= NodeOrder
.begin();
1977 SetVector
<SUnit
*>::iterator NE
= NodeOrder
.end();
1981 // Compute the schedule time for the instruction, which is based
1982 // upon the scheduled time for any predecessors/successors.
1983 int EarlyStart
= INT_MIN
;
1984 int LateStart
= INT_MAX
;
1985 // These values are set when the size of the schedule window is limited
1986 // due to chain dependences.
1987 int SchedEnd
= INT_MAX
;
1988 int SchedStart
= INT_MIN
;
1989 Schedule
.computeStart(SU
, &EarlyStart
, &LateStart
, &SchedEnd
, &SchedStart
,
1993 dbgs() << "Inst (" << SU
->NodeNum
<< ") ";
1994 SU
->getInstr()->dump();
1998 dbgs() << format("\tes: %8x ls: %8x me: %8x ms: %8x\n", EarlyStart
,
1999 LateStart
, SchedEnd
, SchedStart
);
2002 if (EarlyStart
> LateStart
|| SchedEnd
< EarlyStart
||
2003 SchedStart
> LateStart
)
2004 scheduleFound
= false;
2005 else if (EarlyStart
!= INT_MIN
&& LateStart
== INT_MAX
) {
2006 SchedEnd
= std::min(SchedEnd
, EarlyStart
+ (int)II
- 1);
2007 scheduleFound
= Schedule
.insert(SU
, EarlyStart
, SchedEnd
, II
);
2008 } else if (EarlyStart
== INT_MIN
&& LateStart
!= INT_MAX
) {
2009 SchedStart
= std::max(SchedStart
, LateStart
- (int)II
+ 1);
2010 scheduleFound
= Schedule
.insert(SU
, LateStart
, SchedStart
, II
);
2011 } else if (EarlyStart
!= INT_MIN
&& LateStart
!= INT_MAX
) {
2013 std::min(SchedEnd
, std::min(LateStart
, EarlyStart
+ (int)II
- 1));
2014 // When scheduling a Phi it is better to start at the late cycle and go
2015 // backwards. The default order may insert the Phi too far away from
2016 // its first dependence.
2017 if (SU
->getInstr()->isPHI())
2018 scheduleFound
= Schedule
.insert(SU
, SchedEnd
, EarlyStart
, II
);
2020 scheduleFound
= Schedule
.insert(SU
, EarlyStart
, SchedEnd
, II
);
2022 int FirstCycle
= Schedule
.getFirstCycle();
2023 scheduleFound
= Schedule
.insert(SU
, FirstCycle
+ getASAP(SU
),
2024 FirstCycle
+ getASAP(SU
) + II
- 1, II
);
2026 // Even if we find a schedule, make sure the schedule doesn't exceed the
2027 // allowable number of stages. We keep trying if this happens.
2029 if (SwpMaxStages
> -1 &&
2030 Schedule
.getMaxStageCount() > (unsigned)SwpMaxStages
)
2031 scheduleFound
= false;
2035 dbgs() << "\tCan't schedule\n";
2037 } while (++NI
!= NE
&& scheduleFound
);
2039 // If a schedule is found, ensure non-pipelined instructions are in stage 0
2042 Schedule
.normalizeNonPipelinedInstructions(this, LoopPipelinerInfo
);
2044 // If a schedule is found, check if it is a valid schedule too.
2046 scheduleFound
= Schedule
.isValidSchedule(this);
2049 LLVM_DEBUG(dbgs() << "Schedule Found? " << scheduleFound
2050 << " (II=" << Schedule
.getInitiationInterval()
2053 if (scheduleFound
) {
2054 scheduleFound
= LoopPipelinerInfo
->shouldUseSchedule(*this, Schedule
);
2056 LLVM_DEBUG(dbgs() << "Target rejected schedule\n");
2059 if (scheduleFound
) {
2060 Schedule
.finalizeSchedule(this);
2061 Pass
.ORE
->emit([&]() {
2062 return MachineOptimizationRemarkAnalysis(
2063 DEBUG_TYPE
, "schedule", Loop
.getStartLoc(), Loop
.getHeader())
2064 << "Schedule found with Initiation Interval: "
2065 << ore::NV("II", Schedule
.getInitiationInterval())
2066 << ", MaxStageCount: "
2067 << ore::NV("MaxStageCount", Schedule
.getMaxStageCount());
2072 return scheduleFound
&& Schedule
.getMaxStageCount() > 0;
2075 /// Return true if we can compute the amount the instruction changes
2076 /// during each iteration. Set Delta to the amount of the change.
2077 bool SwingSchedulerDAG::computeDelta(MachineInstr
&MI
, unsigned &Delta
) {
2078 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
2079 const MachineOperand
*BaseOp
;
2081 bool OffsetIsScalable
;
2082 if (!TII
->getMemOperandWithOffset(MI
, BaseOp
, Offset
, OffsetIsScalable
, TRI
))
2085 // FIXME: This algorithm assumes instructions have fixed-size offsets.
2086 if (OffsetIsScalable
)
2089 if (!BaseOp
->isReg())
2092 Register BaseReg
= BaseOp
->getReg();
2094 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
2095 // Check if there is a Phi. If so, get the definition in the loop.
2096 MachineInstr
*BaseDef
= MRI
.getVRegDef(BaseReg
);
2097 if (BaseDef
&& BaseDef
->isPHI()) {
2098 BaseReg
= getLoopPhiReg(*BaseDef
, MI
.getParent());
2099 BaseDef
= MRI
.getVRegDef(BaseReg
);
2105 if (!TII
->getIncrementValue(*BaseDef
, D
) && D
>= 0)
2112 /// Check if we can change the instruction to use an offset value from the
2113 /// previous iteration. If so, return true and set the base and offset values
2114 /// so that we can rewrite the load, if necessary.
2115 /// v1 = Phi(v0, v3)
2117 /// v3 = post_store v1, 4, x
2118 /// This function enables the load to be rewritten as v2 = load v3, 4.
2119 bool SwingSchedulerDAG::canUseLastOffsetValue(MachineInstr
*MI
,
2121 unsigned &OffsetPos
,
2124 // Get the load instruction.
2125 if (TII
->isPostIncrement(*MI
))
2127 unsigned BasePosLd
, OffsetPosLd
;
2128 if (!TII
->getBaseAndOffsetPosition(*MI
, BasePosLd
, OffsetPosLd
))
2130 Register BaseReg
= MI
->getOperand(BasePosLd
).getReg();
2132 // Look for the Phi instruction.
2133 MachineRegisterInfo
&MRI
= MI
->getMF()->getRegInfo();
2134 MachineInstr
*Phi
= MRI
.getVRegDef(BaseReg
);
2135 if (!Phi
|| !Phi
->isPHI())
2137 // Get the register defined in the loop block.
2138 unsigned PrevReg
= getLoopPhiReg(*Phi
, MI
->getParent());
2142 // Check for the post-increment load/store instruction.
2143 MachineInstr
*PrevDef
= MRI
.getVRegDef(PrevReg
);
2144 if (!PrevDef
|| PrevDef
== MI
)
2147 if (!TII
->isPostIncrement(*PrevDef
))
2150 unsigned BasePos1
= 0, OffsetPos1
= 0;
2151 if (!TII
->getBaseAndOffsetPosition(*PrevDef
, BasePos1
, OffsetPos1
))
2154 // Make sure that the instructions do not access the same memory location in
2155 // the next iteration.
2156 int64_t LoadOffset
= MI
->getOperand(OffsetPosLd
).getImm();
2157 int64_t StoreOffset
= PrevDef
->getOperand(OffsetPos1
).getImm();
2158 MachineInstr
*NewMI
= MF
.CloneMachineInstr(MI
);
2159 NewMI
->getOperand(OffsetPosLd
).setImm(LoadOffset
+ StoreOffset
);
2160 bool Disjoint
= TII
->areMemAccessesTriviallyDisjoint(*NewMI
, *PrevDef
);
2161 MF
.deleteMachineInstr(NewMI
);
2165 // Set the return value once we determine that we return true.
2166 BasePos
= BasePosLd
;
2167 OffsetPos
= OffsetPosLd
;
2169 Offset
= StoreOffset
;
2173 /// Apply changes to the instruction if needed. The changes are need
2174 /// to improve the scheduling and depend up on the final schedule.
2175 void SwingSchedulerDAG::applyInstrChange(MachineInstr
*MI
,
2176 SMSchedule
&Schedule
) {
2177 SUnit
*SU
= getSUnit(MI
);
2178 DenseMap
<SUnit
*, std::pair
<unsigned, int64_t>>::iterator It
=
2179 InstrChanges
.find(SU
);
2180 if (It
!= InstrChanges
.end()) {
2181 std::pair
<unsigned, int64_t> RegAndOffset
= It
->second
;
2182 unsigned BasePos
, OffsetPos
;
2183 if (!TII
->getBaseAndOffsetPosition(*MI
, BasePos
, OffsetPos
))
2185 Register BaseReg
= MI
->getOperand(BasePos
).getReg();
2186 MachineInstr
*LoopDef
= findDefInLoop(BaseReg
);
2187 int DefStageNum
= Schedule
.stageScheduled(getSUnit(LoopDef
));
2188 int DefCycleNum
= Schedule
.cycleScheduled(getSUnit(LoopDef
));
2189 int BaseStageNum
= Schedule
.stageScheduled(SU
);
2190 int BaseCycleNum
= Schedule
.cycleScheduled(SU
);
2191 if (BaseStageNum
< DefStageNum
) {
2192 MachineInstr
*NewMI
= MF
.CloneMachineInstr(MI
);
2193 int OffsetDiff
= DefStageNum
- BaseStageNum
;
2194 if (DefCycleNum
< BaseCycleNum
) {
2195 NewMI
->getOperand(BasePos
).setReg(RegAndOffset
.first
);
2200 MI
->getOperand(OffsetPos
).getImm() + RegAndOffset
.second
* OffsetDiff
;
2201 NewMI
->getOperand(OffsetPos
).setImm(NewOffset
);
2202 SU
->setInstr(NewMI
);
2203 MISUnitMap
[NewMI
] = SU
;
2209 /// Return the instruction in the loop that defines the register.
2210 /// If the definition is a Phi, then follow the Phi operand to
2211 /// the instruction in the loop.
2212 MachineInstr
*SwingSchedulerDAG::findDefInLoop(Register Reg
) {
2213 SmallPtrSet
<MachineInstr
*, 8> Visited
;
2214 MachineInstr
*Def
= MRI
.getVRegDef(Reg
);
2215 while (Def
->isPHI()) {
2216 if (!Visited
.insert(Def
).second
)
2218 for (unsigned i
= 1, e
= Def
->getNumOperands(); i
< e
; i
+= 2)
2219 if (Def
->getOperand(i
+ 1).getMBB() == BB
) {
2220 Def
= MRI
.getVRegDef(Def
->getOperand(i
).getReg());
2227 /// Return true for an order or output dependence that is loop carried
2228 /// potentially. A dependence is loop carried if the destination defines a valu
2229 /// that may be used or defined by the source in a subsequent iteration.
2230 bool SwingSchedulerDAG::isLoopCarriedDep(SUnit
*Source
, const SDep
&Dep
,
2232 if ((Dep
.getKind() != SDep::Order
&& Dep
.getKind() != SDep::Output
) ||
2233 Dep
.isArtificial() || Dep
.getSUnit()->isBoundaryNode())
2236 if (!SwpPruneLoopCarried
)
2239 if (Dep
.getKind() == SDep::Output
)
2242 MachineInstr
*SI
= Source
->getInstr();
2243 MachineInstr
*DI
= Dep
.getSUnit()->getInstr();
2246 assert(SI
!= nullptr && DI
!= nullptr && "Expecting SUnit with an MI.");
2248 // Assume ordered loads and stores may have a loop carried dependence.
2249 if (SI
->hasUnmodeledSideEffects() || DI
->hasUnmodeledSideEffects() ||
2250 SI
->mayRaiseFPException() || DI
->mayRaiseFPException() ||
2251 SI
->hasOrderedMemoryRef() || DI
->hasOrderedMemoryRef())
2254 // Only chain dependences between a load and store can be loop carried.
2255 if (!DI
->mayStore() || !SI
->mayLoad())
2258 unsigned DeltaS
, DeltaD
;
2259 if (!computeDelta(*SI
, DeltaS
) || !computeDelta(*DI
, DeltaD
))
2262 const MachineOperand
*BaseOpS
, *BaseOpD
;
2263 int64_t OffsetS
, OffsetD
;
2264 bool OffsetSIsScalable
, OffsetDIsScalable
;
2265 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
2266 if (!TII
->getMemOperandWithOffset(*SI
, BaseOpS
, OffsetS
, OffsetSIsScalable
,
2268 !TII
->getMemOperandWithOffset(*DI
, BaseOpD
, OffsetD
, OffsetDIsScalable
,
2272 assert(!OffsetSIsScalable
&& !OffsetDIsScalable
&&
2273 "Expected offsets to be byte offsets");
2275 MachineInstr
*DefS
= MRI
.getVRegDef(BaseOpS
->getReg());
2276 MachineInstr
*DefD
= MRI
.getVRegDef(BaseOpD
->getReg());
2277 if (!DefS
|| !DefD
|| !DefS
->isPHI() || !DefD
->isPHI())
2280 unsigned InitValS
= 0;
2281 unsigned LoopValS
= 0;
2282 unsigned InitValD
= 0;
2283 unsigned LoopValD
= 0;
2284 getPhiRegs(*DefS
, BB
, InitValS
, LoopValS
);
2285 getPhiRegs(*DefD
, BB
, InitValD
, LoopValD
);
2286 MachineInstr
*InitDefS
= MRI
.getVRegDef(InitValS
);
2287 MachineInstr
*InitDefD
= MRI
.getVRegDef(InitValD
);
2289 if (!InitDefS
->isIdenticalTo(*InitDefD
))
2292 // Check that the base register is incremented by a constant value for each
2294 MachineInstr
*LoopDefS
= MRI
.getVRegDef(LoopValS
);
2296 if (!LoopDefS
|| !TII
->getIncrementValue(*LoopDefS
, D
))
2299 uint64_t AccessSizeS
= (*SI
->memoperands_begin())->getSize();
2300 uint64_t AccessSizeD
= (*DI
->memoperands_begin())->getSize();
2302 // This is the main test, which checks the offset values and the loop
2303 // increment value to determine if the accesses may be loop carried.
2304 if (AccessSizeS
== MemoryLocation::UnknownSize
||
2305 AccessSizeD
== MemoryLocation::UnknownSize
)
2308 if (DeltaS
!= DeltaD
|| DeltaS
< AccessSizeS
|| DeltaD
< AccessSizeD
)
2311 return (OffsetS
+ (int64_t)AccessSizeS
< OffsetD
+ (int64_t)AccessSizeD
);
2314 void SwingSchedulerDAG::postProcessDAG() {
2315 for (auto &M
: Mutations
)
2319 /// Try to schedule the node at the specified StartCycle and continue
2320 /// until the node is schedule or the EndCycle is reached. This function
2321 /// returns true if the node is scheduled. This routine may search either
2322 /// forward or backward for a place to insert the instruction based upon
2323 /// the relative values of StartCycle and EndCycle.
2324 bool SMSchedule::insert(SUnit
*SU
, int StartCycle
, int EndCycle
, int II
) {
2325 bool forward
= true;
2327 dbgs() << "Trying to insert node between " << StartCycle
<< " and "
2328 << EndCycle
<< " II: " << II
<< "\n";
2330 if (StartCycle
> EndCycle
)
2333 // The terminating condition depends on the direction.
2334 int termCycle
= forward
? EndCycle
+ 1 : EndCycle
- 1;
2335 for (int curCycle
= StartCycle
; curCycle
!= termCycle
;
2336 forward
? ++curCycle
: --curCycle
) {
2338 if (ST
.getInstrInfo()->isZeroCost(SU
->getInstr()->getOpcode()) ||
2339 ProcItinResources
.canReserveResources(*SU
, curCycle
)) {
2341 dbgs() << "\tinsert at cycle " << curCycle
<< " ";
2342 SU
->getInstr()->dump();
2345 if (!ST
.getInstrInfo()->isZeroCost(SU
->getInstr()->getOpcode()))
2346 ProcItinResources
.reserveResources(*SU
, curCycle
);
2347 ScheduledInstrs
[curCycle
].push_back(SU
);
2348 InstrToCycle
.insert(std::make_pair(SU
, curCycle
));
2349 if (curCycle
> LastCycle
)
2350 LastCycle
= curCycle
;
2351 if (curCycle
< FirstCycle
)
2352 FirstCycle
= curCycle
;
2356 dbgs() << "\tfailed to insert at cycle " << curCycle
<< " ";
2357 SU
->getInstr()->dump();
2363 // Return the cycle of the earliest scheduled instruction in the chain.
2364 int SMSchedule::earliestCycleInChain(const SDep
&Dep
) {
2365 SmallPtrSet
<SUnit
*, 8> Visited
;
2366 SmallVector
<SDep
, 8> Worklist
;
2367 Worklist
.push_back(Dep
);
2368 int EarlyCycle
= INT_MAX
;
2369 while (!Worklist
.empty()) {
2370 const SDep
&Cur
= Worklist
.pop_back_val();
2371 SUnit
*PrevSU
= Cur
.getSUnit();
2372 if (Visited
.count(PrevSU
))
2374 std::map
<SUnit
*, int>::const_iterator it
= InstrToCycle
.find(PrevSU
);
2375 if (it
== InstrToCycle
.end())
2377 EarlyCycle
= std::min(EarlyCycle
, it
->second
);
2378 for (const auto &PI
: PrevSU
->Preds
)
2379 if (PI
.getKind() == SDep::Order
|| PI
.getKind() == SDep::Output
)
2380 Worklist
.push_back(PI
);
2381 Visited
.insert(PrevSU
);
2386 // Return the cycle of the latest scheduled instruction in the chain.
2387 int SMSchedule::latestCycleInChain(const SDep
&Dep
) {
2388 SmallPtrSet
<SUnit
*, 8> Visited
;
2389 SmallVector
<SDep
, 8> Worklist
;
2390 Worklist
.push_back(Dep
);
2391 int LateCycle
= INT_MIN
;
2392 while (!Worklist
.empty()) {
2393 const SDep
&Cur
= Worklist
.pop_back_val();
2394 SUnit
*SuccSU
= Cur
.getSUnit();
2395 if (Visited
.count(SuccSU
) || SuccSU
->isBoundaryNode())
2397 std::map
<SUnit
*, int>::const_iterator it
= InstrToCycle
.find(SuccSU
);
2398 if (it
== InstrToCycle
.end())
2400 LateCycle
= std::max(LateCycle
, it
->second
);
2401 for (const auto &SI
: SuccSU
->Succs
)
2402 if (SI
.getKind() == SDep::Order
|| SI
.getKind() == SDep::Output
)
2403 Worklist
.push_back(SI
);
2404 Visited
.insert(SuccSU
);
2409 /// If an instruction has a use that spans multiple iterations, then
2410 /// return true. These instructions are characterized by having a back-ege
2411 /// to a Phi, which contains a reference to another Phi.
2412 static SUnit
*multipleIterations(SUnit
*SU
, SwingSchedulerDAG
*DAG
) {
2413 for (auto &P
: SU
->Preds
)
2414 if (DAG
->isBackedge(SU
, P
) && P
.getSUnit()->getInstr()->isPHI())
2415 for (auto &S
: P
.getSUnit()->Succs
)
2416 if (S
.getKind() == SDep::Data
&& S
.getSUnit()->getInstr()->isPHI())
2417 return P
.getSUnit();
2421 /// Compute the scheduling start slot for the instruction. The start slot
2422 /// depends on any predecessor or successor nodes scheduled already.
2423 void SMSchedule::computeStart(SUnit
*SU
, int *MaxEarlyStart
, int *MinLateStart
,
2424 int *MinEnd
, int *MaxStart
, int II
,
2425 SwingSchedulerDAG
*DAG
) {
2426 // Iterate over each instruction that has been scheduled already. The start
2427 // slot computation depends on whether the previously scheduled instruction
2428 // is a predecessor or successor of the specified instruction.
2429 for (int cycle
= getFirstCycle(); cycle
<= LastCycle
; ++cycle
) {
2431 // Iterate over each instruction in the current cycle.
2432 for (SUnit
*I
: getInstructions(cycle
)) {
2433 // Because we're processing a DAG for the dependences, we recognize
2434 // the back-edge in recurrences by anti dependences.
2435 for (unsigned i
= 0, e
= (unsigned)SU
->Preds
.size(); i
!= e
; ++i
) {
2436 const SDep
&Dep
= SU
->Preds
[i
];
2437 if (Dep
.getSUnit() == I
) {
2438 if (!DAG
->isBackedge(SU
, Dep
)) {
2439 int EarlyStart
= cycle
+ Dep
.getLatency() -
2440 DAG
->getDistance(Dep
.getSUnit(), SU
, Dep
) * II
;
2441 *MaxEarlyStart
= std::max(*MaxEarlyStart
, EarlyStart
);
2442 if (DAG
->isLoopCarriedDep(SU
, Dep
, false)) {
2443 int End
= earliestCycleInChain(Dep
) + (II
- 1);
2444 *MinEnd
= std::min(*MinEnd
, End
);
2447 int LateStart
= cycle
- Dep
.getLatency() +
2448 DAG
->getDistance(SU
, Dep
.getSUnit(), Dep
) * II
;
2449 *MinLateStart
= std::min(*MinLateStart
, LateStart
);
2452 // For instruction that requires multiple iterations, make sure that
2453 // the dependent instruction is not scheduled past the definition.
2454 SUnit
*BE
= multipleIterations(I
, DAG
);
2455 if (BE
&& Dep
.getSUnit() == BE
&& !SU
->getInstr()->isPHI() &&
2457 *MinLateStart
= std::min(*MinLateStart
, cycle
);
2459 for (unsigned i
= 0, e
= (unsigned)SU
->Succs
.size(); i
!= e
; ++i
) {
2460 if (SU
->Succs
[i
].getSUnit() == I
) {
2461 const SDep
&Dep
= SU
->Succs
[i
];
2462 if (!DAG
->isBackedge(SU
, Dep
)) {
2463 int LateStart
= cycle
- Dep
.getLatency() +
2464 DAG
->getDistance(SU
, Dep
.getSUnit(), Dep
) * II
;
2465 *MinLateStart
= std::min(*MinLateStart
, LateStart
);
2466 if (DAG
->isLoopCarriedDep(SU
, Dep
)) {
2467 int Start
= latestCycleInChain(Dep
) + 1 - II
;
2468 *MaxStart
= std::max(*MaxStart
, Start
);
2471 int EarlyStart
= cycle
+ Dep
.getLatency() -
2472 DAG
->getDistance(Dep
.getSUnit(), SU
, Dep
) * II
;
2473 *MaxEarlyStart
= std::max(*MaxEarlyStart
, EarlyStart
);
2481 /// Order the instructions within a cycle so that the definitions occur
2482 /// before the uses. Returns true if the instruction is added to the start
2483 /// of the list, or false if added to the end.
2484 void SMSchedule::orderDependence(SwingSchedulerDAG
*SSD
, SUnit
*SU
,
2485 std::deque
<SUnit
*> &Insts
) {
2486 MachineInstr
*MI
= SU
->getInstr();
2487 bool OrderBeforeUse
= false;
2488 bool OrderAfterDef
= false;
2489 bool OrderBeforeDef
= false;
2490 unsigned MoveDef
= 0;
2491 unsigned MoveUse
= 0;
2492 int StageInst1
= stageScheduled(SU
);
2495 for (std::deque
<SUnit
*>::iterator I
= Insts
.begin(), E
= Insts
.end(); I
!= E
;
2497 for (MachineOperand
&MO
: MI
->operands()) {
2498 if (!MO
.isReg() || !MO
.getReg().isVirtual())
2501 Register Reg
= MO
.getReg();
2502 unsigned BasePos
, OffsetPos
;
2503 if (ST
.getInstrInfo()->getBaseAndOffsetPosition(*MI
, BasePos
, OffsetPos
))
2504 if (MI
->getOperand(BasePos
).getReg() == Reg
)
2505 if (unsigned NewReg
= SSD
->getInstrBaseReg(SU
))
2508 std::tie(Reads
, Writes
) =
2509 (*I
)->getInstr()->readsWritesVirtualRegister(Reg
);
2510 if (MO
.isDef() && Reads
&& stageScheduled(*I
) <= StageInst1
) {
2511 OrderBeforeUse
= true;
2514 } else if (MO
.isDef() && Reads
&& stageScheduled(*I
) > StageInst1
) {
2515 // Add the instruction after the scheduled instruction.
2516 OrderAfterDef
= true;
2518 } else if (MO
.isUse() && Writes
&& stageScheduled(*I
) == StageInst1
) {
2519 if (cycleScheduled(*I
) == cycleScheduled(SU
) && !(*I
)->isSucc(SU
)) {
2520 OrderBeforeUse
= true;
2524 OrderAfterDef
= true;
2527 } else if (MO
.isUse() && Writes
&& stageScheduled(*I
) > StageInst1
) {
2528 OrderBeforeUse
= true;
2532 OrderAfterDef
= true;
2535 } else if (MO
.isUse() && Writes
&& stageScheduled(*I
) < StageInst1
) {
2536 // Add the instruction before the scheduled instruction.
2537 OrderBeforeUse
= true;
2540 } else if (MO
.isUse() && stageScheduled(*I
) == StageInst1
&&
2541 isLoopCarriedDefOfUse(SSD
, (*I
)->getInstr(), MO
)) {
2543 OrderBeforeDef
= true;
2548 // Check for order dependences between instructions. Make sure the source
2549 // is ordered before the destination.
2550 for (auto &S
: SU
->Succs
) {
2551 if (S
.getSUnit() != *I
)
2553 if (S
.getKind() == SDep::Order
&& stageScheduled(*I
) == StageInst1
) {
2554 OrderBeforeUse
= true;
2558 // We did not handle HW dependences in previous for loop,
2559 // and we normally set Latency = 0 for Anti deps,
2560 // so may have nodes in same cycle with Anti denpendent on HW regs.
2561 else if (S
.getKind() == SDep::Anti
&& stageScheduled(*I
) == StageInst1
) {
2562 OrderBeforeUse
= true;
2563 if ((MoveUse
== 0) || (Pos
< MoveUse
))
2567 for (auto &P
: SU
->Preds
) {
2568 if (P
.getSUnit() != *I
)
2570 if (P
.getKind() == SDep::Order
&& stageScheduled(*I
) == StageInst1
) {
2571 OrderAfterDef
= true;
2577 // A circular dependence.
2578 if (OrderAfterDef
&& OrderBeforeUse
&& MoveUse
== MoveDef
)
2579 OrderBeforeUse
= false;
2581 // OrderAfterDef takes precedences over OrderBeforeDef. The latter is due
2582 // to a loop-carried dependence.
2584 OrderBeforeUse
= !OrderAfterDef
|| (MoveUse
> MoveDef
);
2586 // The uncommon case when the instruction order needs to be updated because
2587 // there is both a use and def.
2588 if (OrderBeforeUse
&& OrderAfterDef
) {
2589 SUnit
*UseSU
= Insts
.at(MoveUse
);
2590 SUnit
*DefSU
= Insts
.at(MoveDef
);
2591 if (MoveUse
> MoveDef
) {
2592 Insts
.erase(Insts
.begin() + MoveUse
);
2593 Insts
.erase(Insts
.begin() + MoveDef
);
2595 Insts
.erase(Insts
.begin() + MoveDef
);
2596 Insts
.erase(Insts
.begin() + MoveUse
);
2598 orderDependence(SSD
, UseSU
, Insts
);
2599 orderDependence(SSD
, SU
, Insts
);
2600 orderDependence(SSD
, DefSU
, Insts
);
2603 // Put the new instruction first if there is a use in the list. Otherwise,
2604 // put it at the end of the list.
2606 Insts
.push_front(SU
);
2608 Insts
.push_back(SU
);
2611 /// Return true if the scheduled Phi has a loop carried operand.
2612 bool SMSchedule::isLoopCarried(SwingSchedulerDAG
*SSD
, MachineInstr
&Phi
) {
2615 assert(Phi
.isPHI() && "Expecting a Phi.");
2616 SUnit
*DefSU
= SSD
->getSUnit(&Phi
);
2617 unsigned DefCycle
= cycleScheduled(DefSU
);
2618 int DefStage
= stageScheduled(DefSU
);
2620 unsigned InitVal
= 0;
2621 unsigned LoopVal
= 0;
2622 getPhiRegs(Phi
, Phi
.getParent(), InitVal
, LoopVal
);
2623 SUnit
*UseSU
= SSD
->getSUnit(MRI
.getVRegDef(LoopVal
));
2626 if (UseSU
->getInstr()->isPHI())
2628 unsigned LoopCycle
= cycleScheduled(UseSU
);
2629 int LoopStage
= stageScheduled(UseSU
);
2630 return (LoopCycle
> DefCycle
) || (LoopStage
<= DefStage
);
2633 /// Return true if the instruction is a definition that is loop carried
2634 /// and defines the use on the next iteration.
2635 /// v1 = phi(v2, v3)
2636 /// (Def) v3 = op v1
2638 /// If MO appears before Def, then then v1 and v3 may get assigned to the same
2640 bool SMSchedule::isLoopCarriedDefOfUse(SwingSchedulerDAG
*SSD
,
2641 MachineInstr
*Def
, MachineOperand
&MO
) {
2646 MachineInstr
*Phi
= MRI
.getVRegDef(MO
.getReg());
2647 if (!Phi
|| !Phi
->isPHI() || Phi
->getParent() != Def
->getParent())
2649 if (!isLoopCarried(SSD
, *Phi
))
2651 unsigned LoopReg
= getLoopPhiReg(*Phi
, Phi
->getParent());
2652 for (MachineOperand
&DMO
: Def
->all_defs()) {
2653 if (DMO
.getReg() == LoopReg
)
2659 /// Determine transitive dependences of unpipelineable instructions
2660 SmallSet
<SUnit
*, 8> SMSchedule::computeUnpipelineableNodes(
2661 SwingSchedulerDAG
*SSD
, TargetInstrInfo::PipelinerLoopInfo
*PLI
) {
2662 SmallSet
<SUnit
*, 8> DoNotPipeline
;
2663 SmallVector
<SUnit
*, 8> Worklist
;
2665 for (auto &SU
: SSD
->SUnits
)
2666 if (SU
.isInstr() && PLI
->shouldIgnoreForPipelining(SU
.getInstr()))
2667 Worklist
.push_back(&SU
);
2669 while (!Worklist
.empty()) {
2670 auto SU
= Worklist
.pop_back_val();
2671 if (DoNotPipeline
.count(SU
))
2673 LLVM_DEBUG(dbgs() << "Do not pipeline SU(" << SU
->NodeNum
<< ")\n");
2674 DoNotPipeline
.insert(SU
);
2675 for (auto &Dep
: SU
->Preds
)
2676 Worklist
.push_back(Dep
.getSUnit());
2677 if (SU
->getInstr()->isPHI())
2678 for (auto &Dep
: SU
->Succs
)
2679 if (Dep
.getKind() == SDep::Anti
)
2680 Worklist
.push_back(Dep
.getSUnit());
2682 return DoNotPipeline
;
2685 // Determine all instructions upon which any unpipelineable instruction depends
2686 // and ensure that they are in stage 0. If unable to do so, return false.
2687 bool SMSchedule::normalizeNonPipelinedInstructions(
2688 SwingSchedulerDAG
*SSD
, TargetInstrInfo::PipelinerLoopInfo
*PLI
) {
2689 SmallSet
<SUnit
*, 8> DNP
= computeUnpipelineableNodes(SSD
, PLI
);
2691 int NewLastCycle
= INT_MIN
;
2692 for (SUnit
&SU
: SSD
->SUnits
) {
2695 if (!DNP
.contains(&SU
) || stageScheduled(&SU
) == 0) {
2696 NewLastCycle
= std::max(NewLastCycle
, InstrToCycle
[&SU
]);
2700 // Put the non-pipelined instruction as early as possible in the schedule
2701 int NewCycle
= getFirstCycle();
2702 for (auto &Dep
: SU
.Preds
)
2703 NewCycle
= std::max(InstrToCycle
[Dep
.getSUnit()], NewCycle
);
2705 int OldCycle
= InstrToCycle
[&SU
];
2706 if (OldCycle
!= NewCycle
) {
2707 InstrToCycle
[&SU
] = NewCycle
;
2708 auto &OldS
= getInstructions(OldCycle
);
2709 llvm::erase_value(OldS
, &SU
);
2710 getInstructions(NewCycle
).emplace_back(&SU
);
2711 LLVM_DEBUG(dbgs() << "SU(" << SU
.NodeNum
2712 << ") is not pipelined; moving from cycle " << OldCycle
2713 << " to " << NewCycle
<< " Instr:" << *SU
.getInstr());
2715 NewLastCycle
= std::max(NewLastCycle
, NewCycle
);
2717 LastCycle
= NewLastCycle
;
2721 // Check if the generated schedule is valid. This function checks if
2722 // an instruction that uses a physical register is scheduled in a
2723 // different stage than the definition. The pipeliner does not handle
2724 // physical register values that may cross a basic block boundary.
2725 // Furthermore, if a physical def/use pair is assigned to the same
2726 // cycle, orderDependence does not guarantee def/use ordering, so that
2727 // case should be considered invalid. (The test checks for both
2728 // earlier and same-cycle use to be more robust.)
2729 bool SMSchedule::isValidSchedule(SwingSchedulerDAG
*SSD
) {
2730 for (SUnit
&SU
: SSD
->SUnits
) {
2731 if (!SU
.hasPhysRegDefs
)
2733 int StageDef
= stageScheduled(&SU
);
2734 int CycleDef
= InstrToCycle
[&SU
];
2735 assert(StageDef
!= -1 && "Instruction should have been scheduled.");
2736 for (auto &SI
: SU
.Succs
)
2737 if (SI
.isAssignedRegDep() && !SI
.getSUnit()->isBoundaryNode())
2738 if (Register::isPhysicalRegister(SI
.getReg())) {
2739 if (stageScheduled(SI
.getSUnit()) != StageDef
)
2741 if (InstrToCycle
[SI
.getSUnit()] <= CycleDef
)
2748 /// A property of the node order in swing-modulo-scheduling is
2749 /// that for nodes outside circuits the following holds:
2750 /// none of them is scheduled after both a successor and a
2752 /// The method below checks whether the property is met.
2753 /// If not, debug information is printed and statistics information updated.
2754 /// Note that we do not use an assert statement.
2755 /// The reason is that although an invalid node oder may prevent
2756 /// the pipeliner from finding a pipelined schedule for arbitrary II,
2757 /// it does not lead to the generation of incorrect code.
2758 void SwingSchedulerDAG::checkValidNodeOrder(const NodeSetType
&Circuits
) const {
2760 // a sorted vector that maps each SUnit to its index in the NodeOrder
2761 typedef std::pair
<SUnit
*, unsigned> UnitIndex
;
2762 std::vector
<UnitIndex
> Indices(NodeOrder
.size(), std::make_pair(nullptr, 0));
2764 for (unsigned i
= 0, s
= NodeOrder
.size(); i
< s
; ++i
)
2765 Indices
.push_back(std::make_pair(NodeOrder
[i
], i
));
2767 auto CompareKey
= [](UnitIndex i1
, UnitIndex i2
) {
2768 return std::get
<0>(i1
) < std::get
<0>(i2
);
2771 // sort, so that we can perform a binary search
2772 llvm::sort(Indices
, CompareKey
);
2776 // for each SUnit in the NodeOrder, check whether
2777 // it appears after both a successor and a predecessor
2778 // of the SUnit. If this is the case, and the SUnit
2779 // is not part of circuit, then the NodeOrder is not
2781 for (unsigned i
= 0, s
= NodeOrder
.size(); i
< s
; ++i
) {
2782 SUnit
*SU
= NodeOrder
[i
];
2785 bool PredBefore
= false;
2786 bool SuccBefore
= false;
2793 for (SDep
&PredEdge
: SU
->Preds
) {
2794 SUnit
*PredSU
= PredEdge
.getSUnit();
2795 unsigned PredIndex
= std::get
<1>(
2796 *llvm::lower_bound(Indices
, std::make_pair(PredSU
, 0), CompareKey
));
2797 if (!PredSU
->getInstr()->isPHI() && PredIndex
< Index
) {
2804 for (SDep
&SuccEdge
: SU
->Succs
) {
2805 SUnit
*SuccSU
= SuccEdge
.getSUnit();
2806 // Do not process a boundary node, it was not included in NodeOrder,
2807 // hence not in Indices either, call to std::lower_bound() below will
2808 // return Indices.end().
2809 if (SuccSU
->isBoundaryNode())
2811 unsigned SuccIndex
= std::get
<1>(
2812 *llvm::lower_bound(Indices
, std::make_pair(SuccSU
, 0), CompareKey
));
2813 if (!SuccSU
->getInstr()->isPHI() && SuccIndex
< Index
) {
2820 if (PredBefore
&& SuccBefore
&& !SU
->getInstr()->isPHI()) {
2821 // instructions in circuits are allowed to be scheduled
2822 // after both a successor and predecessor.
2823 bool InCircuit
= llvm::any_of(
2824 Circuits
, [SU
](const NodeSet
&Circuit
) { return Circuit
.count(SU
); });
2826 LLVM_DEBUG(dbgs() << "In a circuit, predecessor ";);
2829 NumNodeOrderIssues
++;
2830 LLVM_DEBUG(dbgs() << "Predecessor ";);
2832 LLVM_DEBUG(dbgs() << Pred
->NodeNum
<< " and successor " << Succ
->NodeNum
2833 << " are scheduled before node " << SU
->NodeNum
2840 dbgs() << "Invalid node order found!\n";
2844 /// Attempt to fix the degenerate cases when the instruction serialization
2845 /// causes the register lifetimes to overlap. For example,
2846 /// p' = store_pi(p, b)
2847 /// = load p, offset
2848 /// In this case p and p' overlap, which means that two registers are needed.
2849 /// Instead, this function changes the load to use p' and updates the offset.
2850 void SwingSchedulerDAG::fixupRegisterOverlaps(std::deque
<SUnit
*> &Instrs
) {
2851 unsigned OverlapReg
= 0;
2852 unsigned NewBaseReg
= 0;
2853 for (SUnit
*SU
: Instrs
) {
2854 MachineInstr
*MI
= SU
->getInstr();
2855 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
< e
; ++i
) {
2856 const MachineOperand
&MO
= MI
->getOperand(i
);
2857 // Look for an instruction that uses p. The instruction occurs in the
2858 // same cycle but occurs later in the serialized order.
2859 if (MO
.isReg() && MO
.isUse() && MO
.getReg() == OverlapReg
) {
2860 // Check that the instruction appears in the InstrChanges structure,
2861 // which contains instructions that can have the offset updated.
2862 DenseMap
<SUnit
*, std::pair
<unsigned, int64_t>>::iterator It
=
2863 InstrChanges
.find(SU
);
2864 if (It
!= InstrChanges
.end()) {
2865 unsigned BasePos
, OffsetPos
;
2866 // Update the base register and adjust the offset.
2867 if (TII
->getBaseAndOffsetPosition(*MI
, BasePos
, OffsetPos
)) {
2868 MachineInstr
*NewMI
= MF
.CloneMachineInstr(MI
);
2869 NewMI
->getOperand(BasePos
).setReg(NewBaseReg
);
2871 MI
->getOperand(OffsetPos
).getImm() - It
->second
.second
;
2872 NewMI
->getOperand(OffsetPos
).setImm(NewOffset
);
2873 SU
->setInstr(NewMI
);
2874 MISUnitMap
[NewMI
] = SU
;
2882 // Look for an instruction of the form p' = op(p), which uses and defines
2883 // two virtual registers that get allocated to the same physical register.
2884 unsigned TiedUseIdx
= 0;
2885 if (MI
->isRegTiedToUseOperand(i
, &TiedUseIdx
)) {
2886 // OverlapReg is p in the example above.
2887 OverlapReg
= MI
->getOperand(TiedUseIdx
).getReg();
2888 // NewBaseReg is p' in the example above.
2889 NewBaseReg
= MI
->getOperand(i
).getReg();
2896 /// After the schedule has been formed, call this function to combine
2897 /// the instructions from the different stages/cycles. That is, this
2898 /// function creates a schedule that represents a single iteration.
2899 void SMSchedule::finalizeSchedule(SwingSchedulerDAG
*SSD
) {
2900 // Move all instructions to the first stage from later stages.
2901 for (int cycle
= getFirstCycle(); cycle
<= getFinalCycle(); ++cycle
) {
2902 for (int stage
= 1, lastStage
= getMaxStageCount(); stage
<= lastStage
;
2904 std::deque
<SUnit
*> &cycleInstrs
=
2905 ScheduledInstrs
[cycle
+ (stage
* InitiationInterval
)];
2906 for (SUnit
*SU
: llvm::reverse(cycleInstrs
))
2907 ScheduledInstrs
[cycle
].push_front(SU
);
2911 // Erase all the elements in the later stages. Only one iteration should
2912 // remain in the scheduled list, and it contains all the instructions.
2913 for (int cycle
= getFinalCycle() + 1; cycle
<= LastCycle
; ++cycle
)
2914 ScheduledInstrs
.erase(cycle
);
2916 // Change the registers in instruction as specified in the InstrChanges
2917 // map. We need to use the new registers to create the correct order.
2918 for (const SUnit
&SU
: SSD
->SUnits
)
2919 SSD
->applyInstrChange(SU
.getInstr(), *this);
2921 // Reorder the instructions in each cycle to fix and improve the
2923 for (int Cycle
= getFirstCycle(), E
= getFinalCycle(); Cycle
<= E
; ++Cycle
) {
2924 std::deque
<SUnit
*> &cycleInstrs
= ScheduledInstrs
[Cycle
];
2925 std::deque
<SUnit
*> newOrderPhi
;
2926 for (SUnit
*SU
: cycleInstrs
) {
2927 if (SU
->getInstr()->isPHI())
2928 newOrderPhi
.push_back(SU
);
2930 std::deque
<SUnit
*> newOrderI
;
2931 for (SUnit
*SU
: cycleInstrs
) {
2932 if (!SU
->getInstr()->isPHI())
2933 orderDependence(SSD
, SU
, newOrderI
);
2935 // Replace the old order with the new order.
2936 cycleInstrs
.swap(newOrderPhi
);
2937 llvm::append_range(cycleInstrs
, newOrderI
);
2938 SSD
->fixupRegisterOverlaps(cycleInstrs
);
2941 LLVM_DEBUG(dump(););
2944 void NodeSet::print(raw_ostream
&os
) const {
2945 os
<< "Num nodes " << size() << " rec " << RecMII
<< " mov " << MaxMOV
2946 << " depth " << MaxDepth
<< " col " << Colocate
<< "\n";
2947 for (const auto &I
: Nodes
)
2948 os
<< " SU(" << I
->NodeNum
<< ") " << *(I
->getInstr());
2952 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2953 /// Print the schedule information to the given output.
2954 void SMSchedule::print(raw_ostream
&os
) const {
2955 // Iterate over each cycle.
2956 for (int cycle
= getFirstCycle(); cycle
<= getFinalCycle(); ++cycle
) {
2957 // Iterate over each instruction in the cycle.
2958 const_sched_iterator cycleInstrs
= ScheduledInstrs
.find(cycle
);
2959 for (SUnit
*CI
: cycleInstrs
->second
) {
2960 os
<< "cycle " << cycle
<< " (" << stageScheduled(CI
) << ") ";
2961 os
<< "(" << CI
->NodeNum
<< ") ";
2962 CI
->getInstr()->print(os
);
2968 /// Utility function used for debugging to print the schedule.
2969 LLVM_DUMP_METHOD
void SMSchedule::dump() const { print(dbgs()); }
2970 LLVM_DUMP_METHOD
void NodeSet::dump() const { print(dbgs()); }
2972 void ResourceManager::dumpMRT() const {
2976 std::stringstream SS
;
2978 SS
<< std::setw(4) << "Slot";
2979 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
)
2980 SS
<< std::setw(3) << I
;
2981 SS
<< std::setw(7) << "#Mops"
2983 for (int Slot
= 0; Slot
< InitiationInterval
; ++Slot
) {
2984 SS
<< std::setw(4) << Slot
;
2985 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
)
2986 SS
<< std::setw(3) << MRT
[Slot
][I
];
2987 SS
<< std::setw(7) << NumScheduledMops
[Slot
] << "\n";
2994 void ResourceManager::initProcResourceVectors(
2995 const MCSchedModel
&SM
, SmallVectorImpl
<uint64_t> &Masks
) {
2996 unsigned ProcResourceID
= 0;
2998 // We currently limit the resource kinds to 64 and below so that we can use
2999 // uint64_t for Masks
3000 assert(SM
.getNumProcResourceKinds() < 64 &&
3001 "Too many kinds of resources, unsupported");
3002 // Create a unique bitmask for every processor resource unit.
3003 // Skip resource at index 0, since it always references 'InvalidUnit'.
3004 Masks
.resize(SM
.getNumProcResourceKinds());
3005 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
) {
3006 const MCProcResourceDesc
&Desc
= *SM
.getProcResource(I
);
3007 if (Desc
.SubUnitsIdxBegin
)
3009 Masks
[I
] = 1ULL << ProcResourceID
;
3012 // Create a unique bitmask for every processor resource group.
3013 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
) {
3014 const MCProcResourceDesc
&Desc
= *SM
.getProcResource(I
);
3015 if (!Desc
.SubUnitsIdxBegin
)
3017 Masks
[I
] = 1ULL << ProcResourceID
;
3018 for (unsigned U
= 0; U
< Desc
.NumUnits
; ++U
)
3019 Masks
[I
] |= Masks
[Desc
.SubUnitsIdxBegin
[U
]];
3023 if (SwpShowResMask
) {
3024 dbgs() << "ProcResourceDesc:\n";
3025 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
) {
3026 const MCProcResourceDesc
*ProcResource
= SM
.getProcResource(I
);
3027 dbgs() << format(" %16s(%2d): Mask: 0x%08x, NumUnits:%2d\n",
3028 ProcResource
->Name
, I
, Masks
[I
],
3029 ProcResource
->NumUnits
);
3031 dbgs() << " -----------------\n";
3036 bool ResourceManager::canReserveResources(SUnit
&SU
, int Cycle
) {
3038 if (SwpDebugResource
)
3039 dbgs() << "canReserveResources:\n";
3042 return DFAResources
[positiveModulo(Cycle
, InitiationInterval
)]
3043 ->canReserveResources(&SU
.getInstr()->getDesc());
3045 const MCSchedClassDesc
*SCDesc
= DAG
->getSchedClass(&SU
);
3046 if (!SCDesc
->isValid()) {
3048 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3049 dbgs() << "isPseudo:" << SU
.getInstr()->isPseudo() << "\n";
3054 reserveResources(SCDesc
, Cycle
);
3055 bool Result
= !isOverbooked();
3056 unreserveResources(SCDesc
, Cycle
);
3058 LLVM_DEBUG(if (SwpDebugResource
) dbgs() << "return " << Result
<< "\n\n";);
3062 void ResourceManager::reserveResources(SUnit
&SU
, int Cycle
) {
3064 if (SwpDebugResource
)
3065 dbgs() << "reserveResources:\n";
3068 return DFAResources
[positiveModulo(Cycle
, InitiationInterval
)]
3069 ->reserveResources(&SU
.getInstr()->getDesc());
3071 const MCSchedClassDesc
*SCDesc
= DAG
->getSchedClass(&SU
);
3072 if (!SCDesc
->isValid()) {
3074 dbgs() << "No valid Schedule Class Desc for schedClass!\n";
3075 dbgs() << "isPseudo:" << SU
.getInstr()->isPseudo() << "\n";
3080 reserveResources(SCDesc
, Cycle
);
3083 if (SwpDebugResource
) {
3085 dbgs() << "reserveResources: done!\n\n";
3090 void ResourceManager::reserveResources(const MCSchedClassDesc
*SCDesc
,
3093 for (const MCWriteProcResEntry
&PRE
: make_range(
3094 STI
->getWriteProcResBegin(SCDesc
), STI
->getWriteProcResEnd(SCDesc
)))
3095 for (int C
= Cycle
; C
< Cycle
+ PRE
.Cycles
; ++C
)
3096 ++MRT
[positiveModulo(C
, InitiationInterval
)][PRE
.ProcResourceIdx
];
3098 for (int C
= Cycle
; C
< Cycle
+ SCDesc
->NumMicroOps
; ++C
)
3099 ++NumScheduledMops
[positiveModulo(C
, InitiationInterval
)];
3102 void ResourceManager::unreserveResources(const MCSchedClassDesc
*SCDesc
,
3105 for (const MCWriteProcResEntry
&PRE
: make_range(
3106 STI
->getWriteProcResBegin(SCDesc
), STI
->getWriteProcResEnd(SCDesc
)))
3107 for (int C
= Cycle
; C
< Cycle
+ PRE
.Cycles
; ++C
)
3108 --MRT
[positiveModulo(C
, InitiationInterval
)][PRE
.ProcResourceIdx
];
3110 for (int C
= Cycle
; C
< Cycle
+ SCDesc
->NumMicroOps
; ++C
)
3111 --NumScheduledMops
[positiveModulo(C
, InitiationInterval
)];
3114 bool ResourceManager::isOverbooked() const {
3116 for (int Slot
= 0; Slot
< InitiationInterval
; ++Slot
) {
3117 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
) {
3118 const MCProcResourceDesc
*Desc
= SM
.getProcResource(I
);
3119 if (MRT
[Slot
][I
] > Desc
->NumUnits
)
3122 if (NumScheduledMops
[Slot
] > IssueWidth
)
3128 int ResourceManager::calculateResMIIDFA() const {
3131 // Sort the instructions by the number of available choices for scheduling,
3132 // least to most. Use the number of critical resources as the tie breaker.
3133 FuncUnitSorter FUS
= FuncUnitSorter(*ST
);
3134 for (SUnit
&SU
: DAG
->SUnits
)
3135 FUS
.calcCriticalResources(*SU
.getInstr());
3136 PriorityQueue
<MachineInstr
*, std::vector
<MachineInstr
*>, FuncUnitSorter
>
3139 for (SUnit
&SU
: DAG
->SUnits
)
3140 FuncUnitOrder
.push(SU
.getInstr());
3142 SmallVector
<std::unique_ptr
<DFAPacketizer
>, 8> Resources
;
3143 Resources
.push_back(
3144 std::unique_ptr
<DFAPacketizer
>(TII
->CreateTargetScheduleState(*ST
)));
3146 while (!FuncUnitOrder
.empty()) {
3147 MachineInstr
*MI
= FuncUnitOrder
.top();
3148 FuncUnitOrder
.pop();
3149 if (TII
->isZeroCost(MI
->getOpcode()))
3152 // Attempt to reserve the instruction in an existing DFA. At least one
3153 // DFA is needed for each cycle.
3154 unsigned NumCycles
= DAG
->getSUnit(MI
)->Latency
;
3155 unsigned ReservedCycles
= 0;
3156 auto *RI
= Resources
.begin();
3157 auto *RE
= Resources
.end();
3159 dbgs() << "Trying to reserve resource for " << NumCycles
3160 << " cycles for \n";
3163 for (unsigned C
= 0; C
< NumCycles
; ++C
)
3165 if ((*RI
)->canReserveResources(*MI
)) {
3166 (*RI
)->reserveResources(*MI
);
3172 LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
3173 << ", NumCycles:" << NumCycles
<< "\n");
3174 // Add new DFAs, if needed, to reserve resources.
3175 for (unsigned C
= ReservedCycles
; C
< NumCycles
; ++C
) {
3176 LLVM_DEBUG(if (SwpDebugResource
) dbgs()
3177 << "NewResource created to reserve resources"
3179 auto *NewResource
= TII
->CreateTargetScheduleState(*ST
);
3180 assert(NewResource
->canReserveResources(*MI
) && "Reserve error.");
3181 NewResource
->reserveResources(*MI
);
3182 Resources
.push_back(std::unique_ptr
<DFAPacketizer
>(NewResource
));
3186 int Resmii
= Resources
.size();
3187 LLVM_DEBUG(dbgs() << "Return Res MII:" << Resmii
<< "\n");
3191 int ResourceManager::calculateResMII() const {
3193 return calculateResMIIDFA();
3195 // Count each resource consumption and divide it by the number of units.
3196 // ResMII is the max value among them.
3199 SmallVector
<uint64_t> ResourceCount(SM
.getNumProcResourceKinds());
3200 for (SUnit
&SU
: DAG
->SUnits
) {
3201 if (TII
->isZeroCost(SU
.getInstr()->getOpcode()))
3204 const MCSchedClassDesc
*SCDesc
= DAG
->getSchedClass(&SU
);
3205 if (!SCDesc
->isValid())
3209 if (SwpDebugResource
) {
3211 dbgs() << " #Mops: " << SCDesc
->NumMicroOps
<< "\n"
3212 << " WriteProcRes: ";
3215 NumMops
+= SCDesc
->NumMicroOps
;
3216 for (const MCWriteProcResEntry
&PRE
:
3217 make_range(STI
->getWriteProcResBegin(SCDesc
),
3218 STI
->getWriteProcResEnd(SCDesc
))) {
3220 if (SwpDebugResource
) {
3221 const MCProcResourceDesc
*Desc
=
3222 SM
.getProcResource(PRE
.ProcResourceIdx
);
3223 dbgs() << Desc
->Name
<< ": " << PRE
.Cycles
<< ", ";
3226 ResourceCount
[PRE
.ProcResourceIdx
] += PRE
.Cycles
;
3228 LLVM_DEBUG(if (SwpDebugResource
) dbgs() << "\n");
3231 int Result
= (NumMops
+ IssueWidth
- 1) / IssueWidth
;
3233 if (SwpDebugResource
)
3234 dbgs() << "#Mops: " << NumMops
<< ", "
3235 << "IssueWidth: " << IssueWidth
<< ", "
3236 << "Cycles: " << Result
<< "\n";
3240 if (SwpDebugResource
) {
3241 std::stringstream SS
;
3242 SS
<< std::setw(2) << "ID" << std::setw(16) << "Name" << std::setw(10)
3243 << "Units" << std::setw(10) << "Consumed" << std::setw(10) << "Cycles"
3248 for (unsigned I
= 1, E
= SM
.getNumProcResourceKinds(); I
< E
; ++I
) {
3249 const MCProcResourceDesc
*Desc
= SM
.getProcResource(I
);
3250 int Cycles
= (ResourceCount
[I
] + Desc
->NumUnits
- 1) / Desc
->NumUnits
;
3252 if (SwpDebugResource
) {
3253 std::stringstream SS
;
3254 SS
<< std::setw(2) << I
<< std::setw(16) << Desc
->Name
<< std::setw(10)
3255 << Desc
->NumUnits
<< std::setw(10) << ResourceCount
[I
]
3256 << std::setw(10) << Cycles
<< "\n";
3260 if (Cycles
> Result
)
3266 void ResourceManager::init(int II
) {
3267 InitiationInterval
= II
;
3268 DFAResources
.clear();
3269 DFAResources
.resize(II
);
3270 for (auto &I
: DFAResources
)
3271 I
.reset(ST
->getInstrInfo()->CreateTargetScheduleState(*ST
));
3273 MRT
.resize(II
, SmallVector
<uint64_t>(SM
.getNumProcResourceKinds()));
3274 NumScheduledMops
.clear();
3275 NumScheduledMops
.resize(II
);