1 //===- MachineScheduler.cpp - Machine Instruction Scheduler ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // MachineScheduler schedules machine instructions after phi elimination. It
11 // preserves LiveIntervals so it can be invoked before register allocation.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "misched"
17 #include "llvm/CodeGen/MachineScheduler.h"
18 #include "llvm/ADT/PriorityQueue.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineDominators.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterClassInfo.h"
26 #include "llvm/CodeGen/ScheduleDFS.h"
27 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GraphWriter.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetInstrInfo.h"
39 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
40 cl::desc("Force top-down list scheduling"));
41 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
42 cl::desc("Force bottom-up list scheduling"));
46 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
47 cl::desc("Pop up a window to show MISched dags after they are processed"));
49 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
50 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
52 static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
53 cl::desc("Only schedule this function"));
54 static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
55 cl::desc("Only schedule this MBB#"));
57 static bool ViewMISchedDAGs = false;
60 static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
61 cl::desc("Enable register pressure scheduling."), cl::init(true));
63 static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
64 cl::desc("Enable cyclic critical path analysis."), cl::init(true));
66 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
67 cl::desc("Enable load clustering."), cl::init(true));
69 // Experimental heuristics
70 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
71 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
73 static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
74 cl::desc("Verify machine instrs before and after machine scheduling"));
76 // DAG subtrees must have at least this many nodes.
77 static const unsigned MinSubtreeSize = 8;
79 // Pin the vtables to this file.
80 void MachineSchedStrategy::anchor() {}
81 void ScheduleDAGMutation::anchor() {}
83 //===----------------------------------------------------------------------===//
84 // Machine Instruction Scheduling Pass and Registry
85 //===----------------------------------------------------------------------===//
87 MachineSchedContext::MachineSchedContext():
88 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
89 RegClassInfo = new RegisterClassInfo();
92 MachineSchedContext::~MachineSchedContext() {
97 /// Base class for a machine scheduler class that can run at any point.
98 class MachineSchedulerBase : public MachineSchedContext,
99 public MachineFunctionPass {
101 MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
103 virtual void print(raw_ostream &O, const Module* = 0) const;
106 void scheduleRegions(ScheduleDAGInstrs &Scheduler);
109 /// MachineScheduler runs after coalescing and before register allocation.
110 class MachineScheduler : public MachineSchedulerBase {
114 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
116 virtual bool runOnMachineFunction(MachineFunction&);
118 static char ID; // Class identification, replacement for typeinfo
121 ScheduleDAGInstrs *createMachineScheduler();
124 /// PostMachineScheduler runs after shortly before code emission.
125 class PostMachineScheduler : public MachineSchedulerBase {
127 PostMachineScheduler();
129 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
131 virtual bool runOnMachineFunction(MachineFunction&);
133 static char ID; // Class identification, replacement for typeinfo
136 ScheduleDAGInstrs *createPostMachineScheduler();
140 char MachineScheduler::ID = 0;
142 char &llvm::MachineSchedulerID = MachineScheduler::ID;
144 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
145 "Machine Instruction Scheduler", false, false)
146 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
147 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
148 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
149 INITIALIZE_PASS_END(MachineScheduler, "misched",
150 "Machine Instruction Scheduler", false, false)
152 MachineScheduler::MachineScheduler()
153 : MachineSchedulerBase(ID) {
154 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
157 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
158 AU.setPreservesCFG();
159 AU.addRequiredID(MachineDominatorsID);
160 AU.addRequired<MachineLoopInfo>();
161 AU.addRequired<AliasAnalysis>();
162 AU.addRequired<TargetPassConfig>();
163 AU.addRequired<SlotIndexes>();
164 AU.addPreserved<SlotIndexes>();
165 AU.addRequired<LiveIntervals>();
166 AU.addPreserved<LiveIntervals>();
167 MachineFunctionPass::getAnalysisUsage(AU);
170 char PostMachineScheduler::ID = 0;
172 char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
174 INITIALIZE_PASS(PostMachineScheduler, "postmisched",
175 "PostRA Machine Instruction Scheduler", false, false)
177 PostMachineScheduler::PostMachineScheduler()
178 : MachineSchedulerBase(ID) {
179 initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
182 void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
183 AU.setPreservesCFG();
184 AU.addRequiredID(MachineDominatorsID);
185 AU.addRequired<MachineLoopInfo>();
186 AU.addRequired<TargetPassConfig>();
187 MachineFunctionPass::getAnalysisUsage(AU);
190 MachinePassRegistry MachineSchedRegistry::Registry;
192 /// A dummy default scheduler factory indicates whether the scheduler
193 /// is overridden on the command line.
194 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
198 /// MachineSchedOpt allows command line selection of the scheduler.
199 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
200 RegisterPassParser<MachineSchedRegistry> >
201 MachineSchedOpt("misched",
202 cl::init(&useDefaultMachineSched), cl::Hidden,
203 cl::desc("Machine instruction scheduler to use"));
205 static MachineSchedRegistry
206 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
207 useDefaultMachineSched);
209 /// Forward declare the standard machine scheduler. This will be used as the
210 /// default scheduler if the target does not set a default.
211 static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C);
212 static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C);
214 /// Decrement this iterator until reaching the top or a non-debug instr.
215 static MachineBasicBlock::const_iterator
216 priorNonDebug(MachineBasicBlock::const_iterator I,
217 MachineBasicBlock::const_iterator Beg) {
218 assert(I != Beg && "reached the top of the region, cannot decrement");
220 if (!I->isDebugValue())
226 /// Non-const version.
227 static MachineBasicBlock::iterator
228 priorNonDebug(MachineBasicBlock::iterator I,
229 MachineBasicBlock::const_iterator Beg) {
230 return const_cast<MachineInstr*>(
231 &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg));
234 /// If this iterator is a debug value, increment until reaching the End or a
235 /// non-debug instruction.
236 static MachineBasicBlock::const_iterator
237 nextIfDebug(MachineBasicBlock::const_iterator I,
238 MachineBasicBlock::const_iterator End) {
239 for(; I != End; ++I) {
240 if (!I->isDebugValue())
246 /// Non-const version.
247 static MachineBasicBlock::iterator
248 nextIfDebug(MachineBasicBlock::iterator I,
249 MachineBasicBlock::const_iterator End) {
250 // Cast the return value to nonconst MachineInstr, then cast to an
251 // instr_iterator, which does not check for null, finally return a
253 return MachineBasicBlock::instr_iterator(
254 const_cast<MachineInstr*>(
255 &*nextIfDebug(MachineBasicBlock::const_iterator(I), End)));
258 /// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
259 ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
260 // Select the scheduler, or set the default.
261 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
262 if (Ctor != useDefaultMachineSched)
265 // Get the default scheduler set by the target for this function.
266 ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
270 // Default to GenericScheduler.
271 return createGenericSchedLive(this);
274 /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
275 /// the caller. We don't have a command line option to override the postRA
276 /// scheduler. The Target must configure it.
277 ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
278 // Get the postRA scheduler set by the target for this function.
279 ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
283 // Default to GenericScheduler.
284 return createGenericSchedPostRA(this);
287 /// Top-level MachineScheduler pass driver.
289 /// Visit blocks in function order. Divide each block into scheduling regions
290 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
291 /// consistent with the DAG builder, which traverses the interior of the
292 /// scheduling regions bottom-up.
294 /// This design avoids exposing scheduling boundaries to the DAG builder,
295 /// simplifying the DAG builder's support for "special" target instructions.
296 /// At the same time the design allows target schedulers to operate across
297 /// scheduling boundaries, for example to bundle the boudary instructions
298 /// without reordering them. This creates complexity, because the target
299 /// scheduler must update the RegionBegin and RegionEnd positions cached by
300 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
301 /// design would be to split blocks at scheduling boundaries, but LLVM has a
302 /// general bias against block splitting purely for implementation simplicity.
303 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
304 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
306 // Initialize the context of the pass.
308 MLI = &getAnalysis<MachineLoopInfo>();
309 MDT = &getAnalysis<MachineDominatorTree>();
310 PassConfig = &getAnalysis<TargetPassConfig>();
311 AA = &getAnalysis<AliasAnalysis>();
313 LIS = &getAnalysis<LiveIntervals>();
315 if (VerifyScheduling) {
317 MF->verify(this, "Before machine scheduling.");
319 RegClassInfo->runOnMachineFunction(*MF);
321 // Instantiate the selected scheduler for this target, function, and
322 // optimization level.
323 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
324 scheduleRegions(*Scheduler);
327 if (VerifyScheduling)
328 MF->verify(this, "After machine scheduling.");
332 bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
333 DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
335 // Initialize the context of the pass.
337 PassConfig = &getAnalysis<TargetPassConfig>();
339 if (VerifyScheduling)
340 MF->verify(this, "Before post machine scheduling.");
342 // Instantiate the selected scheduler for this target, function, and
343 // optimization level.
344 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
345 scheduleRegions(*Scheduler);
347 if (VerifyScheduling)
348 MF->verify(this, "After post machine scheduling.");
352 /// Return true of the given instruction should not be included in a scheduling
355 /// MachineScheduler does not currently support scheduling across calls. To
356 /// handle calls, the DAG builder needs to be modified to create register
357 /// anti/output dependencies on the registers clobbered by the call's regmask
358 /// operand. In PreRA scheduling, the stack pointer adjustment already prevents
359 /// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
360 /// the boundary, but there would be no benefit to postRA scheduling across
361 /// calls this late anyway.
362 static bool isSchedBoundary(MachineBasicBlock::iterator MI,
363 MachineBasicBlock *MBB,
365 const TargetInstrInfo *TII,
367 return MI->isCall() || TII->isSchedulingBoundary(MI, MBB, *MF);
370 /// Main driver for both MachineScheduler and PostMachineScheduler.
371 void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler) {
372 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
373 bool IsPostRA = Scheduler.isPostRA();
375 // Visit all machine basic blocks.
377 // TODO: Visit blocks in global postorder or postorder within the bottom-up
378 // loop tree. Then we can optionally compute global RegPressure.
379 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
380 MBB != MBBEnd; ++MBB) {
382 Scheduler.startBlock(MBB);
385 if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
387 if (SchedOnlyBlock.getNumOccurrences()
388 && (int)SchedOnlyBlock != MBB->getNumber())
392 // Break the block into scheduling regions [I, RegionEnd), and schedule each
393 // region as soon as it is discovered. RegionEnd points the scheduling
394 // boundary at the bottom of the region. The DAG does not include RegionEnd,
395 // but the region does (i.e. the next RegionEnd is above the previous
396 // RegionBegin). If the current block has no terminator then RegionEnd ==
397 // MBB->end() for the bottom region.
399 // The Scheduler may insert instructions during either schedule() or
400 // exitRegion(), even for empty regions. So the local iterators 'I' and
401 // 'RegionEnd' are invalid across these calls.
403 // MBB::size() uses instr_iterator to count. Here we need a bundle to count
404 // as a single instruction.
405 unsigned RemainingInstrs = std::distance(MBB->begin(), MBB->end());
406 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
407 RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
409 // Avoid decrementing RegionEnd for blocks with no terminator.
410 if (RegionEnd != MBB->end() ||
411 isSchedBoundary(std::prev(RegionEnd), MBB, MF, TII, IsPostRA)) {
413 // Count the boundary instruction.
417 // The next region starts above the previous region. Look backward in the
418 // instruction stream until we find the nearest boundary.
419 unsigned NumRegionInstrs = 0;
420 MachineBasicBlock::iterator I = RegionEnd;
421 for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
422 if (isSchedBoundary(std::prev(I), MBB, MF, TII, IsPostRA))
425 // Notify the scheduler of the region, even if we may skip scheduling
426 // it. Perhaps it still needs to be bundled.
427 Scheduler.enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
429 // Skip empty scheduling regions (0 or 1 schedulable instructions).
430 if (I == RegionEnd || I == std::prev(RegionEnd)) {
431 // Close the current region. Bundle the terminator if needed.
432 // This invalidates 'RegionEnd' and 'I'.
433 Scheduler.exitRegion();
436 DEBUG(dbgs() << "********** " << ((Scheduler.isPostRA()) ? "PostRA " : "")
437 << "MI Scheduling **********\n");
438 DEBUG(dbgs() << MF->getName()
439 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
440 << "\n From: " << *I << " To: ";
441 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
442 else dbgs() << "End";
443 dbgs() << " RegionInstrs: " << NumRegionInstrs
444 << " Remaining: " << RemainingInstrs << "\n");
446 // Schedule a region: possibly reorder instructions.
447 // This invalidates 'RegionEnd' and 'I'.
448 Scheduler.schedule();
450 // Close the current region.
451 Scheduler.exitRegion();
453 // Scheduling has invalidated the current iterator 'I'. Ask the
454 // scheduler for the top of it's scheduled region.
455 RegionEnd = Scheduler.begin();
457 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
458 Scheduler.finishBlock();
459 if (Scheduler.isPostRA()) {
460 // FIXME: Ideally, no further passes should rely on kill flags. However,
461 // thumb2 size reduction is currently an exception.
462 Scheduler.fixupKills(MBB);
465 Scheduler.finalizeSchedule();
468 void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
472 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
473 void ReadyQueue::dump() {
474 dbgs() << Name << ": ";
475 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
476 dbgs() << Queue[i]->NodeNum << " ";
481 //===----------------------------------------------------------------------===//
482 // ScheduleDAGMI - Basic machine instruction scheduling. This is
483 // independent of PreRA/PostRA scheduling and involves no extra book-keeping for
484 // virtual registers.
485 // ===----------------------------------------------------------------------===/
487 ScheduleDAGMI::~ScheduleDAGMI() {
488 DeleteContainerPointers(Mutations);
492 bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
493 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
496 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
497 if (SuccSU != &ExitSU) {
498 // Do not use WillCreateCycle, it assumes SD scheduling.
499 // If Pred is reachable from Succ, then the edge creates a cycle.
500 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
502 Topo.AddPred(SuccSU, PredDep.getSUnit());
504 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
505 // Return true regardless of whether a new edge needed to be inserted.
509 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
510 /// NumPredsLeft reaches zero, release the successor node.
512 /// FIXME: Adjust SuccSU height based on MinLatency.
513 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
514 SUnit *SuccSU = SuccEdge->getSUnit();
516 if (SuccEdge->isWeak()) {
517 --SuccSU->WeakPredsLeft;
518 if (SuccEdge->isCluster())
519 NextClusterSucc = SuccSU;
523 if (SuccSU->NumPredsLeft == 0) {
524 dbgs() << "*** Scheduling failed! ***\n";
526 dbgs() << " has been released too many times!\n";
530 --SuccSU->NumPredsLeft;
531 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
532 SchedImpl->releaseTopNode(SuccSU);
535 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
536 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
537 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
539 releaseSucc(SU, &*I);
543 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
544 /// NumSuccsLeft reaches zero, release the predecessor node.
546 /// FIXME: Adjust PredSU height based on MinLatency.
547 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
548 SUnit *PredSU = PredEdge->getSUnit();
550 if (PredEdge->isWeak()) {
551 --PredSU->WeakSuccsLeft;
552 if (PredEdge->isCluster())
553 NextClusterPred = PredSU;
557 if (PredSU->NumSuccsLeft == 0) {
558 dbgs() << "*** Scheduling failed! ***\n";
560 dbgs() << " has been released too many times!\n";
564 --PredSU->NumSuccsLeft;
565 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
566 SchedImpl->releaseBottomNode(PredSU);
569 /// releasePredecessors - Call releasePred on each of SU's predecessors.
570 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
571 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
573 releasePred(SU, &*I);
577 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
578 /// crossing a scheduling boundary. [begin, end) includes all instructions in
579 /// the region, including the boundary itself and single-instruction regions
580 /// that don't get scheduled.
581 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
582 MachineBasicBlock::iterator begin,
583 MachineBasicBlock::iterator end,
584 unsigned regioninstrs)
586 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
588 SchedImpl->initPolicy(begin, end, regioninstrs);
591 /// This is normally called from the main scheduler loop but may also be invoked
592 /// by the scheduling strategy to perform additional code motion.
593 void ScheduleDAGMI::moveInstruction(
594 MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
595 // Advance RegionBegin if the first instruction moves down.
596 if (&*RegionBegin == MI)
599 // Update the instruction stream.
600 BB->splice(InsertPos, BB, MI);
602 // Update LiveIntervals
604 LIS->handleMove(MI, /*UpdateFlags=*/true);
606 // Recede RegionBegin if an instruction moves above the first.
607 if (RegionBegin == InsertPos)
611 bool ScheduleDAGMI::checkSchedLimit() {
613 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
614 CurrentTop = CurrentBottom;
617 ++NumInstrsScheduled;
622 /// Per-region scheduling driver, called back from
623 /// MachineScheduler::runOnMachineFunction. This is a simplified driver that
624 /// does not consider liveness or register pressure. It is useful for PostRA
625 /// scheduling and potentially other custom schedulers.
626 void ScheduleDAGMI::schedule() {
630 Topo.InitDAGTopologicalSorting();
634 SmallVector<SUnit*, 8> TopRoots, BotRoots;
635 findRootsAndBiasEdges(TopRoots, BotRoots);
637 // Initialize the strategy before modifying the DAG.
638 // This may initialize a DFSResult to be used for queue priority.
639 SchedImpl->initialize(this);
641 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
642 SUnits[su].dumpAll(this));
643 if (ViewMISchedDAGs) viewGraph();
645 // Initialize ready queues now that the DAG and priority data are finalized.
646 initQueues(TopRoots, BotRoots);
648 bool IsTopNode = false;
649 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
650 assert(!SU->isScheduled && "Node already scheduled");
651 if (!checkSchedLimit())
654 MachineInstr *MI = SU->getInstr();
656 assert(SU->isTopReady() && "node still has unscheduled dependencies");
657 if (&*CurrentTop == MI)
658 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
660 moveInstruction(MI, CurrentTop);
663 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
664 MachineBasicBlock::iterator priorII =
665 priorNonDebug(CurrentBottom, CurrentTop);
667 CurrentBottom = priorII;
669 if (&*CurrentTop == MI)
670 CurrentTop = nextIfDebug(++CurrentTop, priorII);
671 moveInstruction(MI, CurrentBottom);
675 updateQueues(SU, IsTopNode);
677 // Notify the scheduling strategy after updating the DAG.
678 SchedImpl->schedNode(SU, IsTopNode);
680 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
685 unsigned BBNum = begin()->getParent()->getNumber();
686 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
692 /// Apply each ScheduleDAGMutation step in order.
693 void ScheduleDAGMI::postprocessDAG() {
694 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
695 Mutations[i]->apply(this);
700 findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
701 SmallVectorImpl<SUnit*> &BotRoots) {
702 for (std::vector<SUnit>::iterator
703 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
705 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
707 // Order predecessors so DFSResult follows the critical path.
708 SU->biasCriticalPath();
710 // A SUnit is ready to top schedule if it has no predecessors.
711 if (!I->NumPredsLeft)
712 TopRoots.push_back(SU);
713 // A SUnit is ready to bottom schedule if it has no successors.
714 if (!I->NumSuccsLeft)
715 BotRoots.push_back(SU);
717 ExitSU.biasCriticalPath();
720 /// Identify DAG roots and setup scheduler queues.
721 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
722 ArrayRef<SUnit*> BotRoots) {
723 NextClusterSucc = NULL;
724 NextClusterPred = NULL;
726 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
728 // Nodes with unreleased weak edges can still be roots.
729 // Release top roots in forward order.
730 for (SmallVectorImpl<SUnit*>::const_iterator
731 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
732 SchedImpl->releaseTopNode(*I);
734 // Release bottom roots in reverse order so the higher priority nodes appear
735 // first. This is more natural and slightly more efficient.
736 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
737 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
738 SchedImpl->releaseBottomNode(*I);
741 releaseSuccessors(&EntrySU);
742 releasePredecessors(&ExitSU);
744 SchedImpl->registerRoots();
746 // Advance past initial DebugValues.
747 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
748 CurrentBottom = RegionEnd;
751 /// Update scheduler queues after scheduling an instruction.
752 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
753 // Release dependent instructions for scheduling.
755 releaseSuccessors(SU);
757 releasePredecessors(SU);
759 SU->isScheduled = true;
762 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
763 void ScheduleDAGMI::placeDebugValues() {
764 // If first instruction was a DBG_VALUE then put it back.
766 BB->splice(RegionBegin, BB, FirstDbgValue);
767 RegionBegin = FirstDbgValue;
770 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
771 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
772 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
773 MachineInstr *DbgValue = P.first;
774 MachineBasicBlock::iterator OrigPrevMI = P.second;
775 if (&*RegionBegin == DbgValue)
777 BB->splice(++OrigPrevMI, BB, DbgValue);
778 if (OrigPrevMI == std::prev(RegionEnd))
779 RegionEnd = DbgValue;
782 FirstDbgValue = NULL;
785 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
786 void ScheduleDAGMI::dumpSchedule() const {
787 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
788 if (SUnit *SU = getSUnit(&(*MI)))
791 dbgs() << "Missing SUnit\n";
796 //===----------------------------------------------------------------------===//
797 // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
799 //===----------------------------------------------------------------------===//
801 ScheduleDAGMILive::~ScheduleDAGMILive() {
805 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
806 /// crossing a scheduling boundary. [begin, end) includes all instructions in
807 /// the region, including the boundary itself and single-instruction regions
808 /// that don't get scheduled.
809 void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
810 MachineBasicBlock::iterator begin,
811 MachineBasicBlock::iterator end,
812 unsigned regioninstrs)
814 // ScheduleDAGMI initializes SchedImpl's per-region policy.
815 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
817 // For convenience remember the end of the liveness region.
818 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
820 SUPressureDiffs.clear();
822 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
825 // Setup the register pressure trackers for the top scheduled top and bottom
826 // scheduled regions.
827 void ScheduleDAGMILive::initRegPressure() {
828 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
829 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
831 // Close the RPTracker to finalize live ins.
832 RPTracker.closeRegion();
834 DEBUG(RPTracker.dump());
836 // Initialize the live ins and live outs.
837 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
838 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
840 // Close one end of the tracker so we can call
841 // getMaxUpward/DownwardPressureDelta before advancing across any
842 // instructions. This converts currently live regs into live ins/outs.
843 TopRPTracker.closeTop();
844 BotRPTracker.closeBottom();
846 BotRPTracker.initLiveThru(RPTracker);
847 if (!BotRPTracker.getLiveThru().empty()) {
848 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
849 DEBUG(dbgs() << "Live Thru: ";
850 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
853 // For each live out vreg reduce the pressure change associated with other
854 // uses of the same vreg below the live-out reaching def.
855 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
857 // Account for liveness generated by the region boundary.
858 if (LiveRegionEnd != RegionEnd) {
859 SmallVector<unsigned, 8> LiveUses;
860 BotRPTracker.recede(&LiveUses);
861 updatePressureDiffs(LiveUses);
864 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
866 // Cache the list of excess pressure sets in this region. This will also track
867 // the max pressure in the scheduled code for these sets.
868 RegionCriticalPSets.clear();
869 const std::vector<unsigned> &RegionPressure =
870 RPTracker.getPressure().MaxSetPressure;
871 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
872 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
873 if (RegionPressure[i] > Limit) {
874 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
875 << " Limit " << Limit
876 << " Actual " << RegionPressure[i] << "\n");
877 RegionCriticalPSets.push_back(PressureChange(i));
880 DEBUG(dbgs() << "Excess PSets: ";
881 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
882 dbgs() << TRI->getRegPressureSetName(
883 RegionCriticalPSets[i].getPSet()) << " ";
887 void ScheduleDAGMILive::
888 updateScheduledPressure(const SUnit *SU,
889 const std::vector<unsigned> &NewMaxPressure) {
890 const PressureDiff &PDiff = getPressureDiff(SU);
891 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
892 for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
896 unsigned ID = I->getPSet();
897 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
899 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
900 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
901 && NewMaxPressure[ID] <= INT16_MAX)
902 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
904 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
905 if (NewMaxPressure[ID] >= Limit - 2) {
906 DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
907 << NewMaxPressure[ID] << " > " << Limit << "(+ "
908 << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
913 /// Update the PressureDiff array for liveness after scheduling this
915 void ScheduleDAGMILive::updatePressureDiffs(ArrayRef<unsigned> LiveUses) {
916 for (unsigned LUIdx = 0, LUEnd = LiveUses.size(); LUIdx != LUEnd; ++LUIdx) {
917 /// FIXME: Currently assuming single-use physregs.
918 unsigned Reg = LiveUses[LUIdx];
919 DEBUG(dbgs() << " LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
920 if (!TRI->isVirtualRegister(Reg))
923 // This may be called before CurrentBottom has been initialized. However,
924 // BotRPTracker must have a valid position. We want the value live into the
925 // instruction or live out of the block, so ask for the previous
926 // instruction's live-out.
927 const LiveInterval &LI = LIS->getInterval(Reg);
929 MachineBasicBlock::const_iterator I =
930 nextIfDebug(BotRPTracker.getPos(), BB->end());
932 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
934 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(I));
937 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
938 assert(VNI && "No live value at use.");
939 for (VReg2UseMap::iterator
940 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
942 DEBUG(dbgs() << " UpdateRegP: SU(" << SU->NodeNum << ") "
944 // If this use comes before the reaching def, it cannot be a last use, so
945 // descrease its pressure change.
946 if (!SU->isScheduled && SU != &ExitSU) {
948 = LI.Query(LIS->getInstructionIndex(SU->getInstr()));
949 if (LRQ.valueIn() == VNI)
950 getPressureDiff(SU).addPressureChange(Reg, true, &MRI);
956 /// schedule - Called back from MachineScheduler::runOnMachineFunction
957 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
958 /// only includes instructions that have DAG nodes, not scheduling boundaries.
960 /// This is a skeletal driver, with all the functionality pushed into helpers,
961 /// so that it can be easilly extended by experimental schedulers. Generally,
962 /// implementing MachineSchedStrategy should be sufficient to implement a new
963 /// scheduling algorithm. However, if a scheduler further subclasses
964 /// ScheduleDAGMILive then it will want to override this virtual method in order
965 /// to update any specialized state.
966 void ScheduleDAGMILive::schedule() {
967 buildDAGWithRegPressure();
969 Topo.InitDAGTopologicalSorting();
973 SmallVector<SUnit*, 8> TopRoots, BotRoots;
974 findRootsAndBiasEdges(TopRoots, BotRoots);
976 // Initialize the strategy before modifying the DAG.
977 // This may initialize a DFSResult to be used for queue priority.
978 SchedImpl->initialize(this);
980 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
981 SUnits[su].dumpAll(this));
982 if (ViewMISchedDAGs) viewGraph();
984 // Initialize ready queues now that the DAG and priority data are finalized.
985 initQueues(TopRoots, BotRoots);
987 if (ShouldTrackPressure) {
988 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
989 TopRPTracker.setPos(CurrentTop);
992 bool IsTopNode = false;
993 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
994 assert(!SU->isScheduled && "Node already scheduled");
995 if (!checkSchedLimit())
998 scheduleMI(SU, IsTopNode);
1000 updateQueues(SU, IsTopNode);
1003 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1004 if (!ScheduledTrees.test(SubtreeID)) {
1005 ScheduledTrees.set(SubtreeID);
1006 DFSResult->scheduleTree(SubtreeID);
1007 SchedImpl->scheduleTree(SubtreeID);
1011 // Notify the scheduling strategy after updating the DAG.
1012 SchedImpl->schedNode(SU, IsTopNode);
1014 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1019 unsigned BBNum = begin()->getParent()->getNumber();
1020 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1026 /// Build the DAG and setup three register pressure trackers.
1027 void ScheduleDAGMILive::buildDAGWithRegPressure() {
1028 if (!ShouldTrackPressure) {
1030 RegionCriticalPSets.clear();
1031 buildSchedGraph(AA);
1035 // Initialize the register pressure tracker used by buildSchedGraph.
1036 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1037 /*TrackUntiedDefs=*/true);
1039 // Account for liveness generate by the region boundary.
1040 if (LiveRegionEnd != RegionEnd)
1043 // Build the DAG, and compute current register pressure.
1044 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs);
1046 // Initialize top/bottom trackers after computing region pressure.
1050 void ScheduleDAGMILive::computeDFSResult() {
1052 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1054 ScheduledTrees.clear();
1055 DFSResult->resize(SUnits.size());
1056 DFSResult->compute(SUnits);
1057 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1060 /// Compute the max cyclic critical path through the DAG. The scheduling DAG
1061 /// only provides the critical path for single block loops. To handle loops that
1062 /// span blocks, we could use the vreg path latencies provided by
1063 /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1064 /// available for use in the scheduler.
1066 /// The cyclic path estimation identifies a def-use pair that crosses the back
1067 /// edge and considers the depth and height of the nodes. For example, consider
1068 /// the following instruction sequence where each instruction has unit latency
1069 /// and defines an epomymous virtual register:
1071 /// a->b(a,c)->c(b)->d(c)->exit
1073 /// The cyclic critical path is a two cycles: b->c->b
1074 /// The acyclic critical path is four cycles: a->b->c->d->exit
1075 /// LiveOutHeight = height(c) = len(c->d->exit) = 2
1076 /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1077 /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1078 /// LiveInDepth = depth(b) = len(a->b) = 1
1080 /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1081 /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1082 /// CyclicCriticalPath = min(2, 2) = 2
1084 /// This could be relevant to PostRA scheduling, but is currently implemented
1085 /// assuming LiveIntervals.
1086 unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
1087 // This only applies to single block loop.
1088 if (!BB->isSuccessor(BB))
1091 unsigned MaxCyclicLatency = 0;
1092 // Visit each live out vreg def to find def/use pairs that cross iterations.
1093 ArrayRef<unsigned> LiveOuts = RPTracker.getPressure().LiveOutRegs;
1094 for (ArrayRef<unsigned>::iterator RI = LiveOuts.begin(), RE = LiveOuts.end();
1097 if (!TRI->isVirtualRegister(Reg))
1099 const LiveInterval &LI = LIS->getInterval(Reg);
1100 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1104 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1105 const SUnit *DefSU = getSUnit(DefMI);
1109 unsigned LiveOutHeight = DefSU->getHeight();
1110 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1111 // Visit all local users of the vreg def.
1112 for (VReg2UseMap::iterator
1113 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
1114 if (UI->SU == &ExitSU)
1117 // Only consider uses of the phi.
1118 LiveQueryResult LRQ =
1119 LI.Query(LIS->getInstructionIndex(UI->SU->getInstr()));
1120 if (!LRQ.valueIn()->isPHIDef())
1123 // Assume that a path spanning two iterations is a cycle, which could
1124 // overestimate in strange cases. This allows cyclic latency to be
1125 // estimated as the minimum slack of the vreg's depth or height.
1126 unsigned CyclicLatency = 0;
1127 if (LiveOutDepth > UI->SU->getDepth())
1128 CyclicLatency = LiveOutDepth - UI->SU->getDepth();
1130 unsigned LiveInHeight = UI->SU->getHeight() + DefSU->Latency;
1131 if (LiveInHeight > LiveOutHeight) {
1132 if (LiveInHeight - LiveOutHeight < CyclicLatency)
1133 CyclicLatency = LiveInHeight - LiveOutHeight;
1138 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1139 << UI->SU->NodeNum << ") = " << CyclicLatency << "c\n");
1140 if (CyclicLatency > MaxCyclicLatency)
1141 MaxCyclicLatency = CyclicLatency;
1144 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1145 return MaxCyclicLatency;
1148 /// Move an instruction and update register pressure.
1149 void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
1150 // Move the instruction to its new location in the instruction stream.
1151 MachineInstr *MI = SU->getInstr();
1154 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1155 if (&*CurrentTop == MI)
1156 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
1158 moveInstruction(MI, CurrentTop);
1159 TopRPTracker.setPos(MI);
1162 if (ShouldTrackPressure) {
1163 // Update top scheduled pressure.
1164 TopRPTracker.advance();
1165 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
1166 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
1170 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1171 MachineBasicBlock::iterator priorII =
1172 priorNonDebug(CurrentBottom, CurrentTop);
1173 if (&*priorII == MI)
1174 CurrentBottom = priorII;
1176 if (&*CurrentTop == MI) {
1177 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1178 TopRPTracker.setPos(CurrentTop);
1180 moveInstruction(MI, CurrentBottom);
1183 if (ShouldTrackPressure) {
1184 // Update bottom scheduled pressure.
1185 SmallVector<unsigned, 8> LiveUses;
1186 BotRPTracker.recede(&LiveUses);
1187 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
1188 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
1189 updatePressureDiffs(LiveUses);
1194 //===----------------------------------------------------------------------===//
1195 // LoadClusterMutation - DAG post-processing to cluster loads.
1196 //===----------------------------------------------------------------------===//
1199 /// \brief Post-process the DAG to create cluster edges between neighboring
1201 class LoadClusterMutation : public ScheduleDAGMutation {
1206 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
1207 : SU(su), BaseReg(reg), Offset(ofs) {}
1209 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
1210 const LoadClusterMutation::LoadInfo &RHS);
1212 const TargetInstrInfo *TII;
1213 const TargetRegisterInfo *TRI;
1215 LoadClusterMutation(const TargetInstrInfo *tii,
1216 const TargetRegisterInfo *tri)
1217 : TII(tii), TRI(tri) {}
1219 virtual void apply(ScheduleDAGMI *DAG);
1221 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
1225 bool LoadClusterMutation::LoadInfoLess(
1226 const LoadClusterMutation::LoadInfo &LHS,
1227 const LoadClusterMutation::LoadInfo &RHS) {
1228 if (LHS.BaseReg != RHS.BaseReg)
1229 return LHS.BaseReg < RHS.BaseReg;
1230 return LHS.Offset < RHS.Offset;
1233 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
1234 ScheduleDAGMI *DAG) {
1235 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
1236 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
1237 SUnit *SU = Loads[Idx];
1240 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
1241 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
1243 if (LoadRecords.size() < 2)
1245 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
1246 unsigned ClusterLength = 1;
1247 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
1248 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
1253 SUnit *SUa = LoadRecords[Idx].SU;
1254 SUnit *SUb = LoadRecords[Idx+1].SU;
1255 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
1256 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
1258 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
1259 << SUb->NodeNum << ")\n");
1260 // Copy successor edges from SUa to SUb. Interleaving computation
1261 // dependent on SUa can prevent load combining due to register reuse.
1262 // Predecessor edges do not need to be copied from SUb to SUa since nearby
1263 // loads should have effectively the same inputs.
1264 for (SUnit::const_succ_iterator
1265 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1266 if (SI->getSUnit() == SUb)
1268 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1269 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1278 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
1279 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
1280 // Map DAG NodeNum to store chain ID.
1281 DenseMap<unsigned, unsigned> StoreChainIDs;
1282 // Map each store chain to a set of dependent loads.
1283 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1284 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1285 SUnit *SU = &DAG->SUnits[Idx];
1286 if (!SU->getInstr()->mayLoad())
1288 unsigned ChainPredID = DAG->SUnits.size();
1289 for (SUnit::const_pred_iterator
1290 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1292 ChainPredID = PI->getSUnit()->NodeNum;
1296 // Check if this chain-like pred has been seen
1297 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
1298 unsigned NumChains = StoreChainDependents.size();
1299 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1300 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1302 StoreChainDependents.resize(NumChains + 1);
1303 StoreChainDependents[Result.first->second].push_back(SU);
1305 // Iterate over the store chains.
1306 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1307 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
1310 //===----------------------------------------------------------------------===//
1311 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
1312 //===----------------------------------------------------------------------===//
1315 /// \brief Post-process the DAG to create cluster edges between instructions
1316 /// that may be fused by the processor into a single operation.
1317 class MacroFusion : public ScheduleDAGMutation {
1318 const TargetInstrInfo *TII;
1320 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
1322 virtual void apply(ScheduleDAGMI *DAG);
1326 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
1327 /// fused operations.
1328 void MacroFusion::apply(ScheduleDAGMI *DAG) {
1329 // For now, assume targets can only fuse with the branch.
1330 MachineInstr *Branch = DAG->ExitSU.getInstr();
1334 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
1335 SUnit *SU = &DAG->SUnits[--Idx];
1336 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
1339 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1340 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1341 // need to copy predecessor edges from ExitSU to SU, since top-down
1342 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1343 // of SU, we could create an artificial edge from the deepest root, but it
1344 // hasn't been needed yet.
1345 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
1347 assert(Success && "No DAG nodes should be reachable from ExitSU");
1349 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
1354 //===----------------------------------------------------------------------===//
1355 // CopyConstrain - DAG post-processing to encourage copy elimination.
1356 //===----------------------------------------------------------------------===//
1359 /// \brief Post-process the DAG to create weak edges from all uses of a copy to
1360 /// the one use that defines the copy's source vreg, most likely an induction
1361 /// variable increment.
1362 class CopyConstrain : public ScheduleDAGMutation {
1364 SlotIndex RegionBeginIdx;
1365 // RegionEndIdx is the slot index of the last non-debug instruction in the
1366 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
1367 SlotIndex RegionEndIdx;
1369 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1371 virtual void apply(ScheduleDAGMI *DAG);
1374 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
1378 /// constrainLocalCopy handles two possibilities:
1383 /// I3: dst = src (copy)
1384 /// (create pred->succ edges I0->I1, I2->I1)
1387 /// I0: dst = src (copy)
1391 /// (create pred->succ edges I1->I2, I3->I2)
1393 /// Although the MachineScheduler is currently constrained to single blocks,
1394 /// this algorithm should handle extended blocks. An EBB is a set of
1395 /// contiguously numbered blocks such that the previous block in the EBB is
1396 /// always the single predecessor.
1397 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
1398 LiveIntervals *LIS = DAG->getLIS();
1399 MachineInstr *Copy = CopySU->getInstr();
1401 // Check for pure vreg copies.
1402 unsigned SrcReg = Copy->getOperand(1).getReg();
1403 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1406 unsigned DstReg = Copy->getOperand(0).getReg();
1407 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1410 // Check if either the dest or source is local. If it's live across a back
1411 // edge, it's not local. Note that if both vregs are live across the back
1412 // edge, we cannot successfully contrain the copy without cyclic scheduling.
1413 unsigned LocalReg = DstReg;
1414 unsigned GlobalReg = SrcReg;
1415 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1416 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1419 LocalLI = &LIS->getInterval(LocalReg);
1420 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1423 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1425 // Find the global segment after the start of the local LI.
1426 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1427 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1428 // local live range. We could create edges from other global uses to the local
1429 // start, but the coalescer should have already eliminated these cases, so
1430 // don't bother dealing with it.
1431 if (GlobalSegment == GlobalLI->end())
1434 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1435 // returned the next global segment. But if GlobalSegment overlaps with
1436 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1437 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1438 if (GlobalSegment->contains(LocalLI->beginIndex()))
1441 if (GlobalSegment == GlobalLI->end())
1444 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1445 if (GlobalSegment != GlobalLI->begin()) {
1446 // Two address defs have no hole.
1447 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
1448 GlobalSegment->start)) {
1451 // If the prior global segment may be defined by the same two-address
1452 // instruction that also defines LocalLI, then can't make a hole here.
1453 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
1454 LocalLI->beginIndex())) {
1457 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1458 // it would be a disconnected component in the live range.
1459 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
1460 "Disconnected LRG within the scheduling region.");
1462 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1466 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1470 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1471 // constraining the uses of the last local def to precede GlobalDef.
1472 SmallVector<SUnit*,8> LocalUses;
1473 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1474 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1475 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1476 for (SUnit::const_succ_iterator
1477 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1479 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1481 if (I->getSUnit() == GlobalSU)
1483 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1485 LocalUses.push_back(I->getSUnit());
1487 // Open the top of the GlobalLI hole by constraining any earlier global uses
1488 // to precede the start of LocalLI.
1489 SmallVector<SUnit*,8> GlobalUses;
1490 MachineInstr *FirstLocalDef =
1491 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1492 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1493 for (SUnit::const_pred_iterator
1494 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1495 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1497 if (I->getSUnit() == FirstLocalSU)
1499 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1501 GlobalUses.push_back(I->getSUnit());
1503 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1504 // Add the weak edges.
1505 for (SmallVectorImpl<SUnit*>::const_iterator
1506 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1507 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1508 << GlobalSU->NodeNum << ")\n");
1509 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1511 for (SmallVectorImpl<SUnit*>::const_iterator
1512 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1513 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1514 << FirstLocalSU->NodeNum << ")\n");
1515 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1519 /// \brief Callback from DAG postProcessing to create weak edges to encourage
1520 /// copy elimination.
1521 void CopyConstrain::apply(ScheduleDAGMI *DAG) {
1522 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1524 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1525 if (FirstPos == DAG->end())
1527 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
1528 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1529 &*priorNonDebug(DAG->end(), DAG->begin()));
1531 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1532 SUnit *SU = &DAG->SUnits[Idx];
1533 if (!SU->getInstr()->isCopy())
1536 constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
1540 //===----------------------------------------------------------------------===//
1541 // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1542 // and possibly other custom schedulers.
1543 //===----------------------------------------------------------------------===//
1545 static const unsigned InvalidCycle = ~0U;
1547 SchedBoundary::~SchedBoundary() { delete HazardRec; }
1549 void SchedBoundary::reset() {
1550 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1551 // Destroying and reconstructing it is very expensive though. So keep
1552 // invalid, placeholder HazardRecs.
1553 if (HazardRec && HazardRec->isEnabled()) {
1559 CheckPending = false;
1563 MinReadyCycle = UINT_MAX;
1564 ExpectedLatency = 0;
1565 DependentLatency = 0;
1567 MaxExecutedResCount = 0;
1569 IsResourceLimited = false;
1570 ReservedCycles.clear();
1572 // Track the maximum number of stall cycles that could arise either from the
1573 // latency of a DAG edge or the number of cycles that a processor resource is
1574 // reserved (SchedBoundary::ReservedCycles).
1575 MaxObservedLatency = 0;
1577 // Reserve a zero-count for invalid CritResIdx.
1578 ExecutedResCounts.resize(1);
1579 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1582 void SchedRemainder::
1583 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1585 if (!SchedModel->hasInstrSchedModel())
1587 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1588 for (std::vector<SUnit>::iterator
1589 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1590 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1591 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1592 * SchedModel->getMicroOpFactor();
1593 for (TargetSchedModel::ProcResIter
1594 PI = SchedModel->getWriteProcResBegin(SC),
1595 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1596 unsigned PIdx = PI->ProcResourceIdx;
1597 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1598 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1603 void SchedBoundary::
1604 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1607 SchedModel = smodel;
1609 if (SchedModel->hasInstrSchedModel()) {
1610 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
1611 ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1615 /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1616 /// these "soft stalls" differently than the hard stall cycles based on CPU
1617 /// resources and computed by checkHazard(). A fully in-order model
1618 /// (MicroOpBufferSize==0) will not make use of this since instructions are not
1619 /// available for scheduling until they are ready. However, a weaker in-order
1620 /// model may use this for heuristics. For example, if a processor has in-order
1621 /// behavior when reading certain resources, this may come into play.
1622 unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
1623 if (!SU->isUnbuffered)
1626 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1627 if (ReadyCycle > CurrCycle)
1628 return ReadyCycle - CurrCycle;
1632 /// Compute the next cycle at which the given processor resource can be
1634 unsigned SchedBoundary::
1635 getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1636 unsigned NextUnreserved = ReservedCycles[PIdx];
1637 // If this resource has never been used, always return cycle zero.
1638 if (NextUnreserved == InvalidCycle)
1640 // For bottom-up scheduling add the cycles needed for the current operation.
1642 NextUnreserved += Cycles;
1643 return NextUnreserved;
1646 /// Does this SU have a hazard within the current instruction group.
1648 /// The scheduler supports two modes of hazard recognition. The first is the
1649 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1650 /// supports highly complicated in-order reservation tables
1651 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1653 /// The second is a streamlined mechanism that checks for hazards based on
1654 /// simple counters that the scheduler itself maintains. It explicitly checks
1655 /// for instruction dispatch limitations, including the number of micro-ops that
1656 /// can dispatch per cycle.
1658 /// TODO: Also check whether the SU must start a new group.
1659 bool SchedBoundary::checkHazard(SUnit *SU) {
1660 if (HazardRec->isEnabled()
1661 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1664 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1665 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
1666 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1667 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1670 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1671 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1672 for (TargetSchedModel::ProcResIter
1673 PI = SchedModel->getWriteProcResBegin(SC),
1674 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1675 if (getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles) > CurrCycle)
1682 // Find the unscheduled node in ReadySUs with the highest latency.
1683 unsigned SchedBoundary::
1684 findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1686 unsigned RemLatency = 0;
1687 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
1689 unsigned L = getUnscheduledLatency(*I);
1690 if (L > RemLatency) {
1696 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1697 << LateSU->NodeNum << ") " << RemLatency << "c\n");
1702 // Count resources in this zone and the remaining unscheduled
1703 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1704 // resource index, or zero if the zone is issue limited.
1705 unsigned SchedBoundary::
1706 getOtherResourceCount(unsigned &OtherCritIdx) {
1708 if (!SchedModel->hasInstrSchedModel())
1711 unsigned OtherCritCount = Rem->RemIssueCount
1712 + (RetiredMOps * SchedModel->getMicroOpFactor());
1713 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1714 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
1715 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1716 PIdx != PEnd; ++PIdx) {
1717 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1718 if (OtherCount > OtherCritCount) {
1719 OtherCritCount = OtherCount;
1720 OtherCritIdx = PIdx;
1724 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1725 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1726 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
1728 return OtherCritCount;
1731 void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
1732 if (ReadyCycle < MinReadyCycle)
1733 MinReadyCycle = ReadyCycle;
1735 // Check for interlocks first. For the purpose of other heuristics, an
1736 // instruction that cannot issue appears as if it's not in the ReadyQueue.
1737 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1738 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
1743 // Record this node as an immediate dependent of the scheduled node.
1747 void SchedBoundary::releaseTopNode(SUnit *SU) {
1748 if (SU->isScheduled)
1751 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1755 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1756 unsigned Latency = I->getLatency();
1758 MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1760 if (SU->TopReadyCycle < PredReadyCycle + Latency)
1761 SU->TopReadyCycle = PredReadyCycle + Latency;
1763 releaseNode(SU, SU->TopReadyCycle);
1766 void SchedBoundary::releaseBottomNode(SUnit *SU) {
1767 if (SU->isScheduled)
1770 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1772 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1776 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1777 unsigned Latency = I->getLatency();
1779 MaxObservedLatency = std::max(Latency, MaxObservedLatency);
1781 if (SU->BotReadyCycle < SuccReadyCycle + Latency)
1782 SU->BotReadyCycle = SuccReadyCycle + Latency;
1784 releaseNode(SU, SU->BotReadyCycle);
1787 /// Move the boundary of scheduled code by one cycle.
1788 void SchedBoundary::bumpCycle(unsigned NextCycle) {
1789 if (SchedModel->getMicroOpBufferSize() == 0) {
1790 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1791 if (MinReadyCycle > NextCycle)
1792 NextCycle = MinReadyCycle;
1794 // Update the current micro-ops, which will issue in the next cycle.
1795 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1796 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1798 // Decrement DependentLatency based on the next cycle.
1799 if ((NextCycle - CurrCycle) > DependentLatency)
1800 DependentLatency = 0;
1802 DependentLatency -= (NextCycle - CurrCycle);
1804 if (!HazardRec->isEnabled()) {
1805 // Bypass HazardRec virtual calls.
1806 CurrCycle = NextCycle;
1809 // Bypass getHazardType calls in case of long latency.
1810 for (; CurrCycle != NextCycle; ++CurrCycle) {
1812 HazardRec->AdvanceCycle();
1814 HazardRec->RecedeCycle();
1817 CheckPending = true;
1818 unsigned LFactor = SchedModel->getLatencyFactor();
1820 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1823 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1826 void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
1827 ExecutedResCounts[PIdx] += Count;
1828 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1829 MaxExecutedResCount = ExecutedResCounts[PIdx];
1832 /// Add the given processor resource to this scheduled zone.
1834 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1835 /// during which this resource is consumed.
1837 /// \return the next cycle at which the instruction may execute without
1838 /// oversubscribing resources.
1839 unsigned SchedBoundary::
1840 countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
1841 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1842 unsigned Count = Factor * Cycles;
1843 DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx)
1844 << " +" << Cycles << "x" << Factor << "u\n");
1846 // Update Executed resources counts.
1847 incExecutedResources(PIdx, Count);
1848 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1849 Rem->RemainingCounts[PIdx] -= Count;
1851 // Check if this resource exceeds the current critical resource. If so, it
1852 // becomes the critical resource.
1853 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
1854 ZoneCritResIdx = PIdx;
1855 DEBUG(dbgs() << " *** Critical resource "
1856 << SchedModel->getResourceName(PIdx) << ": "
1857 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
1859 // For reserved resources, record the highest cycle using the resource.
1860 unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
1861 if (NextAvailable > CurrCycle) {
1862 DEBUG(dbgs() << " Resource conflict: "
1863 << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
1864 << NextAvailable << "\n");
1866 return NextAvailable;
1869 /// Move the boundary of scheduled code by one SUnit.
1870 void SchedBoundary::bumpNode(SUnit *SU) {
1871 // Update the reservation table.
1872 if (HazardRec->isEnabled()) {
1873 if (!isTop() && SU->isCall) {
1874 // Calls are scheduled with their preceding instructions. For bottom-up
1875 // scheduling, clear the pipeline state before emitting.
1878 HazardRec->EmitInstruction(SU);
1880 // checkHazard should prevent scheduling multiple instructions per cycle that
1881 // exceed the issue width.
1882 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1883 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
1885 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
1886 "Cannot schedule this instruction's MicroOps in the current cycle.");
1888 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1889 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
1891 unsigned NextCycle = CurrCycle;
1892 switch (SchedModel->getMicroOpBufferSize()) {
1894 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
1897 if (ReadyCycle > NextCycle) {
1898 NextCycle = ReadyCycle;
1899 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
1903 // We don't currently model the OOO reorder buffer, so consider all
1904 // scheduled MOps to be "retired". We do loosely model in-order resource
1905 // latency. If this instruction uses an in-order resource, account for any
1906 // likely stall cycles.
1907 if (SU->isUnbuffered && ReadyCycle > NextCycle)
1908 NextCycle = ReadyCycle;
1911 RetiredMOps += IncMOps;
1913 // Update resource counts and critical resource.
1914 if (SchedModel->hasInstrSchedModel()) {
1915 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
1916 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
1917 Rem->RemIssueCount -= DecRemIssue;
1918 if (ZoneCritResIdx) {
1919 // Scale scheduled micro-ops for comparing with the critical resource.
1920 unsigned ScaledMOps =
1921 RetiredMOps * SchedModel->getMicroOpFactor();
1923 // If scaled micro-ops are now more than the previous critical resource by
1924 // a full cycle, then micro-ops issue becomes critical.
1925 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
1926 >= (int)SchedModel->getLatencyFactor()) {
1928 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
1929 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
1932 for (TargetSchedModel::ProcResIter
1933 PI = SchedModel->getWriteProcResBegin(SC),
1934 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1936 countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
1937 if (RCycle > NextCycle)
1940 if (SU->hasReservedResource) {
1941 // For reserved resources, record the highest cycle using the resource.
1942 // For top-down scheduling, this is the cycle in which we schedule this
1943 // instruction plus the number of cycles the operations reserves the
1944 // resource. For bottom-up is it simply the instruction's cycle.
1945 for (TargetSchedModel::ProcResIter
1946 PI = SchedModel->getWriteProcResBegin(SC),
1947 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1948 unsigned PIdx = PI->ProcResourceIdx;
1949 if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
1950 ReservedCycles[PIdx] = isTop() ? NextCycle + PI->Cycles : NextCycle;
1952 MaxObservedLatency = std::max(PI->Cycles, MaxObservedLatency);
1958 // Update ExpectedLatency and DependentLatency.
1959 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
1960 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
1961 if (SU->getDepth() > TopLatency) {
1962 TopLatency = SU->getDepth();
1963 DEBUG(dbgs() << " " << Available.getName()
1964 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
1966 if (SU->getHeight() > BotLatency) {
1967 BotLatency = SU->getHeight();
1968 DEBUG(dbgs() << " " << Available.getName()
1969 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
1971 // If we stall for any reason, bump the cycle.
1972 if (NextCycle > CurrCycle) {
1973 bumpCycle(NextCycle);
1976 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
1977 // resource limited. If a stall occurred, bumpCycle does this.
1978 unsigned LFactor = SchedModel->getLatencyFactor();
1980 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1983 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
1984 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
1985 // one cycle. Since we commonly reach the max MOps here, opportunistically
1986 // bump the cycle to avoid uselessly checking everything in the readyQ.
1987 CurrMOps += IncMOps;
1988 while (CurrMOps >= SchedModel->getIssueWidth()) {
1989 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
1990 << " at cycle " << CurrCycle << '\n');
1991 bumpCycle(++NextCycle);
1993 DEBUG(dumpScheduledState());
1996 /// Release pending ready nodes in to the available queue. This makes them
1997 /// visible to heuristics.
1998 void SchedBoundary::releasePending() {
1999 // If the available queue is empty, it is safe to reset MinReadyCycle.
2000 if (Available.empty())
2001 MinReadyCycle = UINT_MAX;
2003 // Check to see if any of the pending instructions are ready to issue. If
2004 // so, add them to the available queue.
2005 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2006 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2007 SUnit *SU = *(Pending.begin()+i);
2008 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
2010 if (ReadyCycle < MinReadyCycle)
2011 MinReadyCycle = ReadyCycle;
2013 if (!IsBuffered && ReadyCycle > CurrCycle)
2016 if (checkHazard(SU))
2020 Pending.remove(Pending.begin()+i);
2023 DEBUG(if (!Pending.empty()) Pending.dump());
2024 CheckPending = false;
2027 /// Remove SU from the ready set for this boundary.
2028 void SchedBoundary::removeReady(SUnit *SU) {
2029 if (Available.isInQueue(SU))
2030 Available.remove(Available.find(SU));
2032 assert(Pending.isInQueue(SU) && "bad ready count");
2033 Pending.remove(Pending.find(SU));
2037 /// If this queue only has one ready candidate, return it. As a side effect,
2038 /// defer any nodes that now hit a hazard, and advance the cycle until at least
2039 /// one node is ready. If multiple instructions are ready, return NULL.
2040 SUnit *SchedBoundary::pickOnlyChoice() {
2045 // Defer any ready instrs that now have a hazard.
2046 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2047 if (checkHazard(*I)) {
2049 I = Available.remove(I);
2055 for (unsigned i = 0; Available.empty(); ++i) {
2056 assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
2057 "permanent hazard"); (void)i;
2058 bumpCycle(CurrCycle + 1);
2061 if (Available.size() == 1)
2062 return *Available.begin();
2067 // This is useful information to dump after bumpNode.
2068 // Note that the Queue contents are more useful before pickNodeFromQueue.
2069 void SchedBoundary::dumpScheduledState() {
2072 if (ZoneCritResIdx) {
2073 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2074 ResCount = getResourceCount(ZoneCritResIdx);
2077 ResFactor = SchedModel->getMicroOpFactor();
2078 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
2080 unsigned LFactor = SchedModel->getLatencyFactor();
2081 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2082 << " Retired: " << RetiredMOps;
2083 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2084 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
2085 << ResCount / ResFactor << " "
2086 << SchedModel->getResourceName(ZoneCritResIdx)
2087 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2088 << (IsResourceLimited ? " - Resource" : " - Latency")
2093 //===----------------------------------------------------------------------===//
2094 // GenericScheduler - Generic implementation of MachineSchedStrategy.
2095 //===----------------------------------------------------------------------===//
2098 /// Base class for GenericScheduler. This class maintains information about
2099 /// scheduling candidates based on TargetSchedModel making it easy to implement
2100 /// heuristics for either preRA or postRA scheduling.
2101 class GenericSchedulerBase : public MachineSchedStrategy {
2103 /// Represent the type of SchedCandidate found within a single queue.
2104 /// pickNodeBidirectional depends on these listed by decreasing priority.
2106 NoCand, PhysRegCopy, RegExcess, RegCritical, Stall, Cluster, Weak, RegMax,
2107 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
2108 TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
2111 static const char *getReasonStr(GenericSchedulerBase::CandReason Reason);
2114 /// Policy for scheduling the next instruction in the candidate's zone.
2117 unsigned ReduceResIdx;
2118 unsigned DemandResIdx;
2120 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
2123 /// Status of an instruction's critical resource consumption.
2124 struct SchedResourceDelta {
2125 // Count critical resources in the scheduled region required by SU.
2126 unsigned CritResources;
2128 // Count critical resources from another region consumed by SU.
2129 unsigned DemandedResources;
2131 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
2133 bool operator==(const SchedResourceDelta &RHS) const {
2134 return CritResources == RHS.CritResources
2135 && DemandedResources == RHS.DemandedResources;
2137 bool operator!=(const SchedResourceDelta &RHS) const {
2138 return !operator==(RHS);
2142 /// Store the state used by GenericScheduler heuristics, required for the
2143 /// lifetime of one invocation of pickNode().
2144 struct SchedCandidate {
2147 // The best SUnit candidate.
2150 // The reason for this candidate.
2153 // Set of reasons that apply to multiple candidates.
2154 uint32_t RepeatReasonSet;
2156 // Register pressure values for the best candidate.
2157 RegPressureDelta RPDelta;
2159 // Critical resource consumption of the best candidate.
2160 SchedResourceDelta ResDelta;
2162 SchedCandidate(const CandPolicy &policy)
2163 : Policy(policy), SU(NULL), Reason(NoCand), RepeatReasonSet(0) {}
2165 bool isValid() const { return SU; }
2167 // Copy the status of another candidate without changing policy.
2168 void setBest(SchedCandidate &Best) {
2169 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
2171 Reason = Best.Reason;
2172 RPDelta = Best.RPDelta;
2173 ResDelta = Best.ResDelta;
2176 bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
2177 void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
2179 void initResourceDelta(const ScheduleDAGMI *DAG,
2180 const TargetSchedModel *SchedModel);
2184 const MachineSchedContext *Context;
2185 const TargetSchedModel *SchedModel;
2186 const TargetRegisterInfo *TRI;
2190 GenericSchedulerBase(const MachineSchedContext *C):
2191 Context(C), SchedModel(0), TRI(0) {}
2193 void setPolicy(CandPolicy &Policy, bool IsPostRA, SchedBoundary &CurrZone,
2194 SchedBoundary *OtherZone);
2197 void traceCandidate(const SchedCandidate &Cand);
2202 void GenericSchedulerBase::SchedCandidate::
2203 initResourceDelta(const ScheduleDAGMI *DAG,
2204 const TargetSchedModel *SchedModel) {
2205 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2208 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2209 for (TargetSchedModel::ProcResIter
2210 PI = SchedModel->getWriteProcResBegin(SC),
2211 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2212 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2213 ResDelta.CritResources += PI->Cycles;
2214 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2215 ResDelta.DemandedResources += PI->Cycles;
2219 /// Set the CandPolicy given a scheduling zone given the current resources and
2220 /// latencies inside and outside the zone.
2221 void GenericSchedulerBase::setPolicy(CandPolicy &Policy,
2223 SchedBoundary &CurrZone,
2224 SchedBoundary *OtherZone) {
2225 // Apply preemptive heuristics based on the the total latency and resources
2226 // inside and outside this zone. Potential stalls should be considered before
2227 // following this policy.
2229 // Compute remaining latency. We need this both to determine whether the
2230 // overall schedule has become latency-limited and whether the instructions
2231 // outside this zone are resource or latency limited.
2233 // The "dependent" latency is updated incrementally during scheduling as the
2234 // max height/depth of scheduled nodes minus the cycles since it was
2236 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2238 // The "independent" latency is the max ready queue depth:
2239 // ILat = max N.depth for N in Available|Pending
2241 // RemainingLatency is the greater of independent and dependent latency.
2242 unsigned RemLatency = CurrZone.getDependentLatency();
2243 RemLatency = std::max(RemLatency,
2244 CurrZone.findMaxLatency(CurrZone.Available.elements()));
2245 RemLatency = std::max(RemLatency,
2246 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2248 // Compute the critical resource outside the zone.
2249 unsigned OtherCritIdx = 0;
2250 unsigned OtherCount =
2251 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2253 bool OtherResLimited = false;
2254 if (SchedModel->hasInstrSchedModel()) {
2255 unsigned LFactor = SchedModel->getLatencyFactor();
2256 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2258 // Schedule aggressively for latency in PostRA mode. We don't check for
2259 // acyclic latency during PostRA, and highly out-of-order processors will
2260 // skip PostRA scheduling.
2261 if (!OtherResLimited) {
2262 if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2263 Policy.ReduceLatency |= true;
2264 DEBUG(dbgs() << " " << CurrZone.Available.getName()
2265 << " RemainingLatency " << RemLatency << " + "
2266 << CurrZone.getCurrCycle() << "c > CritPath "
2267 << Rem.CriticalPath << "\n");
2270 // If the same resource is limiting inside and outside the zone, do nothing.
2271 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2275 if (CurrZone.isResourceLimited()) {
2276 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
2277 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2280 if (OtherResLimited)
2281 dbgs() << " RemainingLimit: "
2282 << SchedModel->getResourceName(OtherCritIdx) << "\n";
2283 if (!CurrZone.isResourceLimited() && !OtherResLimited)
2284 dbgs() << " Latency limited both directions.\n");
2286 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2287 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2289 if (OtherResLimited)
2290 Policy.DemandResIdx = OtherCritIdx;
2294 const char *GenericSchedulerBase::getReasonStr(
2295 GenericSchedulerBase::CandReason Reason) {
2297 case NoCand: return "NOCAND ";
2298 case PhysRegCopy: return "PREG-COPY";
2299 case RegExcess: return "REG-EXCESS";
2300 case RegCritical: return "REG-CRIT ";
2301 case Stall: return "STALL ";
2302 case Cluster: return "CLUSTER ";
2303 case Weak: return "WEAK ";
2304 case RegMax: return "REG-MAX ";
2305 case ResourceReduce: return "RES-REDUCE";
2306 case ResourceDemand: return "RES-DEMAND";
2307 case TopDepthReduce: return "TOP-DEPTH ";
2308 case TopPathReduce: return "TOP-PATH ";
2309 case BotHeightReduce:return "BOT-HEIGHT";
2310 case BotPathReduce: return "BOT-PATH ";
2311 case NextDefUse: return "DEF-USE ";
2312 case NodeOrder: return "ORDER ";
2314 llvm_unreachable("Unknown reason!");
2317 void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2319 unsigned ResIdx = 0;
2320 unsigned Latency = 0;
2321 switch (Cand.Reason) {
2325 P = Cand.RPDelta.Excess;
2328 P = Cand.RPDelta.CriticalMax;
2331 P = Cand.RPDelta.CurrentMax;
2333 case ResourceReduce:
2334 ResIdx = Cand.Policy.ReduceResIdx;
2336 case ResourceDemand:
2337 ResIdx = Cand.Policy.DemandResIdx;
2339 case TopDepthReduce:
2340 Latency = Cand.SU->getDepth();
2343 Latency = Cand.SU->getHeight();
2345 case BotHeightReduce:
2346 Latency = Cand.SU->getHeight();
2349 Latency = Cand.SU->getDepth();
2352 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2354 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2355 << ":" << P.getUnitInc() << " ";
2359 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2363 dbgs() << " " << Latency << " cycles ";
2370 /// Return true if this heuristic determines order.
2371 static bool tryLess(int TryVal, int CandVal,
2372 GenericSchedulerBase::SchedCandidate &TryCand,
2373 GenericSchedulerBase::SchedCandidate &Cand,
2374 GenericSchedulerBase::CandReason Reason) {
2375 if (TryVal < CandVal) {
2376 TryCand.Reason = Reason;
2379 if (TryVal > CandVal) {
2380 if (Cand.Reason > Reason)
2381 Cand.Reason = Reason;
2384 Cand.setRepeat(Reason);
2388 static bool tryGreater(int TryVal, int CandVal,
2389 GenericSchedulerBase::SchedCandidate &TryCand,
2390 GenericSchedulerBase::SchedCandidate &Cand,
2391 GenericSchedulerBase::CandReason Reason) {
2392 if (TryVal > CandVal) {
2393 TryCand.Reason = Reason;
2396 if (TryVal < CandVal) {
2397 if (Cand.Reason > Reason)
2398 Cand.Reason = Reason;
2401 Cand.setRepeat(Reason);
2405 static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2406 GenericSchedulerBase::SchedCandidate &Cand,
2407 SchedBoundary &Zone) {
2409 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2410 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2411 TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2414 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2415 TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2419 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2420 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2421 TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2424 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2425 TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2431 static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand,
2433 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2434 << GenericSchedulerBase::getReasonStr(Cand.Reason) << '\n');
2438 /// GenericScheduler shrinks the unscheduled zone using heuristics to balance
2440 class GenericScheduler : public GenericSchedulerBase {
2441 ScheduleDAGMILive *DAG;
2443 // State of the top and bottom scheduled instruction boundaries.
2447 MachineSchedPolicy RegionPolicy;
2449 GenericScheduler(const MachineSchedContext *C):
2450 GenericSchedulerBase(C), DAG(0), Top(SchedBoundary::TopQID, "TopQ"),
2451 Bot(SchedBoundary::BotQID, "BotQ") {}
2453 virtual void initPolicy(MachineBasicBlock::iterator Begin,
2454 MachineBasicBlock::iterator End,
2455 unsigned NumRegionInstrs) override;
2457 virtual bool shouldTrackPressure() const override {
2458 return RegionPolicy.ShouldTrackPressure;
2461 virtual void initialize(ScheduleDAGMI *dag) override;
2463 virtual SUnit *pickNode(bool &IsTopNode) override;
2465 virtual void schedNode(SUnit *SU, bool IsTopNode) override;
2467 virtual void releaseTopNode(SUnit *SU) override {
2468 Top.releaseTopNode(SU);
2471 virtual void releaseBottomNode(SUnit *SU) override {
2472 Bot.releaseBottomNode(SU);
2475 virtual void registerRoots() override;
2478 void checkAcyclicLatency();
2480 void tryCandidate(SchedCandidate &Cand,
2481 SchedCandidate &TryCand,
2482 SchedBoundary &Zone,
2483 const RegPressureTracker &RPTracker,
2484 RegPressureTracker &TempTracker);
2486 SUnit *pickNodeBidirectional(bool &IsTopNode);
2488 void pickNodeFromQueue(SchedBoundary &Zone,
2489 const RegPressureTracker &RPTracker,
2490 SchedCandidate &Candidate);
2492 void reschedulePhysRegCopies(SUnit *SU, bool isTop);
2496 void GenericScheduler::initialize(ScheduleDAGMI *dag) {
2497 assert(dag->hasVRegLiveness() &&
2498 "(PreRA)GenericScheduler needs vreg liveness");
2499 DAG = static_cast<ScheduleDAGMILive*>(dag);
2500 SchedModel = DAG->getSchedModel();
2503 Rem.init(DAG, SchedModel);
2504 Top.init(DAG, SchedModel, &Rem);
2505 Bot.init(DAG, SchedModel, &Rem);
2507 // Initialize resource counts.
2509 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2510 // are disabled, then these HazardRecs will be disabled.
2511 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2512 const TargetMachine &TM = DAG->MF.getTarget();
2513 if (!Top.HazardRec) {
2515 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2517 if (!Bot.HazardRec) {
2519 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
2523 /// Initialize the per-region scheduling policy.
2524 void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2525 MachineBasicBlock::iterator End,
2526 unsigned NumRegionInstrs) {
2527 const TargetMachine &TM = Context->MF->getTarget();
2528 const TargetLowering *TLI = TM.getTargetLowering();
2530 // Avoid setting up the register pressure tracker for small regions to save
2531 // compile time. As a rough heuristic, only track pressure when the number of
2532 // schedulable instructions exceeds half the integer register file.
2533 RegionPolicy.ShouldTrackPressure = true;
2534 for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2535 MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2536 if (TLI->isTypeLegal(LegalIntVT)) {
2537 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
2538 TLI->getRegClassFor(LegalIntVT));
2539 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2543 // For generic targets, we default to bottom-up, because it's simpler and more
2544 // compile-time optimizations have been implemented in that direction.
2545 RegionPolicy.OnlyBottomUp = true;
2547 // Allow the subtarget to override default policy.
2548 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
2549 ST.overrideSchedPolicy(RegionPolicy, Begin, End, NumRegionInstrs);
2551 // After subtarget overrides, apply command line options.
2552 if (!EnableRegPressure)
2553 RegionPolicy.ShouldTrackPressure = false;
2555 // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2556 // e.g. -misched-bottomup=false allows scheduling in both directions.
2557 assert((!ForceTopDown || !ForceBottomUp) &&
2558 "-misched-topdown incompatible with -misched-bottomup");
2559 if (ForceBottomUp.getNumOccurrences() > 0) {
2560 RegionPolicy.OnlyBottomUp = ForceBottomUp;
2561 if (RegionPolicy.OnlyBottomUp)
2562 RegionPolicy.OnlyTopDown = false;
2564 if (ForceTopDown.getNumOccurrences() > 0) {
2565 RegionPolicy.OnlyTopDown = ForceTopDown;
2566 if (RegionPolicy.OnlyTopDown)
2567 RegionPolicy.OnlyBottomUp = false;
2571 /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2572 /// critical path by more cycles than it takes to drain the instruction buffer.
2573 /// We estimate an upper bounds on in-flight instructions as:
2575 /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2576 /// InFlightIterations = AcyclicPath / CyclesPerIteration
2577 /// InFlightResources = InFlightIterations * LoopResources
2579 /// TODO: Check execution resources in addition to IssueCount.
2580 void GenericScheduler::checkAcyclicLatency() {
2581 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2584 // Scaled number of cycles per loop iteration.
2585 unsigned IterCount =
2586 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2588 // Scaled acyclic critical path.
2589 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2590 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2591 unsigned InFlightCount =
2592 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2593 unsigned BufferLimit =
2594 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2596 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2598 DEBUG(dbgs() << "IssueCycles="
2599 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2600 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2601 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2602 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2603 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2604 if (Rem.IsAcyclicLatencyLimited)
2605 dbgs() << " ACYCLIC LATENCY LIMIT\n");
2608 void GenericScheduler::registerRoots() {
2609 Rem.CriticalPath = DAG->ExitSU.getDepth();
2611 // Some roots may not feed into ExitSU. Check all of them in case.
2612 for (std::vector<SUnit*>::const_iterator
2613 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2614 if ((*I)->getDepth() > Rem.CriticalPath)
2615 Rem.CriticalPath = (*I)->getDepth();
2617 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
2619 if (EnableCyclicPath) {
2620 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2621 checkAcyclicLatency();
2625 static bool tryPressure(const PressureChange &TryP,
2626 const PressureChange &CandP,
2627 GenericSchedulerBase::SchedCandidate &TryCand,
2628 GenericSchedulerBase::SchedCandidate &Cand,
2629 GenericSchedulerBase::CandReason Reason) {
2630 int TryRank = TryP.getPSetOrMax();
2631 int CandRank = CandP.getPSetOrMax();
2632 // If both candidates affect the same set, go with the smallest increase.
2633 if (TryRank == CandRank) {
2634 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2637 // If one candidate decreases and the other increases, go with it.
2638 // Invalid candidates have UnitInc==0.
2639 if (tryLess(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2643 // If the candidates are decreasing pressure, reverse priority.
2644 if (TryP.getUnitInc() < 0)
2645 std::swap(TryRank, CandRank);
2646 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2649 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2650 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2653 /// Minimize physical register live ranges. Regalloc wants them adjacent to
2654 /// their physreg def/use.
2656 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2657 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2658 /// with the operation that produces or consumes the physreg. We'll do this when
2659 /// regalloc has support for parallel copies.
2660 static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2661 const MachineInstr *MI = SU->getInstr();
2665 unsigned ScheduledOper = isTop ? 1 : 0;
2666 unsigned UnscheduledOper = isTop ? 0 : 1;
2667 // If we have already scheduled the physreg produce/consumer, immediately
2668 // schedule the copy.
2669 if (TargetRegisterInfo::isPhysicalRegister(
2670 MI->getOperand(ScheduledOper).getReg()))
2672 // If the physreg is at the boundary, defer it. Otherwise schedule it
2673 // immediately to free the dependent. We can hoist the copy later.
2674 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2675 if (TargetRegisterInfo::isPhysicalRegister(
2676 MI->getOperand(UnscheduledOper).getReg()))
2677 return AtBoundary ? -1 : 1;
2681 /// Apply a set of heursitics to a new candidate. Heuristics are currently
2682 /// hierarchical. This may be more efficient than a graduated cost model because
2683 /// we don't need to evaluate all aspects of the model for each node in the
2684 /// queue. But it's really done to make the heuristics easier to debug and
2685 /// statistically analyze.
2687 /// \param Cand provides the policy and current best candidate.
2688 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2689 /// \param Zone describes the scheduled zone that we are extending.
2690 /// \param RPTracker describes reg pressure within the scheduled zone.
2691 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
2692 void GenericScheduler::tryCandidate(SchedCandidate &Cand,
2693 SchedCandidate &TryCand,
2694 SchedBoundary &Zone,
2695 const RegPressureTracker &RPTracker,
2696 RegPressureTracker &TempTracker) {
2698 if (DAG->isTrackingPressure()) {
2699 // Always initialize TryCand's RPDelta.
2701 TempTracker.getMaxDownwardPressureDelta(
2702 TryCand.SU->getInstr(),
2704 DAG->getRegionCriticalPSets(),
2705 DAG->getRegPressure().MaxSetPressure);
2708 if (VerifyScheduling) {
2709 TempTracker.getMaxUpwardPressureDelta(
2710 TryCand.SU->getInstr(),
2711 &DAG->getPressureDiff(TryCand.SU),
2713 DAG->getRegionCriticalPSets(),
2714 DAG->getRegPressure().MaxSetPressure);
2717 RPTracker.getUpwardPressureDelta(
2718 TryCand.SU->getInstr(),
2719 DAG->getPressureDiff(TryCand.SU),
2721 DAG->getRegionCriticalPSets(),
2722 DAG->getRegPressure().MaxSetPressure);
2726 DEBUG(if (TryCand.RPDelta.Excess.isValid())
2727 dbgs() << " SU(" << TryCand.SU->NodeNum << ") "
2728 << TRI->getRegPressureSetName(TryCand.RPDelta.Excess.getPSet())
2729 << ":" << TryCand.RPDelta.Excess.getUnitInc() << "\n");
2731 // Initialize the candidate if needed.
2732 if (!Cand.isValid()) {
2733 TryCand.Reason = NodeOrder;
2737 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2738 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2739 TryCand, Cand, PhysRegCopy))
2742 // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2743 // invalid; convert it to INT_MAX to give it lowest priority.
2744 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2745 Cand.RPDelta.Excess,
2746 TryCand, Cand, RegExcess))
2749 // Avoid increasing the max critical pressure in the scheduled region.
2750 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2751 Cand.RPDelta.CriticalMax,
2752 TryCand, Cand, RegCritical))
2755 // For loops that are acyclic path limited, aggressively schedule for latency.
2756 // This can result in very long dependence chains scheduled in sequence, so
2757 // once every cycle (when CurrMOps == 0), switch to normal heuristics.
2758 if (Rem.IsAcyclicLatencyLimited && !Zone.getCurrMOps()
2759 && tryLatency(TryCand, Cand, Zone))
2762 // Prioritize instructions that read unbuffered resources by stall cycles.
2763 if (tryLess(Zone.getLatencyStallCycles(TryCand.SU),
2764 Zone.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2767 // Keep clustered nodes together to encourage downstream peephole
2768 // optimizations which may reduce resource requirements.
2770 // This is a best effort to set things up for a post-RA pass. Optimizations
2771 // like generating loads of multiple registers should ideally be done within
2772 // the scheduler pass by combining the loads during DAG postprocessing.
2773 const SUnit *NextClusterSU =
2774 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2775 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2776 TryCand, Cand, Cluster))
2779 // Weak edges are for clustering and other constraints.
2780 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2781 getWeakLeft(Cand.SU, Zone.isTop()),
2782 TryCand, Cand, Weak)) {
2785 // Avoid increasing the max pressure of the entire region.
2786 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2787 Cand.RPDelta.CurrentMax,
2788 TryCand, Cand, RegMax))
2791 // Avoid critical resource consumption and balance the schedule.
2792 TryCand.initResourceDelta(DAG, SchedModel);
2793 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2794 TryCand, Cand, ResourceReduce))
2796 if (tryGreater(TryCand.ResDelta.DemandedResources,
2797 Cand.ResDelta.DemandedResources,
2798 TryCand, Cand, ResourceDemand))
2801 // Avoid serializing long latency dependence chains.
2802 // For acyclic path limited loops, latency was already checked above.
2803 if (Cand.Policy.ReduceLatency && !Rem.IsAcyclicLatencyLimited
2804 && tryLatency(TryCand, Cand, Zone)) {
2808 // Prefer immediate defs/users of the last scheduled instruction. This is a
2809 // local pressure avoidance strategy that also makes the machine code
2811 if (tryGreater(Zone.isNextSU(TryCand.SU), Zone.isNextSU(Cand.SU),
2812 TryCand, Cand, NextDefUse))
2815 // Fall through to original instruction order.
2816 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2817 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2818 TryCand.Reason = NodeOrder;
2822 /// Pick the best candidate from the queue.
2824 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2825 /// DAG building. To adjust for the current scheduling location we need to
2826 /// maintain the number of vreg uses remaining to be top-scheduled.
2827 void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2828 const RegPressureTracker &RPTracker,
2829 SchedCandidate &Cand) {
2830 ReadyQueue &Q = Zone.Available;
2834 // getMaxPressureDelta temporarily modifies the tracker.
2835 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2837 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2839 SchedCandidate TryCand(Cand.Policy);
2841 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2842 if (TryCand.Reason != NoCand) {
2843 // Initialize resource delta if needed in case future heuristics query it.
2844 if (TryCand.ResDelta == SchedResourceDelta())
2845 TryCand.initResourceDelta(DAG, SchedModel);
2846 Cand.setBest(TryCand);
2847 DEBUG(traceCandidate(Cand));
2852 /// Pick the best candidate node from either the top or bottom queue.
2853 SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
2854 // Schedule as far as possible in the direction of no choice. This is most
2855 // efficient, but also provides the best heuristics for CriticalPSets.
2856 if (SUnit *SU = Bot.pickOnlyChoice()) {
2858 DEBUG(dbgs() << "Pick Bot NOCAND\n");
2861 if (SUnit *SU = Top.pickOnlyChoice()) {
2863 DEBUG(dbgs() << "Pick Top NOCAND\n");
2866 CandPolicy NoPolicy;
2867 SchedCandidate BotCand(NoPolicy);
2868 SchedCandidate TopCand(NoPolicy);
2869 // Set the bottom-up policy based on the state of the current bottom zone and
2870 // the instructions outside the zone, including the top zone.
2871 setPolicy(BotCand.Policy, /*IsPostRA=*/false, Bot, &Top);
2872 // Set the top-down policy based on the state of the current top zone and
2873 // the instructions outside the zone, including the bottom zone.
2874 setPolicy(TopCand.Policy, /*IsPostRA=*/false, Top, &Bot);
2876 // Prefer bottom scheduling when heuristics are silent.
2877 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2878 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2880 // If either Q has a single candidate that provides the least increase in
2881 // Excess pressure, we can immediately schedule from that Q.
2883 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2884 // affects picking from either Q. If scheduling in one direction must
2885 // increase pressure for one of the excess PSets, then schedule in that
2886 // direction first to provide more freedom in the other direction.
2887 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2888 || (BotCand.Reason == RegCritical
2889 && !BotCand.isRepeat(RegCritical)))
2892 tracePick(BotCand, IsTopNode);
2895 // Check if the top Q has a better candidate.
2896 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2897 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2899 // Choose the queue with the most important (lowest enum) reason.
2900 if (TopCand.Reason < BotCand.Reason) {
2902 tracePick(TopCand, IsTopNode);
2905 // Otherwise prefer the bottom candidate, in node order if all else failed.
2907 tracePick(BotCand, IsTopNode);
2911 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2912 SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
2913 if (DAG->top() == DAG->bottom()) {
2914 assert(Top.Available.empty() && Top.Pending.empty() &&
2915 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2920 if (RegionPolicy.OnlyTopDown) {
2921 SU = Top.pickOnlyChoice();
2923 CandPolicy NoPolicy;
2924 SchedCandidate TopCand(NoPolicy);
2925 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2926 assert(TopCand.Reason != NoCand && "failed to find a candidate");
2927 tracePick(TopCand, true);
2932 else if (RegionPolicy.OnlyBottomUp) {
2933 SU = Bot.pickOnlyChoice();
2935 CandPolicy NoPolicy;
2936 SchedCandidate BotCand(NoPolicy);
2937 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2938 assert(BotCand.Reason != NoCand && "failed to find a candidate");
2939 tracePick(BotCand, false);
2945 SU = pickNodeBidirectional(IsTopNode);
2947 } while (SU->isScheduled);
2949 if (SU->isTopReady())
2950 Top.removeReady(SU);
2951 if (SU->isBottomReady())
2952 Bot.removeReady(SU);
2954 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2958 void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
2960 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2963 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2965 // Find already scheduled copies with a single physreg dependence and move
2966 // them just above the scheduled instruction.
2967 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2969 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2971 SUnit *DepSU = I->getSUnit();
2972 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2974 MachineInstr *Copy = DepSU->getInstr();
2975 if (!Copy->isCopy())
2977 DEBUG(dbgs() << " Rescheduling physreg copy ";
2978 I->getSUnit()->dump(DAG));
2979 DAG->moveInstruction(Copy, InsertPos);
2983 /// Update the scheduler's state after scheduling a node. This is the same node
2984 /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
2985 /// update it's state based on the current cycle before MachineSchedStrategy
2988 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2989 /// them here. See comments in biasPhysRegCopy.
2990 void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2992 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
2994 if (SU->hasPhysRegUses)
2995 reschedulePhysRegCopies(SU, true);
2998 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
3000 if (SU->hasPhysRegDefs)
3001 reschedulePhysRegCopies(SU, false);
3005 /// Create the standard converging machine scheduler. This will be used as the
3006 /// default scheduler if the target does not set a default.
3007 static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C) {
3008 ScheduleDAGMILive *DAG = new ScheduleDAGMILive(C, new GenericScheduler(C));
3009 // Register DAG post-processors.
3011 // FIXME: extend the mutation API to allow earlier mutations to instantiate
3012 // data and pass it to later mutations. Have a single mutation that gathers
3013 // the interesting nodes in one pass.
3014 DAG->addMutation(new CopyConstrain(DAG->TII, DAG->TRI));
3015 if (EnableLoadCluster && DAG->TII->enableClusterLoads())
3016 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
3017 if (EnableMacroFusion)
3018 DAG->addMutation(new MacroFusion(DAG->TII));
3022 static MachineSchedRegistry
3023 GenericSchedRegistry("converge", "Standard converging scheduler.",
3024 createGenericSchedLive);
3026 //===----------------------------------------------------------------------===//
3027 // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3028 //===----------------------------------------------------------------------===//
3031 /// PostGenericScheduler - Interface to the scheduling algorithm used by
3034 /// Callbacks from ScheduleDAGMI:
3035 /// initPolicy -> initialize(DAG) -> registerRoots -> pickNode ...
3036 class PostGenericScheduler : public GenericSchedulerBase {
3039 SmallVector<SUnit*, 8> BotRoots;
3041 PostGenericScheduler(const MachineSchedContext *C):
3042 GenericSchedulerBase(C), Top(SchedBoundary::TopQID, "TopQ") {}
3044 virtual ~PostGenericScheduler() {}
3046 virtual void initPolicy(MachineBasicBlock::iterator Begin,
3047 MachineBasicBlock::iterator End,
3048 unsigned NumRegionInstrs) override {
3049 /* no configurable policy */
3052 /// PostRA scheduling does not track pressure.
3053 virtual bool shouldTrackPressure() const override { return false; }
3055 virtual void initialize(ScheduleDAGMI *Dag) override {
3057 SchedModel = DAG->getSchedModel();
3060 Rem.init(DAG, SchedModel);
3061 Top.init(DAG, SchedModel, &Rem);
3064 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3065 // or are disabled, then these HazardRecs will be disabled.
3066 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
3067 const TargetMachine &TM = DAG->MF.getTarget();
3068 if (!Top.HazardRec) {
3070 TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
3074 virtual void registerRoots() override;
3076 virtual SUnit *pickNode(bool &IsTopNode) override;
3078 virtual void scheduleTree(unsigned SubtreeID) override {
3079 llvm_unreachable("PostRA scheduler does not support subtree analysis.");
3082 virtual void schedNode(SUnit *SU, bool IsTopNode) override;
3084 virtual void releaseTopNode(SUnit *SU) override {
3085 Top.releaseTopNode(SU);
3088 // Only called for roots.
3089 virtual void releaseBottomNode(SUnit *SU) override {
3090 BotRoots.push_back(SU);
3094 void tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand);
3096 void pickNodeFromQueue(SchedCandidate &Cand);
3100 void PostGenericScheduler::registerRoots() {
3101 Rem.CriticalPath = DAG->ExitSU.getDepth();
3103 // Some roots may not feed into ExitSU. Check all of them in case.
3104 for (SmallVectorImpl<SUnit*>::const_iterator
3105 I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
3106 if ((*I)->getDepth() > Rem.CriticalPath)
3107 Rem.CriticalPath = (*I)->getDepth();
3109 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
3112 /// Apply a set of heursitics to a new candidate for PostRA scheduling.
3114 /// \param Cand provides the policy and current best candidate.
3115 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3116 void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3117 SchedCandidate &TryCand) {
3119 // Initialize the candidate if needed.
3120 if (!Cand.isValid()) {
3121 TryCand.Reason = NodeOrder;
3125 // Prioritize instructions that read unbuffered resources by stall cycles.
3126 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3127 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3130 // Avoid critical resource consumption and balance the schedule.
3131 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3132 TryCand, Cand, ResourceReduce))
3134 if (tryGreater(TryCand.ResDelta.DemandedResources,
3135 Cand.ResDelta.DemandedResources,
3136 TryCand, Cand, ResourceDemand))
3139 // Avoid serializing long latency dependence chains.
3140 if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3144 // Fall through to original instruction order.
3145 if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3146 TryCand.Reason = NodeOrder;
3149 void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3150 ReadyQueue &Q = Top.Available;
3154 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
3155 SchedCandidate TryCand(Cand.Policy);
3157 TryCand.initResourceDelta(DAG, SchedModel);
3158 tryCandidate(Cand, TryCand);
3159 if (TryCand.Reason != NoCand) {
3160 Cand.setBest(TryCand);
3161 DEBUG(traceCandidate(Cand));
3166 /// Pick the next node to schedule.
3167 SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3168 if (DAG->top() == DAG->bottom()) {
3169 assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
3174 SU = Top.pickOnlyChoice();
3176 CandPolicy NoPolicy;
3177 SchedCandidate TopCand(NoPolicy);
3178 // Set the top-down policy based on the state of the current top zone and
3179 // the instructions outside the zone, including the bottom zone.
3180 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, NULL);
3181 pickNodeFromQueue(TopCand);
3182 assert(TopCand.Reason != NoCand && "failed to find a candidate");
3183 tracePick(TopCand, true);
3186 } while (SU->isScheduled);
3189 Top.removeReady(SU);
3191 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3195 /// Called after ScheduleDAGMI has scheduled an instruction and updated
3196 /// scheduled/remaining flags in the DAG nodes.
3197 void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3198 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3202 /// Create a generic scheduler with no vreg liveness or DAG mutation passes.
3203 static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C) {
3204 return new ScheduleDAGMI(C, new PostGenericScheduler(C), /*IsPostRA=*/true);
3207 //===----------------------------------------------------------------------===//
3208 // ILP Scheduler. Currently for experimental analysis of heuristics.
3209 //===----------------------------------------------------------------------===//
3212 /// \brief Order nodes by the ILP metric.
3214 const SchedDFSResult *DFSResult;
3215 const BitVector *ScheduledTrees;
3218 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
3220 /// \brief Apply a less-than relation on node priority.
3222 /// (Return true if A comes after B in the Q.)
3223 bool operator()(const SUnit *A, const SUnit *B) const {
3224 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3225 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3226 if (SchedTreeA != SchedTreeB) {
3227 // Unscheduled trees have lower priority.
3228 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3229 return ScheduledTrees->test(SchedTreeB);
3231 // Trees with shallower connections have have lower priority.
3232 if (DFSResult->getSubtreeLevel(SchedTreeA)
3233 != DFSResult->getSubtreeLevel(SchedTreeB)) {
3234 return DFSResult->getSubtreeLevel(SchedTreeA)
3235 < DFSResult->getSubtreeLevel(SchedTreeB);
3239 return DFSResult->getILP(A) < DFSResult->getILP(B);
3241 return DFSResult->getILP(A) > DFSResult->getILP(B);
3245 /// \brief Schedule based on the ILP metric.
3246 class ILPScheduler : public MachineSchedStrategy {
3247 ScheduleDAGMILive *DAG;
3250 std::vector<SUnit*> ReadyQ;
3252 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
3254 virtual void initialize(ScheduleDAGMI *dag) {
3255 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3256 DAG = static_cast<ScheduleDAGMILive*>(dag);
3257 DAG->computeDFSResult();
3258 Cmp.DFSResult = DAG->getDFSResult();
3259 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
3263 virtual void registerRoots() {
3264 // Restore the heap in ReadyQ with the updated DFS results.
3265 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3268 /// Implement MachineSchedStrategy interface.
3269 /// -----------------------------------------
3271 /// Callback to select the highest priority node from the ready Q.
3272 virtual SUnit *pickNode(bool &IsTopNode) {
3273 if (ReadyQ.empty()) return NULL;
3274 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3275 SUnit *SU = ReadyQ.back();
3278 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
3279 << " ILP: " << DAG->getDFSResult()->getILP(SU)
3280 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3281 << DAG->getDFSResult()->getSubtreeLevel(
3282 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3283 << "Scheduling " << *SU->getInstr());
3287 /// \brief Scheduler callback to notify that a new subtree is scheduled.
3288 virtual void scheduleTree(unsigned SubtreeID) {
3289 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3292 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3293 /// DFSResults, and resort the priority Q.
3294 virtual void schedNode(SUnit *SU, bool IsTopNode) {
3295 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
3298 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
3300 virtual void releaseBottomNode(SUnit *SU) {
3301 ReadyQ.push_back(SU);
3302 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3307 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
3308 return new ScheduleDAGMILive(C, new ILPScheduler(true));
3310 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
3311 return new ScheduleDAGMILive(C, new ILPScheduler(false));
3313 static MachineSchedRegistry ILPMaxRegistry(
3314 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3315 static MachineSchedRegistry ILPMinRegistry(
3316 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3318 //===----------------------------------------------------------------------===//
3319 // Machine Instruction Shuffler for Correctness Testing
3320 //===----------------------------------------------------------------------===//
3324 /// Apply a less-than relation on the node order, which corresponds to the
3325 /// instruction order prior to scheduling. IsReverse implements greater-than.
3326 template<bool IsReverse>
3328 bool operator()(SUnit *A, SUnit *B) const {
3330 return A->NodeNum > B->NodeNum;
3332 return A->NodeNum < B->NodeNum;
3336 /// Reorder instructions as much as possible.
3337 class InstructionShuffler : public MachineSchedStrategy {
3341 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3342 // gives nodes with a higher number higher priority causing the latest
3343 // instructions to be scheduled first.
3344 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3346 // When scheduling bottom-up, use greater-than as the queue priority.
3347 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3350 InstructionShuffler(bool alternate, bool topdown)
3351 : IsAlternating(alternate), IsTopDown(topdown) {}
3353 virtual void initialize(ScheduleDAGMI*) {
3358 /// Implement MachineSchedStrategy interface.
3359 /// -----------------------------------------
3361 virtual SUnit *pickNode(bool &IsTopNode) {
3365 if (TopQ.empty()) return NULL;
3368 } while (SU->isScheduled);
3373 if (BottomQ.empty()) return NULL;
3376 } while (SU->isScheduled);
3380 IsTopDown = !IsTopDown;
3384 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
3386 virtual void releaseTopNode(SUnit *SU) {
3389 virtual void releaseBottomNode(SUnit *SU) {
3395 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
3396 bool Alternate = !ForceTopDown && !ForceBottomUp;
3397 bool TopDown = !ForceBottomUp;
3398 assert((TopDown || !ForceTopDown) &&
3399 "-misched-topdown incompatible with -misched-bottomup");
3400 return new ScheduleDAGMILive(C, new InstructionShuffler(Alternate, TopDown));
3402 static MachineSchedRegistry ShufflerRegistry(
3403 "shuffle", "Shuffle machine instructions alternating directions",
3404 createInstructionShuffler);
3407 //===----------------------------------------------------------------------===//
3408 // GraphWriter support for ScheduleDAGMILive.
3409 //===----------------------------------------------------------------------===//
3414 template<> struct GraphTraits<
3415 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3418 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3420 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3422 static std::string getGraphName(const ScheduleDAG *G) {
3423 return G->MF.getName();
3426 static bool renderGraphFromBottomUp() {
3430 static bool isNodeHidden(const SUnit *Node) {
3431 return (Node->Preds.size() > 10 || Node->Succs.size() > 10);
3434 static bool hasNodeAddressLabel(const SUnit *Node,
3435 const ScheduleDAG *Graph) {
3439 /// If you want to override the dot attributes printed for a particular
3440 /// edge, override this method.
3441 static std::string getEdgeAttributes(const SUnit *Node,
3443 const ScheduleDAG *Graph) {
3444 if (EI.isArtificialDep())
3445 return "color=cyan,style=dashed";
3447 return "color=blue,style=dashed";
3451 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3453 raw_string_ostream SS(Str);
3454 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3455 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3456 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : 0;
3457 SS << "SU:" << SU->NodeNum;
3459 SS << " I:" << DFS->getNumInstrs(SU);
3462 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3463 return G->getGraphNodeLabel(SU);
3466 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
3467 std::string Str("shape=Mrecord");
3468 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3469 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3470 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : 0;
3472 Str += ",style=filled,fillcolor=\"#";
3473 Str += DOT::getColorString(DFS->getSubtreeID(N));
3482 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3483 /// rendered using 'dot'.
3485 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3487 ViewGraph(this, Name, false, Title);
3489 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3490 << "systems with Graphviz or gv!\n";
3494 /// Out-of-line implementation with no arguments is handy for gdb.
3495 void ScheduleDAGMI::viewGraph() {
3496 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());