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/OwningPtr.h"
19 #include "llvm/ADT/PriorityQueue.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterClassInfo.h"
27 #include "llvm/CodeGen/ScheduleDFS.h"
28 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/GraphWriter.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
40 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
41 cl::desc("Force top-down list scheduling"));
42 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
43 cl::desc("Force bottom-up list scheduling"));
47 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
48 cl::desc("Pop up a window to show MISched dags after they are processed"));
50 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
51 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
53 static bool ViewMISchedDAGs = false;
56 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
57 cl::desc("Enable load clustering."), cl::init(true));
59 // Experimental heuristics
60 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
61 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
63 static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
64 cl::desc("Verify machine instrs before and after machine scheduling"));
66 // DAG subtrees must have at least this many nodes.
67 static const unsigned MinSubtreeSize = 8;
69 //===----------------------------------------------------------------------===//
70 // Machine Instruction Scheduling Pass and Registry
71 //===----------------------------------------------------------------------===//
73 MachineSchedContext::MachineSchedContext():
74 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
75 RegClassInfo = new RegisterClassInfo();
78 MachineSchedContext::~MachineSchedContext() {
83 /// MachineScheduler runs after coalescing and before register allocation.
84 class MachineScheduler : public MachineSchedContext,
85 public MachineFunctionPass {
89 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
91 virtual void releaseMemory() {}
93 virtual bool runOnMachineFunction(MachineFunction&);
95 virtual void print(raw_ostream &O, const Module* = 0) const;
97 static char ID; // Class identification, replacement for typeinfo
101 char MachineScheduler::ID = 0;
103 char &llvm::MachineSchedulerID = MachineScheduler::ID;
105 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
106 "Machine Instruction Scheduler", false, false)
107 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
108 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
109 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
110 INITIALIZE_PASS_END(MachineScheduler, "misched",
111 "Machine Instruction Scheduler", false, false)
113 MachineScheduler::MachineScheduler()
114 : MachineFunctionPass(ID) {
115 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
118 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
119 AU.setPreservesCFG();
120 AU.addRequiredID(MachineDominatorsID);
121 AU.addRequired<MachineLoopInfo>();
122 AU.addRequired<AliasAnalysis>();
123 AU.addRequired<TargetPassConfig>();
124 AU.addRequired<SlotIndexes>();
125 AU.addPreserved<SlotIndexes>();
126 AU.addRequired<LiveIntervals>();
127 AU.addPreserved<LiveIntervals>();
128 MachineFunctionPass::getAnalysisUsage(AU);
131 MachinePassRegistry MachineSchedRegistry::Registry;
133 /// A dummy default scheduler factory indicates whether the scheduler
134 /// is overridden on the command line.
135 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
139 /// MachineSchedOpt allows command line selection of the scheduler.
140 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
141 RegisterPassParser<MachineSchedRegistry> >
142 MachineSchedOpt("misched",
143 cl::init(&useDefaultMachineSched), cl::Hidden,
144 cl::desc("Machine instruction scheduler to use"));
146 static MachineSchedRegistry
147 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
148 useDefaultMachineSched);
150 /// Forward declare the standard machine scheduler. This will be used as the
151 /// default scheduler if the target does not set a default.
152 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
155 /// Decrement this iterator until reaching the top or a non-debug instr.
156 static MachineBasicBlock::iterator
157 priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
158 assert(I != Beg && "reached the top of the region, cannot decrement");
160 if (!I->isDebugValue())
166 /// If this iterator is a debug value, increment until reaching the End or a
167 /// non-debug instruction.
168 static MachineBasicBlock::iterator
169 nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
170 for(; I != End; ++I) {
171 if (!I->isDebugValue())
177 /// Top-level MachineScheduler pass driver.
179 /// Visit blocks in function order. Divide each block into scheduling regions
180 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
181 /// consistent with the DAG builder, which traverses the interior of the
182 /// scheduling regions bottom-up.
184 /// This design avoids exposing scheduling boundaries to the DAG builder,
185 /// simplifying the DAG builder's support for "special" target instructions.
186 /// At the same time the design allows target schedulers to operate across
187 /// scheduling boundaries, for example to bundle the boudary instructions
188 /// without reordering them. This creates complexity, because the target
189 /// scheduler must update the RegionBegin and RegionEnd positions cached by
190 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
191 /// design would be to split blocks at scheduling boundaries, but LLVM has a
192 /// general bias against block splitting purely for implementation simplicity.
193 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
194 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
196 // Initialize the context of the pass.
198 MLI = &getAnalysis<MachineLoopInfo>();
199 MDT = &getAnalysis<MachineDominatorTree>();
200 PassConfig = &getAnalysis<TargetPassConfig>();
201 AA = &getAnalysis<AliasAnalysis>();
203 LIS = &getAnalysis<LiveIntervals>();
204 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
206 if (VerifyScheduling) {
208 MF->verify(this, "Before machine scheduling.");
210 RegClassInfo->runOnMachineFunction(*MF);
212 // Select the scheduler, or set the default.
213 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
214 if (Ctor == useDefaultMachineSched) {
215 // Get the default scheduler set by the target.
216 Ctor = MachineSchedRegistry::getDefault();
218 Ctor = createConvergingSched;
219 MachineSchedRegistry::setDefault(Ctor);
222 // Instantiate the selected scheduler.
223 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
225 // Visit all machine basic blocks.
227 // TODO: Visit blocks in global postorder or postorder within the bottom-up
228 // loop tree. Then we can optionally compute global RegPressure.
229 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
230 MBB != MBBEnd; ++MBB) {
232 Scheduler->startBlock(MBB);
234 // Break the block into scheduling regions [I, RegionEnd), and schedule each
235 // region as soon as it is discovered. RegionEnd points the scheduling
236 // boundary at the bottom of the region. The DAG does not include RegionEnd,
237 // but the region does (i.e. the next RegionEnd is above the previous
238 // RegionBegin). If the current block has no terminator then RegionEnd ==
239 // MBB->end() for the bottom region.
241 // The Scheduler may insert instructions during either schedule() or
242 // exitRegion(), even for empty regions. So the local iterators 'I' and
243 // 'RegionEnd' are invalid across these calls.
244 unsigned RemainingInstrs = MBB->size();
245 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
246 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
248 // Avoid decrementing RegionEnd for blocks with no terminator.
249 if (RegionEnd != MBB->end()
250 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
252 // Count the boundary instruction.
256 // The next region starts above the previous region. Look backward in the
257 // instruction stream until we find the nearest boundary.
258 unsigned NumRegionInstrs = 0;
259 MachineBasicBlock::iterator I = RegionEnd;
260 for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
261 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
264 // Notify the scheduler of the region, even if we may skip scheduling
265 // it. Perhaps it still needs to be bundled.
266 Scheduler->enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
268 // Skip empty scheduling regions (0 or 1 schedulable instructions).
269 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
270 // Close the current region. Bundle the terminator if needed.
271 // This invalidates 'RegionEnd' and 'I'.
272 Scheduler->exitRegion();
275 DEBUG(dbgs() << "********** MI Scheduling **********\n");
276 DEBUG(dbgs() << MF->getName()
277 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
278 << "\n From: " << *I << " To: ";
279 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
280 else dbgs() << "End";
281 dbgs() << " RegionInstrs: " << NumRegionInstrs
282 << " Remaining: " << RemainingInstrs << "\n");
284 // Schedule a region: possibly reorder instructions.
285 // This invalidates 'RegionEnd' and 'I'.
286 Scheduler->schedule();
288 // Close the current region.
289 Scheduler->exitRegion();
291 // Scheduling has invalidated the current iterator 'I'. Ask the
292 // scheduler for the top of it's scheduled region.
293 RegionEnd = Scheduler->begin();
295 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
296 Scheduler->finishBlock();
298 Scheduler->finalizeSchedule();
300 if (VerifyScheduling)
301 MF->verify(this, "After machine scheduling.");
305 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
309 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
310 void ReadyQueue::dump() {
311 dbgs() << Name << ": ";
312 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
313 dbgs() << Queue[i]->NodeNum << " ";
318 //===----------------------------------------------------------------------===//
319 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
321 //===----------------------------------------------------------------------===//
323 ScheduleDAGMI::~ScheduleDAGMI() {
325 DeleteContainerPointers(Mutations);
329 bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
330 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
333 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
334 if (SuccSU != &ExitSU) {
335 // Do not use WillCreateCycle, it assumes SD scheduling.
336 // If Pred is reachable from Succ, then the edge creates a cycle.
337 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
339 Topo.AddPred(SuccSU, PredDep.getSUnit());
341 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
342 // Return true regardless of whether a new edge needed to be inserted.
346 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
347 /// NumPredsLeft reaches zero, release the successor node.
349 /// FIXME: Adjust SuccSU height based on MinLatency.
350 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
351 SUnit *SuccSU = SuccEdge->getSUnit();
353 if (SuccEdge->isWeak()) {
354 --SuccSU->WeakPredsLeft;
355 if (SuccEdge->isCluster())
356 NextClusterSucc = SuccSU;
360 if (SuccSU->NumPredsLeft == 0) {
361 dbgs() << "*** Scheduling failed! ***\n";
363 dbgs() << " has been released too many times!\n";
367 --SuccSU->NumPredsLeft;
368 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
369 SchedImpl->releaseTopNode(SuccSU);
372 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
373 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
374 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
376 releaseSucc(SU, &*I);
380 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
381 /// NumSuccsLeft reaches zero, release the predecessor node.
383 /// FIXME: Adjust PredSU height based on MinLatency.
384 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
385 SUnit *PredSU = PredEdge->getSUnit();
387 if (PredEdge->isWeak()) {
388 --PredSU->WeakSuccsLeft;
389 if (PredEdge->isCluster())
390 NextClusterPred = PredSU;
394 if (PredSU->NumSuccsLeft == 0) {
395 dbgs() << "*** Scheduling failed! ***\n";
397 dbgs() << " has been released too many times!\n";
401 --PredSU->NumSuccsLeft;
402 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
403 SchedImpl->releaseBottomNode(PredSU);
406 /// releasePredecessors - Call releasePred on each of SU's predecessors.
407 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
408 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
410 releasePred(SU, &*I);
414 /// This is normally called from the main scheduler loop but may also be invoked
415 /// by the scheduling strategy to perform additional code motion.
416 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
417 MachineBasicBlock::iterator InsertPos) {
418 // Advance RegionBegin if the first instruction moves down.
419 if (&*RegionBegin == MI)
422 // Update the instruction stream.
423 BB->splice(InsertPos, BB, MI);
425 // Update LiveIntervals
426 LIS->handleMove(MI, /*UpdateFlags=*/true);
428 // Recede RegionBegin if an instruction moves above the first.
429 if (RegionBegin == InsertPos)
433 bool ScheduleDAGMI::checkSchedLimit() {
435 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
436 CurrentTop = CurrentBottom;
439 ++NumInstrsScheduled;
444 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
445 /// crossing a scheduling boundary. [begin, end) includes all instructions in
446 /// the region, including the boundary itself and single-instruction regions
447 /// that don't get scheduled.
448 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
449 MachineBasicBlock::iterator begin,
450 MachineBasicBlock::iterator end,
451 unsigned regioninstrs)
453 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
455 // For convenience remember the end of the liveness region.
457 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
460 // Setup the register pressure trackers for the top scheduled top and bottom
461 // scheduled regions.
462 void ScheduleDAGMI::initRegPressure() {
463 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
464 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
466 // Close the RPTracker to finalize live ins.
467 RPTracker.closeRegion();
469 DEBUG(RPTracker.dump());
471 // Initialize the live ins and live outs.
472 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
473 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
475 // Close one end of the tracker so we can call
476 // getMaxUpward/DownwardPressureDelta before advancing across any
477 // instructions. This converts currently live regs into live ins/outs.
478 TopRPTracker.closeTop();
479 BotRPTracker.closeBottom();
481 BotRPTracker.initLiveThru(RPTracker);
482 if (!BotRPTracker.getLiveThru().empty()) {
483 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
484 DEBUG(dbgs() << "Live Thru: ";
485 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
488 // Account for liveness generated by the region boundary.
489 if (LiveRegionEnd != RegionEnd)
490 BotRPTracker.recede();
492 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
494 // Cache the list of excess pressure sets in this region. This will also track
495 // the max pressure in the scheduled code for these sets.
496 RegionCriticalPSets.clear();
497 const std::vector<unsigned> &RegionPressure =
498 RPTracker.getPressure().MaxSetPressure;
499 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
500 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
501 if (RegionPressure[i] > Limit) {
502 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
503 << " Limit " << Limit
504 << " Actual " << RegionPressure[i] << "\n");
505 RegionCriticalPSets.push_back(PressureElement(i, 0));
508 DEBUG(dbgs() << "Excess PSets: ";
509 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
510 dbgs() << TRI->getRegPressureSetName(
511 RegionCriticalPSets[i].PSetID) << " ";
515 // FIXME: When the pressure tracker deals in pressure differences then we won't
516 // iterate over all RegionCriticalPSets[i].
518 updateScheduledPressure(const std::vector<unsigned> &NewMaxPressure) {
519 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
520 unsigned ID = RegionCriticalPSets[i].PSetID;
521 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
522 if ((int)NewMaxPressure[ID] > MaxUnits)
523 MaxUnits = NewMaxPressure[ID];
526 for (unsigned i = 0, e = NewMaxPressure.size(); i < e; ++i) {
527 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
528 if (NewMaxPressure[i] > Limit ) {
529 dbgs() << " " << TRI->getRegPressureSetName(i) << ": "
530 << NewMaxPressure[i] << " > " << Limit << "\n";
535 /// schedule - Called back from MachineScheduler::runOnMachineFunction
536 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
537 /// only includes instructions that have DAG nodes, not scheduling boundaries.
539 /// This is a skeletal driver, with all the functionality pushed into helpers,
540 /// so that it can be easilly extended by experimental schedulers. Generally,
541 /// implementing MachineSchedStrategy should be sufficient to implement a new
542 /// scheduling algorithm. However, if a scheduler further subclasses
543 /// ScheduleDAGMI then it will want to override this virtual method in order to
544 /// update any specialized state.
545 void ScheduleDAGMI::schedule() {
546 buildDAGWithRegPressure();
548 Topo.InitDAGTopologicalSorting();
552 SmallVector<SUnit*, 8> TopRoots, BotRoots;
553 findRootsAndBiasEdges(TopRoots, BotRoots);
555 // Initialize the strategy before modifying the DAG.
556 // This may initialize a DFSResult to be used for queue priority.
557 SchedImpl->initialize(this);
559 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
560 SUnits[su].dumpAll(this));
561 if (ViewMISchedDAGs) viewGraph();
563 // Initialize ready queues now that the DAG and priority data are finalized.
564 initQueues(TopRoots, BotRoots);
566 bool IsTopNode = false;
567 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
568 assert(!SU->isScheduled && "Node already scheduled");
569 if (!checkSchedLimit())
572 scheduleMI(SU, IsTopNode);
574 updateQueues(SU, IsTopNode);
576 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
581 unsigned BBNum = begin()->getParent()->getNumber();
582 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
588 /// Build the DAG and setup three register pressure trackers.
589 void ScheduleDAGMI::buildDAGWithRegPressure() {
590 // Initialize the register pressure tracker used by buildSchedGraph.
591 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
592 /*TrackUntiedDefs=*/true);
594 // Account for liveness generate by the region boundary.
595 if (LiveRegionEnd != RegionEnd)
598 // Build the DAG, and compute current register pressure.
599 buildSchedGraph(AA, &RPTracker);
601 // Initialize top/bottom trackers after computing region pressure.
605 /// Apply each ScheduleDAGMutation step in order.
606 void ScheduleDAGMI::postprocessDAG() {
607 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
608 Mutations[i]->apply(this);
612 void ScheduleDAGMI::computeDFSResult() {
614 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
616 ScheduledTrees.clear();
617 DFSResult->resize(SUnits.size());
618 DFSResult->compute(SUnits);
619 ScheduledTrees.resize(DFSResult->getNumSubtrees());
622 void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
623 SmallVectorImpl<SUnit*> &BotRoots) {
624 for (std::vector<SUnit>::iterator
625 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
627 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
629 // Order predecessors so DFSResult follows the critical path.
630 SU->biasCriticalPath();
632 // A SUnit is ready to top schedule if it has no predecessors.
633 if (!I->NumPredsLeft)
634 TopRoots.push_back(SU);
635 // A SUnit is ready to bottom schedule if it has no successors.
636 if (!I->NumSuccsLeft)
637 BotRoots.push_back(SU);
639 ExitSU.biasCriticalPath();
642 /// Identify DAG roots and setup scheduler queues.
643 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
644 ArrayRef<SUnit*> BotRoots) {
645 NextClusterSucc = NULL;
646 NextClusterPred = NULL;
648 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
650 // Nodes with unreleased weak edges can still be roots.
651 // Release top roots in forward order.
652 for (SmallVectorImpl<SUnit*>::const_iterator
653 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
654 SchedImpl->releaseTopNode(*I);
656 // Release bottom roots in reverse order so the higher priority nodes appear
657 // first. This is more natural and slightly more efficient.
658 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
659 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
660 SchedImpl->releaseBottomNode(*I);
663 releaseSuccessors(&EntrySU);
664 releasePredecessors(&ExitSU);
666 SchedImpl->registerRoots();
668 // Advance past initial DebugValues.
669 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
670 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
671 TopRPTracker.setPos(CurrentTop);
673 CurrentBottom = RegionEnd;
676 /// Move an instruction and update register pressure.
677 void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
678 // Move the instruction to its new location in the instruction stream.
679 MachineInstr *MI = SU->getInstr();
682 assert(SU->isTopReady() && "node still has unscheduled dependencies");
683 if (&*CurrentTop == MI)
684 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
686 moveInstruction(MI, CurrentTop);
687 TopRPTracker.setPos(MI);
690 // Update top scheduled pressure.
691 TopRPTracker.advance();
692 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
693 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
696 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
697 MachineBasicBlock::iterator priorII =
698 priorNonDebug(CurrentBottom, CurrentTop);
700 CurrentBottom = priorII;
702 if (&*CurrentTop == MI) {
703 CurrentTop = nextIfDebug(++CurrentTop, priorII);
704 TopRPTracker.setPos(CurrentTop);
706 moveInstruction(MI, CurrentBottom);
709 // Update bottom scheduled pressure.
710 BotRPTracker.recede();
711 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
712 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
716 /// Update scheduler queues after scheduling an instruction.
717 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
718 // Release dependent instructions for scheduling.
720 releaseSuccessors(SU);
722 releasePredecessors(SU);
724 SU->isScheduled = true;
727 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
728 if (!ScheduledTrees.test(SubtreeID)) {
729 ScheduledTrees.set(SubtreeID);
730 DFSResult->scheduleTree(SubtreeID);
731 SchedImpl->scheduleTree(SubtreeID);
735 // Notify the scheduling strategy after updating the DAG.
736 SchedImpl->schedNode(SU, IsTopNode);
739 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
740 void ScheduleDAGMI::placeDebugValues() {
741 // If first instruction was a DBG_VALUE then put it back.
743 BB->splice(RegionBegin, BB, FirstDbgValue);
744 RegionBegin = FirstDbgValue;
747 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
748 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
749 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
750 MachineInstr *DbgValue = P.first;
751 MachineBasicBlock::iterator OrigPrevMI = P.second;
752 if (&*RegionBegin == DbgValue)
754 BB->splice(++OrigPrevMI, BB, DbgValue);
755 if (OrigPrevMI == llvm::prior(RegionEnd))
756 RegionEnd = DbgValue;
759 FirstDbgValue = NULL;
762 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
763 void ScheduleDAGMI::dumpSchedule() const {
764 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
765 if (SUnit *SU = getSUnit(&(*MI)))
768 dbgs() << "Missing SUnit\n";
773 //===----------------------------------------------------------------------===//
774 // LoadClusterMutation - DAG post-processing to cluster loads.
775 //===----------------------------------------------------------------------===//
778 /// \brief Post-process the DAG to create cluster edges between neighboring
780 class LoadClusterMutation : public ScheduleDAGMutation {
785 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
786 : SU(su), BaseReg(reg), Offset(ofs) {}
788 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
789 const LoadClusterMutation::LoadInfo &RHS);
791 const TargetInstrInfo *TII;
792 const TargetRegisterInfo *TRI;
794 LoadClusterMutation(const TargetInstrInfo *tii,
795 const TargetRegisterInfo *tri)
796 : TII(tii), TRI(tri) {}
798 virtual void apply(ScheduleDAGMI *DAG);
800 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
804 bool LoadClusterMutation::LoadInfoLess(
805 const LoadClusterMutation::LoadInfo &LHS,
806 const LoadClusterMutation::LoadInfo &RHS) {
807 if (LHS.BaseReg != RHS.BaseReg)
808 return LHS.BaseReg < RHS.BaseReg;
809 return LHS.Offset < RHS.Offset;
812 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
813 ScheduleDAGMI *DAG) {
814 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
815 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
816 SUnit *SU = Loads[Idx];
819 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
820 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
822 if (LoadRecords.size() < 2)
824 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
825 unsigned ClusterLength = 1;
826 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
827 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
832 SUnit *SUa = LoadRecords[Idx].SU;
833 SUnit *SUb = LoadRecords[Idx+1].SU;
834 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
835 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
837 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
838 << SUb->NodeNum << ")\n");
839 // Copy successor edges from SUa to SUb. Interleaving computation
840 // dependent on SUa can prevent load combining due to register reuse.
841 // Predecessor edges do not need to be copied from SUb to SUa since nearby
842 // loads should have effectively the same inputs.
843 for (SUnit::const_succ_iterator
844 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
845 if (SI->getSUnit() == SUb)
847 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
848 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
857 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
858 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
859 // Map DAG NodeNum to store chain ID.
860 DenseMap<unsigned, unsigned> StoreChainIDs;
861 // Map each store chain to a set of dependent loads.
862 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
863 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
864 SUnit *SU = &DAG->SUnits[Idx];
865 if (!SU->getInstr()->mayLoad())
867 unsigned ChainPredID = DAG->SUnits.size();
868 for (SUnit::const_pred_iterator
869 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
871 ChainPredID = PI->getSUnit()->NodeNum;
875 // Check if this chain-like pred has been seen
876 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
877 unsigned NumChains = StoreChainDependents.size();
878 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
879 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
881 StoreChainDependents.resize(NumChains + 1);
882 StoreChainDependents[Result.first->second].push_back(SU);
884 // Iterate over the store chains.
885 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
886 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
889 //===----------------------------------------------------------------------===//
890 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
891 //===----------------------------------------------------------------------===//
894 /// \brief Post-process the DAG to create cluster edges between instructions
895 /// that may be fused by the processor into a single operation.
896 class MacroFusion : public ScheduleDAGMutation {
897 const TargetInstrInfo *TII;
899 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
901 virtual void apply(ScheduleDAGMI *DAG);
905 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
906 /// fused operations.
907 void MacroFusion::apply(ScheduleDAGMI *DAG) {
908 // For now, assume targets can only fuse with the branch.
909 MachineInstr *Branch = DAG->ExitSU.getInstr();
913 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
914 SUnit *SU = &DAG->SUnits[--Idx];
915 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
918 // Create a single weak edge from SU to ExitSU. The only effect is to cause
919 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
920 // need to copy predecessor edges from ExitSU to SU, since top-down
921 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
922 // of SU, we could create an artificial edge from the deepest root, but it
923 // hasn't been needed yet.
924 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
926 assert(Success && "No DAG nodes should be reachable from ExitSU");
928 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
933 //===----------------------------------------------------------------------===//
934 // CopyConstrain - DAG post-processing to encourage copy elimination.
935 //===----------------------------------------------------------------------===//
938 /// \brief Post-process the DAG to create weak edges from all uses of a copy to
939 /// the one use that defines the copy's source vreg, most likely an induction
940 /// variable increment.
941 class CopyConstrain : public ScheduleDAGMutation {
943 SlotIndex RegionBeginIdx;
944 // RegionEndIdx is the slot index of the last non-debug instruction in the
945 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
946 SlotIndex RegionEndIdx;
948 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
950 virtual void apply(ScheduleDAGMI *DAG);
953 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMI *DAG);
957 /// constrainLocalCopy handles two possibilities:
962 /// I3: dst = src (copy)
963 /// (create pred->succ edges I0->I1, I2->I1)
966 /// I0: dst = src (copy)
970 /// (create pred->succ edges I1->I2, I3->I2)
972 /// Although the MachineScheduler is currently constrained to single blocks,
973 /// this algorithm should handle extended blocks. An EBB is a set of
974 /// contiguously numbered blocks such that the previous block in the EBB is
975 /// always the single predecessor.
976 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMI *DAG) {
977 LiveIntervals *LIS = DAG->getLIS();
978 MachineInstr *Copy = CopySU->getInstr();
980 // Check for pure vreg copies.
981 unsigned SrcReg = Copy->getOperand(1).getReg();
982 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
985 unsigned DstReg = Copy->getOperand(0).getReg();
986 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
989 // Check if either the dest or source is local. If it's live across a back
990 // edge, it's not local. Note that if both vregs are live across the back
991 // edge, we cannot successfully contrain the copy without cyclic scheduling.
992 unsigned LocalReg = DstReg;
993 unsigned GlobalReg = SrcReg;
994 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
995 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
998 LocalLI = &LIS->getInterval(LocalReg);
999 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1002 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1004 // Find the global segment after the start of the local LI.
1005 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1006 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1007 // local live range. We could create edges from other global uses to the local
1008 // start, but the coalescer should have already eliminated these cases, so
1009 // don't bother dealing with it.
1010 if (GlobalSegment == GlobalLI->end())
1013 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1014 // returned the next global segment. But if GlobalSegment overlaps with
1015 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1016 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1017 if (GlobalSegment->contains(LocalLI->beginIndex()))
1020 if (GlobalSegment == GlobalLI->end())
1023 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1024 if (GlobalSegment != GlobalLI->begin()) {
1025 // Two address defs have no hole.
1026 if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->end,
1027 GlobalSegment->start)) {
1030 // If the prior global segment may be defined by the same two-address
1031 // instruction that also defines LocalLI, then can't make a hole here.
1032 if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->start,
1033 LocalLI->beginIndex())) {
1036 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1037 // it would be a disconnected component in the live range.
1038 assert(llvm::prior(GlobalSegment)->start < LocalLI->beginIndex() &&
1039 "Disconnected LRG within the scheduling region.");
1041 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1045 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1049 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1050 // constraining the uses of the last local def to precede GlobalDef.
1051 SmallVector<SUnit*,8> LocalUses;
1052 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1053 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1054 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1055 for (SUnit::const_succ_iterator
1056 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1058 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1060 if (I->getSUnit() == GlobalSU)
1062 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1064 LocalUses.push_back(I->getSUnit());
1066 // Open the top of the GlobalLI hole by constraining any earlier global uses
1067 // to precede the start of LocalLI.
1068 SmallVector<SUnit*,8> GlobalUses;
1069 MachineInstr *FirstLocalDef =
1070 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1071 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1072 for (SUnit::const_pred_iterator
1073 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1074 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1076 if (I->getSUnit() == FirstLocalSU)
1078 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1080 GlobalUses.push_back(I->getSUnit());
1082 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1083 // Add the weak edges.
1084 for (SmallVectorImpl<SUnit*>::const_iterator
1085 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1086 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1087 << GlobalSU->NodeNum << ")\n");
1088 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1090 for (SmallVectorImpl<SUnit*>::const_iterator
1091 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1092 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1093 << FirstLocalSU->NodeNum << ")\n");
1094 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1098 /// \brief Callback from DAG postProcessing to create weak edges to encourage
1099 /// copy elimination.
1100 void CopyConstrain::apply(ScheduleDAGMI *DAG) {
1101 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1102 if (FirstPos == DAG->end())
1104 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
1105 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1106 &*priorNonDebug(DAG->end(), DAG->begin()));
1108 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1109 SUnit *SU = &DAG->SUnits[Idx];
1110 if (!SU->getInstr()->isCopy())
1113 constrainLocalCopy(SU, DAG);
1117 //===----------------------------------------------------------------------===//
1118 // ConvergingScheduler - Implementation of the generic MachineSchedStrategy.
1119 //===----------------------------------------------------------------------===//
1122 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
1124 class ConvergingScheduler : public MachineSchedStrategy {
1126 /// Represent the type of SchedCandidate found within a single queue.
1127 /// pickNodeBidirectional depends on these listed by decreasing priority.
1129 NoCand, PhysRegCopy, RegExcess, RegCritical, Cluster, Weak, RegMax,
1130 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
1131 TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
1134 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
1137 /// Policy for scheduling the next instruction in the candidate's zone.
1140 unsigned ReduceResIdx;
1141 unsigned DemandResIdx;
1143 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
1146 /// Status of an instruction's critical resource consumption.
1147 struct SchedResourceDelta {
1148 // Count critical resources in the scheduled region required by SU.
1149 unsigned CritResources;
1151 // Count critical resources from another region consumed by SU.
1152 unsigned DemandedResources;
1154 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
1156 bool operator==(const SchedResourceDelta &RHS) const {
1157 return CritResources == RHS.CritResources
1158 && DemandedResources == RHS.DemandedResources;
1160 bool operator!=(const SchedResourceDelta &RHS) const {
1161 return !operator==(RHS);
1165 /// Store the state used by ConvergingScheduler heuristics, required for the
1166 /// lifetime of one invocation of pickNode().
1167 struct SchedCandidate {
1170 // The best SUnit candidate.
1173 // The reason for this candidate.
1176 // Set of reasons that apply to multiple candidates.
1177 uint32_t RepeatReasonSet;
1179 // Register pressure values for the best candidate.
1180 RegPressureDelta RPDelta;
1182 // Critical resource consumption of the best candidate.
1183 SchedResourceDelta ResDelta;
1185 SchedCandidate(const CandPolicy &policy)
1186 : Policy(policy), SU(NULL), Reason(NoCand), RepeatReasonSet(0) {}
1188 bool isValid() const { return SU; }
1190 // Copy the status of another candidate without changing policy.
1191 void setBest(SchedCandidate &Best) {
1192 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
1194 Reason = Best.Reason;
1195 RPDelta = Best.RPDelta;
1196 ResDelta = Best.ResDelta;
1199 bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
1200 void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
1202 void initResourceDelta(const ScheduleDAGMI *DAG,
1203 const TargetSchedModel *SchedModel);
1206 /// Summarize the unscheduled region.
1207 struct SchedRemainder {
1208 // Critical path through the DAG in expected latency.
1209 unsigned CriticalPath;
1211 // Scaled count of micro-ops left to schedule.
1212 unsigned RemIssueCount;
1214 // Unscheduled resources
1215 SmallVector<unsigned, 16> RemainingCounts;
1220 RemainingCounts.clear();
1223 SchedRemainder() { reset(); }
1225 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
1228 /// Each Scheduling boundary is associated with ready queues. It tracks the
1229 /// current cycle in the direction of movement, and maintains the state
1230 /// of "hazards" and other interlocks at the current cycle.
1231 struct SchedBoundary {
1233 const TargetSchedModel *SchedModel;
1234 SchedRemainder *Rem;
1236 ReadyQueue Available;
1240 // For heuristics, keep a list of the nodes that immediately depend on the
1241 // most recently scheduled node.
1242 SmallPtrSet<const SUnit*, 8> NextSUs;
1244 ScheduleHazardRecognizer *HazardRec;
1246 /// Number of cycles it takes to issue the instructions scheduled in this
1247 /// zone. It is defined as: scheduled-micro-ops / issue-width + stalls.
1248 /// See getStalls().
1251 /// Micro-ops issued in the current cycle
1254 /// MinReadyCycle - Cycle of the soonest available instruction.
1255 unsigned MinReadyCycle;
1257 // The expected latency of the critical path in this scheduled zone.
1258 unsigned ExpectedLatency;
1260 // The latency of dependence chains leading into this zone.
1261 // For each node scheduled bottom-up: DLat = max DLat, N.Depth.
1262 // For each cycle scheduled: DLat -= 1.
1263 unsigned DependentLatency;
1265 /// Count the scheduled (issued) micro-ops that can be retired by
1266 /// time=CurrCycle assuming the first scheduled instr is retired at time=0.
1267 unsigned RetiredMOps;
1269 // Count scheduled resources that have been executed. Resources are
1270 // considered executed if they become ready in the time that it takes to
1271 // saturate any resource including the one in question. Counts are scaled
1272 // for direct comparison with other resources. Counts can be compared with
1273 // MOps * getMicroOpFactor and Latency * getLatencyFactor.
1274 SmallVector<unsigned, 16> ExecutedResCounts;
1276 /// Cache the max count for a single resource.
1277 unsigned MaxExecutedResCount;
1279 // Cache the critical resources ID in this scheduled zone.
1280 unsigned ZoneCritResIdx;
1282 // Is the scheduled region resource limited vs. latency limited.
1283 bool IsResourceLimited;
1286 // Remember the greatest operand latency as an upper bound on the number of
1287 // times we should retry the pending queue because of a hazard.
1288 unsigned MaxObservedLatency;
1292 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1297 CheckPending = false;
1302 MinReadyCycle = UINT_MAX;
1303 ExpectedLatency = 0;
1304 DependentLatency = 0;
1306 MaxExecutedResCount = 0;
1308 IsResourceLimited = false;
1310 MaxObservedLatency = 0;
1312 // Reserve a zero-count for invalid CritResIdx.
1313 ExecutedResCounts.resize(1);
1314 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1317 /// Pending queues extend the ready queues with the same ID and the
1318 /// PendingFlag set.
1319 SchedBoundary(unsigned ID, const Twine &Name):
1320 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
1321 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
1326 ~SchedBoundary() { delete HazardRec; }
1328 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1329 SchedRemainder *rem);
1331 bool isTop() const {
1332 return Available.getID() == ConvergingScheduler::TopQID;
1336 const char *getResourceName(unsigned PIdx) {
1339 return SchedModel->getProcResource(PIdx)->Name;
1343 /// Get the number of latency cycles "covered" by the scheduled
1344 /// instructions. This is the larger of the critical path within the zone
1345 /// and the number of cycles required to issue the instructions.
1346 unsigned getScheduledLatency() const {
1347 return std::max(ExpectedLatency, CurrCycle);
1350 unsigned getUnscheduledLatency(SUnit *SU) const {
1351 return isTop() ? SU->getHeight() : SU->getDepth();
1354 unsigned getResourceCount(unsigned ResIdx) const {
1355 return ExecutedResCounts[ResIdx];
1358 /// Get the scaled count of scheduled micro-ops and resources, including
1359 /// executed resources.
1360 unsigned getCriticalCount() const {
1361 if (!ZoneCritResIdx)
1362 return RetiredMOps * SchedModel->getMicroOpFactor();
1363 return getResourceCount(ZoneCritResIdx);
1366 /// Get a scaled count for the minimum execution time of the scheduled
1367 /// micro-ops that are ready to execute by getExecutedCount. Notice the
1369 unsigned getExecutedCount() const {
1370 return std::max(CurrCycle * SchedModel->getLatencyFactor(),
1371 MaxExecutedResCount);
1374 bool checkHazard(SUnit *SU);
1376 unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
1378 unsigned getOtherResourceCount(unsigned &OtherCritIdx);
1380 void setPolicy(CandPolicy &Policy, SchedBoundary &OtherZone);
1382 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1384 void bumpCycle(unsigned NextCycle);
1386 void incExecutedResources(unsigned PIdx, unsigned Count);
1388 unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle);
1390 void bumpNode(SUnit *SU);
1392 void releasePending();
1394 void removeReady(SUnit *SU);
1396 SUnit *pickOnlyChoice();
1399 void dumpScheduledState();
1405 const TargetSchedModel *SchedModel;
1406 const TargetRegisterInfo *TRI;
1408 // State of the top and bottom scheduled instruction boundaries.
1414 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
1421 ConvergingScheduler():
1422 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
1424 virtual void initialize(ScheduleDAGMI *dag);
1426 virtual SUnit *pickNode(bool &IsTopNode);
1428 virtual void schedNode(SUnit *SU, bool IsTopNode);
1430 virtual void releaseTopNode(SUnit *SU);
1432 virtual void releaseBottomNode(SUnit *SU);
1434 virtual void registerRoots();
1437 void tryCandidate(SchedCandidate &Cand,
1438 SchedCandidate &TryCand,
1439 SchedBoundary &Zone,
1440 const RegPressureTracker &RPTracker,
1441 RegPressureTracker &TempTracker);
1443 SUnit *pickNodeBidirectional(bool &IsTopNode);
1445 void pickNodeFromQueue(SchedBoundary &Zone,
1446 const RegPressureTracker &RPTracker,
1447 SchedCandidate &Candidate);
1449 void reschedulePhysRegCopies(SUnit *SU, bool isTop);
1452 void traceCandidate(const SchedCandidate &Cand);
1457 void ConvergingScheduler::SchedRemainder::
1458 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1460 if (!SchedModel->hasInstrSchedModel())
1462 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1463 for (std::vector<SUnit>::iterator
1464 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1465 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1466 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1467 * SchedModel->getMicroOpFactor();
1468 for (TargetSchedModel::ProcResIter
1469 PI = SchedModel->getWriteProcResBegin(SC),
1470 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1471 unsigned PIdx = PI->ProcResourceIdx;
1472 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1473 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1478 void ConvergingScheduler::SchedBoundary::
1479 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1482 SchedModel = smodel;
1484 if (SchedModel->hasInstrSchedModel())
1485 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
1488 void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1490 SchedModel = DAG->getSchedModel();
1493 Rem.init(DAG, SchedModel);
1494 Top.init(DAG, SchedModel, &Rem);
1495 Bot.init(DAG, SchedModel, &Rem);
1497 // Initialize resource counts.
1499 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1500 // are disabled, then these HazardRecs will be disabled.
1501 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
1502 const TargetMachine &TM = DAG->MF.getTarget();
1503 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1504 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1506 assert((!ForceTopDown || !ForceBottomUp) &&
1507 "-misched-topdown incompatible with -misched-bottomup");
1510 void ConvergingScheduler::releaseTopNode(SUnit *SU) {
1511 if (SU->isScheduled)
1514 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1518 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1519 unsigned Latency = I->getLatency();
1521 Top.MaxObservedLatency = std::max(Latency, Top.MaxObservedLatency);
1523 if (SU->TopReadyCycle < PredReadyCycle + Latency)
1524 SU->TopReadyCycle = PredReadyCycle + Latency;
1526 Top.releaseNode(SU, SU->TopReadyCycle);
1529 void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
1530 if (SU->isScheduled)
1533 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1535 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1539 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1540 unsigned Latency = I->getLatency();
1542 Bot.MaxObservedLatency = std::max(Latency, Bot.MaxObservedLatency);
1544 if (SU->BotReadyCycle < SuccReadyCycle + Latency)
1545 SU->BotReadyCycle = SuccReadyCycle + Latency;
1547 Bot.releaseNode(SU, SU->BotReadyCycle);
1550 void ConvergingScheduler::registerRoots() {
1551 Rem.CriticalPath = DAG->ExitSU.getDepth();
1552 // Some roots may not feed into ExitSU. Check all of them in case.
1553 for (std::vector<SUnit*>::const_iterator
1554 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1555 if ((*I)->getDepth() > Rem.CriticalPath)
1556 Rem.CriticalPath = (*I)->getDepth();
1558 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1561 /// Does this SU have a hazard within the current instruction group.
1563 /// The scheduler supports two modes of hazard recognition. The first is the
1564 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1565 /// supports highly complicated in-order reservation tables
1566 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1568 /// The second is a streamlined mechanism that checks for hazards based on
1569 /// simple counters that the scheduler itself maintains. It explicitly checks
1570 /// for instruction dispatch limitations, including the number of micro-ops that
1571 /// can dispatch per cycle.
1573 /// TODO: Also check whether the SU must start a new group.
1574 bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1575 if (HazardRec->isEnabled())
1576 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1578 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1579 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
1580 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1581 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1587 // Find the unscheduled node in ReadySUs with the highest latency.
1588 unsigned ConvergingScheduler::SchedBoundary::
1589 findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1591 unsigned RemLatency = 0;
1592 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
1594 unsigned L = getUnscheduledLatency(*I);
1595 if (L > RemLatency) {
1601 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1602 << LateSU->NodeNum << ") " << RemLatency << "c\n");
1607 // Count resources in this zone and the remaining unscheduled
1608 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1609 // resource index, or zero if the zone is issue limited.
1610 unsigned ConvergingScheduler::SchedBoundary::
1611 getOtherResourceCount(unsigned &OtherCritIdx) {
1613 if (!SchedModel->hasInstrSchedModel())
1616 unsigned OtherCritCount = Rem->RemIssueCount
1617 + (RetiredMOps * SchedModel->getMicroOpFactor());
1618 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1619 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
1620 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1621 PIdx != PEnd; ++PIdx) {
1622 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1623 if (OtherCount > OtherCritCount) {
1624 OtherCritCount = OtherCount;
1625 OtherCritIdx = PIdx;
1629 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1630 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1631 << " " << getResourceName(OtherCritIdx) << "\n");
1633 return OtherCritCount;
1636 /// Set the CandPolicy for this zone given the current resources and latencies
1637 /// inside and outside the zone.
1638 void ConvergingScheduler::SchedBoundary::setPolicy(CandPolicy &Policy,
1639 SchedBoundary &OtherZone) {
1640 // Now that potential stalls have been considered, apply preemptive heuristics
1641 // based on the the total latency and resources inside and outside this
1644 // Compute remaining latency. We need this both to determine whether the
1645 // overall schedule has become latency-limited and whether the instructions
1646 // outside this zone are resource or latency limited.
1648 // The "dependent" latency is updated incrementally during scheduling as the
1649 // max height/depth of scheduled nodes minus the cycles since it was
1651 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
1653 // The "independent" latency is the max ready queue depth:
1654 // ILat = max N.depth for N in Available|Pending
1656 // RemainingLatency is the greater of independent and dependent latency.
1657 unsigned RemLatency = DependentLatency;
1658 RemLatency = std::max(RemLatency, findMaxLatency(Available.elements()));
1659 RemLatency = std::max(RemLatency, findMaxLatency(Pending.elements()));
1661 // Compute the critical resource outside the zone.
1662 unsigned OtherCritIdx;
1663 unsigned OtherCount = OtherZone.getOtherResourceCount(OtherCritIdx);
1665 bool OtherResLimited = false;
1666 if (SchedModel->hasInstrSchedModel()) {
1667 unsigned LFactor = SchedModel->getLatencyFactor();
1668 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
1670 if (!OtherResLimited && (RemLatency + CurrCycle > Rem->CriticalPath)) {
1671 Policy.ReduceLatency |= true;
1672 DEBUG(dbgs() << " " << Available.getName() << " RemainingLatency "
1673 << RemLatency << " + " << CurrCycle << "c > CritPath "
1674 << Rem->CriticalPath << "\n");
1676 // If the same resource is limiting inside and outside the zone, do nothing.
1677 if (ZoneCritResIdx == OtherCritIdx)
1681 if (IsResourceLimited) {
1682 dbgs() << " " << Available.getName() << " ResourceLimited: "
1683 << getResourceName(ZoneCritResIdx) << "\n";
1685 if (OtherResLimited)
1686 dbgs() << " RemainingLimit: " << getResourceName(OtherCritIdx) << "\n";
1687 if (!IsResourceLimited && !OtherResLimited)
1688 dbgs() << " Latency limited both directions.\n");
1690 if (IsResourceLimited && !Policy.ReduceResIdx)
1691 Policy.ReduceResIdx = ZoneCritResIdx;
1693 if (OtherResLimited)
1694 Policy.DemandResIdx = OtherCritIdx;
1697 void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1698 unsigned ReadyCycle) {
1699 if (ReadyCycle < MinReadyCycle)
1700 MinReadyCycle = ReadyCycle;
1702 // Check for interlocks first. For the purpose of other heuristics, an
1703 // instruction that cannot issue appears as if it's not in the ReadyQueue.
1704 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1705 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
1710 // Record this node as an immediate dependent of the scheduled node.
1714 /// Move the boundary of scheduled code by one cycle.
1715 void ConvergingScheduler::SchedBoundary::bumpCycle(unsigned NextCycle) {
1716 if (SchedModel->getMicroOpBufferSize() == 0) {
1717 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1718 if (MinReadyCycle > NextCycle)
1719 NextCycle = MinReadyCycle;
1721 // Update the current micro-ops, which will issue in the next cycle.
1722 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1723 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1725 // Decrement DependentLatency based on the next cycle.
1726 if ((NextCycle - CurrCycle) > DependentLatency)
1727 DependentLatency = 0;
1729 DependentLatency -= (NextCycle - CurrCycle);
1731 if (!HazardRec->isEnabled()) {
1732 // Bypass HazardRec virtual calls.
1733 CurrCycle = NextCycle;
1736 // Bypass getHazardType calls in case of long latency.
1737 for (; CurrCycle != NextCycle; ++CurrCycle) {
1739 HazardRec->AdvanceCycle();
1741 HazardRec->RecedeCycle();
1744 CheckPending = true;
1745 unsigned LFactor = SchedModel->getLatencyFactor();
1747 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1750 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1753 void ConvergingScheduler::SchedBoundary::incExecutedResources(unsigned PIdx,
1755 ExecutedResCounts[PIdx] += Count;
1756 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1757 MaxExecutedResCount = ExecutedResCounts[PIdx];
1760 /// Add the given processor resource to this scheduled zone.
1762 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1763 /// during which this resource is consumed.
1765 /// \return the next cycle at which the instruction may execute without
1766 /// oversubscribing resources.
1767 unsigned ConvergingScheduler::SchedBoundary::
1768 countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle) {
1769 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1770 unsigned Count = Factor * Cycles;
1771 DEBUG(dbgs() << " " << getResourceName(PIdx)
1772 << " +" << Cycles << "x" << Factor << "u\n");
1774 // Update Executed resources counts.
1775 incExecutedResources(PIdx, Count);
1776 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1777 Rem->RemainingCounts[PIdx] -= Count;
1779 // Check if this resource exceeds the current critical resource. If so, it
1780 // becomes the critical resource.
1781 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
1782 ZoneCritResIdx = PIdx;
1783 DEBUG(dbgs() << " *** Critical resource "
1784 << getResourceName(PIdx) << ": "
1785 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
1787 // TODO: We don't yet model reserved resources. It's not hard though.
1791 /// Move the boundary of scheduled code by one SUnit.
1792 void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
1793 // Update the reservation table.
1794 if (HazardRec->isEnabled()) {
1795 if (!isTop() && SU->isCall) {
1796 // Calls are scheduled with their preceding instructions. For bottom-up
1797 // scheduling, clear the pipeline state before emitting.
1800 HazardRec->EmitInstruction(SU);
1802 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1803 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
1804 CurrMOps += IncMOps;
1805 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1806 // issue width. However, we commonly reach the maximum. In this case
1807 // opportunistically bump the cycle to avoid uselessly checking everything in
1808 // the readyQ. Furthermore, a single instruction may produce more than one
1809 // cycle's worth of micro-ops.
1811 // TODO: Also check if this SU must end a dispatch group.
1812 unsigned NextCycle = CurrCycle;
1813 if (CurrMOps >= SchedModel->getIssueWidth()) {
1815 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
1816 << " at cycle " << CurrCycle << '\n');
1818 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1819 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
1821 switch (SchedModel->getMicroOpBufferSize()) {
1823 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
1826 if (ReadyCycle > NextCycle) {
1827 NextCycle = ReadyCycle;
1828 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
1832 // We don't currently model the OOO reorder buffer, so consider all
1833 // scheduled MOps to be "retired".
1836 RetiredMOps += IncMOps;
1838 // Update resource counts and critical resource.
1839 if (SchedModel->hasInstrSchedModel()) {
1840 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
1841 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
1842 Rem->RemIssueCount -= DecRemIssue;
1843 if (ZoneCritResIdx) {
1844 // Scale scheduled micro-ops for comparing with the critical resource.
1845 unsigned ScaledMOps =
1846 RetiredMOps * SchedModel->getMicroOpFactor();
1848 // If scaled micro-ops are now more than the previous critical resource by
1849 // a full cycle, then micro-ops issue becomes critical.
1850 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
1851 >= (int)SchedModel->getLatencyFactor()) {
1853 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
1854 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
1857 for (TargetSchedModel::ProcResIter
1858 PI = SchedModel->getWriteProcResBegin(SC),
1859 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1861 countResource(PI->ProcResourceIdx, PI->Cycles, ReadyCycle);
1862 if (RCycle > NextCycle)
1866 // Update ExpectedLatency and DependentLatency.
1867 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
1868 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
1869 if (SU->getDepth() > TopLatency) {
1870 TopLatency = SU->getDepth();
1871 DEBUG(dbgs() << " " << Available.getName()
1872 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
1874 if (SU->getHeight() > BotLatency) {
1875 BotLatency = SU->getHeight();
1876 DEBUG(dbgs() << " " << Available.getName()
1877 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
1879 // If we stall for any reason, bump the cycle.
1880 if (NextCycle > CurrCycle) {
1881 bumpCycle(NextCycle);
1884 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
1885 // resource limited. If a stall occured, bumpCycle does this.
1886 unsigned LFactor = SchedModel->getLatencyFactor();
1888 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1891 DEBUG(dumpScheduledState());
1894 /// Release pending ready nodes in to the available queue. This makes them
1895 /// visible to heuristics.
1896 void ConvergingScheduler::SchedBoundary::releasePending() {
1897 // If the available queue is empty, it is safe to reset MinReadyCycle.
1898 if (Available.empty())
1899 MinReadyCycle = UINT_MAX;
1901 // Check to see if any of the pending instructions are ready to issue. If
1902 // so, add them to the available queue.
1903 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1904 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1905 SUnit *SU = *(Pending.begin()+i);
1906 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
1908 if (ReadyCycle < MinReadyCycle)
1909 MinReadyCycle = ReadyCycle;
1911 if (!IsBuffered && ReadyCycle > CurrCycle)
1914 if (checkHazard(SU))
1918 Pending.remove(Pending.begin()+i);
1921 DEBUG(if (!Pending.empty()) Pending.dump());
1922 CheckPending = false;
1925 /// Remove SU from the ready set for this boundary.
1926 void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1927 if (Available.isInQueue(SU))
1928 Available.remove(Available.find(SU));
1930 assert(Pending.isInQueue(SU) && "bad ready count");
1931 Pending.remove(Pending.find(SU));
1935 /// If this queue only has one ready candidate, return it. As a side effect,
1936 /// defer any nodes that now hit a hazard, and advance the cycle until at least
1937 /// one node is ready. If multiple instructions are ready, return NULL.
1938 SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1943 // Defer any ready instrs that now have a hazard.
1944 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1945 if (checkHazard(*I)) {
1947 I = Available.remove(I);
1953 for (unsigned i = 0; Available.empty(); ++i) {
1954 assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
1955 "permanent hazard"); (void)i;
1956 bumpCycle(CurrCycle + 1);
1959 if (Available.size() == 1)
1960 return *Available.begin();
1965 // This is useful information to dump after bumpNode.
1966 // Note that the Queue contents are more useful before pickNodeFromQueue.
1967 void ConvergingScheduler::SchedBoundary::dumpScheduledState() {
1970 if (ZoneCritResIdx) {
1971 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
1972 ResCount = getResourceCount(ZoneCritResIdx);
1975 ResFactor = SchedModel->getMicroOpFactor();
1976 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
1978 unsigned LFactor = SchedModel->getLatencyFactor();
1979 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
1980 << " Retired: " << RetiredMOps;
1981 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
1982 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
1983 << ResCount / ResFactor << " " << getResourceName(ZoneCritResIdx)
1984 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
1985 << (IsResourceLimited ? " - Resource" : " - Latency")
1990 void ConvergingScheduler::SchedCandidate::
1991 initResourceDelta(const ScheduleDAGMI *DAG,
1992 const TargetSchedModel *SchedModel) {
1993 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1996 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1997 for (TargetSchedModel::ProcResIter
1998 PI = SchedModel->getWriteProcResBegin(SC),
1999 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2000 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2001 ResDelta.CritResources += PI->Cycles;
2002 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2003 ResDelta.DemandedResources += PI->Cycles;
2008 /// Return true if this heuristic determines order.
2009 static bool tryLess(int TryVal, int CandVal,
2010 ConvergingScheduler::SchedCandidate &TryCand,
2011 ConvergingScheduler::SchedCandidate &Cand,
2012 ConvergingScheduler::CandReason Reason) {
2013 if (TryVal < CandVal) {
2014 TryCand.Reason = Reason;
2017 if (TryVal > CandVal) {
2018 if (Cand.Reason > Reason)
2019 Cand.Reason = Reason;
2022 Cand.setRepeat(Reason);
2026 static bool tryGreater(int TryVal, int CandVal,
2027 ConvergingScheduler::SchedCandidate &TryCand,
2028 ConvergingScheduler::SchedCandidate &Cand,
2029 ConvergingScheduler::CandReason Reason) {
2030 if (TryVal > CandVal) {
2031 TryCand.Reason = Reason;
2034 if (TryVal < CandVal) {
2035 if (Cand.Reason > Reason)
2036 Cand.Reason = Reason;
2039 Cand.setRepeat(Reason);
2043 static bool tryPressure(const PressureElement &TryP,
2044 const PressureElement &CandP,
2045 ConvergingScheduler::SchedCandidate &TryCand,
2046 ConvergingScheduler::SchedCandidate &Cand,
2047 ConvergingScheduler::CandReason Reason) {
2048 // If both candidates affect the same set, go with the smallest increase.
2049 if (TryP.PSetID == CandP.PSetID) {
2050 return tryLess(TryP.UnitIncrease, CandP.UnitIncrease, TryCand, Cand,
2053 // If one candidate decreases and the other increases, go with it.
2054 if (tryLess(TryP.UnitIncrease < 0, CandP.UnitIncrease < 0, TryCand, Cand,
2058 // If TryP has lower Rank, it has a higher priority.
2059 int TryRank = TryP.PSetRank();
2060 int CandRank = CandP.PSetRank();
2061 // If the candidates are decreasing pressure, reverse priority.
2062 if (TryP.UnitIncrease < 0)
2063 std::swap(TryRank, CandRank);
2064 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2067 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2068 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2071 /// Minimize physical register live ranges. Regalloc wants them adjacent to
2072 /// their physreg def/use.
2074 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2075 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2076 /// with the operation that produces or consumes the physreg. We'll do this when
2077 /// regalloc has support for parallel copies.
2078 static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2079 const MachineInstr *MI = SU->getInstr();
2083 unsigned ScheduledOper = isTop ? 1 : 0;
2084 unsigned UnscheduledOper = isTop ? 0 : 1;
2085 // If we have already scheduled the physreg produce/consumer, immediately
2086 // schedule the copy.
2087 if (TargetRegisterInfo::isPhysicalRegister(
2088 MI->getOperand(ScheduledOper).getReg()))
2090 // If the physreg is at the boundary, defer it. Otherwise schedule it
2091 // immediately to free the dependent. We can hoist the copy later.
2092 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2093 if (TargetRegisterInfo::isPhysicalRegister(
2094 MI->getOperand(UnscheduledOper).getReg()))
2095 return AtBoundary ? -1 : 1;
2099 /// Apply a set of heursitics to a new candidate. Heuristics are currently
2100 /// hierarchical. This may be more efficient than a graduated cost model because
2101 /// we don't need to evaluate all aspects of the model for each node in the
2102 /// queue. But it's really done to make the heuristics easier to debug and
2103 /// statistically analyze.
2105 /// \param Cand provides the policy and current best candidate.
2106 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2107 /// \param Zone describes the scheduled zone that we are extending.
2108 /// \param RPTracker describes reg pressure within the scheduled zone.
2109 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
2110 void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
2111 SchedCandidate &TryCand,
2112 SchedBoundary &Zone,
2113 const RegPressureTracker &RPTracker,
2114 RegPressureTracker &TempTracker) {
2116 // Always initialize TryCand's RPDelta.
2117 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
2118 DAG->getRegionCriticalPSets(),
2119 DAG->getRegPressure().MaxSetPressure);
2121 // Initialize the candidate if needed.
2122 if (!Cand.isValid()) {
2123 TryCand.Reason = NodeOrder;
2127 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2128 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2129 TryCand, Cand, PhysRegCopy))
2132 // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2133 // invalid; convert it to INT_MAX to give it lowest priority.
2134 if (tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
2138 // Avoid increasing the max critical pressure in the scheduled region.
2139 if (tryPressure(TryCand.RPDelta.CriticalMax, Cand.RPDelta.CriticalMax,
2140 TryCand, Cand, RegCritical))
2143 // Keep clustered nodes together to encourage downstream peephole
2144 // optimizations which may reduce resource requirements.
2146 // This is a best effort to set things up for a post-RA pass. Optimizations
2147 // like generating loads of multiple registers should ideally be done within
2148 // the scheduler pass by combining the loads during DAG postprocessing.
2149 const SUnit *NextClusterSU =
2150 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2151 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2152 TryCand, Cand, Cluster))
2155 // Weak edges are for clustering and other constraints.
2156 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2157 getWeakLeft(Cand.SU, Zone.isTop()),
2158 TryCand, Cand, Weak)) {
2161 // Avoid increasing the max pressure of the entire region.
2162 if (tryPressure(TryCand.RPDelta.CurrentMax, Cand.RPDelta.CurrentMax,
2163 TryCand, Cand, RegMax))
2166 // Avoid critical resource consumption and balance the schedule.
2167 TryCand.initResourceDelta(DAG, SchedModel);
2168 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2169 TryCand, Cand, ResourceReduce))
2171 if (tryGreater(TryCand.ResDelta.DemandedResources,
2172 Cand.ResDelta.DemandedResources,
2173 TryCand, Cand, ResourceDemand))
2176 // Avoid serializing long latency dependence chains.
2177 if (Cand.Policy.ReduceLatency) {
2179 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2180 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2181 TryCand, Cand, TopDepthReduce))
2184 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2185 TryCand, Cand, TopPathReduce))
2189 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2190 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2191 TryCand, Cand, BotHeightReduce))
2194 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2195 TryCand, Cand, BotPathReduce))
2200 // Prefer immediate defs/users of the last scheduled instruction. This is a
2201 // local pressure avoidance strategy that also makes the machine code
2203 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
2204 TryCand, Cand, NextDefUse))
2207 // Fall through to original instruction order.
2208 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2209 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2210 TryCand.Reason = NodeOrder;
2215 const char *ConvergingScheduler::getReasonStr(
2216 ConvergingScheduler::CandReason Reason) {
2218 case NoCand: return "NOCAND ";
2219 case PhysRegCopy: return "PREG-COPY";
2220 case RegExcess: return "REG-EXCESS";
2221 case RegCritical: return "REG-CRIT ";
2222 case Cluster: return "CLUSTER ";
2223 case Weak: return "WEAK ";
2224 case RegMax: return "REG-MAX ";
2225 case ResourceReduce: return "RES-REDUCE";
2226 case ResourceDemand: return "RES-DEMAND";
2227 case TopDepthReduce: return "TOP-DEPTH ";
2228 case TopPathReduce: return "TOP-PATH ";
2229 case BotHeightReduce:return "BOT-HEIGHT";
2230 case BotPathReduce: return "BOT-PATH ";
2231 case NextDefUse: return "DEF-USE ";
2232 case NodeOrder: return "ORDER ";
2234 llvm_unreachable("Unknown reason!");
2237 void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand) {
2239 unsigned ResIdx = 0;
2240 unsigned Latency = 0;
2241 switch (Cand.Reason) {
2245 P = Cand.RPDelta.Excess;
2248 P = Cand.RPDelta.CriticalMax;
2251 P = Cand.RPDelta.CurrentMax;
2253 case ResourceReduce:
2254 ResIdx = Cand.Policy.ReduceResIdx;
2256 case ResourceDemand:
2257 ResIdx = Cand.Policy.DemandResIdx;
2259 case TopDepthReduce:
2260 Latency = Cand.SU->getDepth();
2263 Latency = Cand.SU->getHeight();
2265 case BotHeightReduce:
2266 Latency = Cand.SU->getHeight();
2269 Latency = Cand.SU->getDepth();
2272 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2274 dbgs() << " " << TRI->getRegPressureSetName(P.PSetID)
2275 << ":" << P.UnitIncrease << " ";
2279 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2283 dbgs() << " " << Latency << " cycles ";
2290 /// Pick the best candidate from the top queue.
2292 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2293 /// DAG building. To adjust for the current scheduling location we need to
2294 /// maintain the number of vreg uses remaining to be top-scheduled.
2295 void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2296 const RegPressureTracker &RPTracker,
2297 SchedCandidate &Cand) {
2298 ReadyQueue &Q = Zone.Available;
2302 // getMaxPressureDelta temporarily modifies the tracker.
2303 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2305 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2307 SchedCandidate TryCand(Cand.Policy);
2309 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2310 if (TryCand.Reason != NoCand) {
2311 // Initialize resource delta if needed in case future heuristics query it.
2312 if (TryCand.ResDelta == SchedResourceDelta())
2313 TryCand.initResourceDelta(DAG, SchedModel);
2314 Cand.setBest(TryCand);
2315 DEBUG(traceCandidate(Cand));
2320 static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
2322 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2323 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
2326 /// Pick the best candidate node from either the top or bottom queue.
2327 SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
2328 // Schedule as far as possible in the direction of no choice. This is most
2329 // efficient, but also provides the best heuristics for CriticalPSets.
2330 if (SUnit *SU = Bot.pickOnlyChoice()) {
2332 DEBUG(dbgs() << "Pick Bot NOCAND\n");
2335 if (SUnit *SU = Top.pickOnlyChoice()) {
2337 DEBUG(dbgs() << "Pick Top NOCAND\n");
2340 CandPolicy NoPolicy;
2341 SchedCandidate BotCand(NoPolicy);
2342 SchedCandidate TopCand(NoPolicy);
2343 Bot.setPolicy(BotCand.Policy, Top);
2344 Top.setPolicy(TopCand.Policy, Bot);
2346 // Prefer bottom scheduling when heuristics are silent.
2347 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2348 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2350 // If either Q has a single candidate that provides the least increase in
2351 // Excess pressure, we can immediately schedule from that Q.
2353 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2354 // affects picking from either Q. If scheduling in one direction must
2355 // increase pressure for one of the excess PSets, then schedule in that
2356 // direction first to provide more freedom in the other direction.
2357 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2358 || (BotCand.Reason == RegCritical
2359 && !BotCand.isRepeat(RegCritical)))
2362 tracePick(BotCand, IsTopNode);
2365 // Check if the top Q has a better candidate.
2366 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2367 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2369 // Choose the queue with the most important (lowest enum) reason.
2370 if (TopCand.Reason < BotCand.Reason) {
2372 tracePick(TopCand, IsTopNode);
2375 // Otherwise prefer the bottom candidate, in node order if all else failed.
2377 tracePick(BotCand, IsTopNode);
2381 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2382 SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2383 if (DAG->top() == DAG->bottom()) {
2384 assert(Top.Available.empty() && Top.Pending.empty() &&
2385 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2391 SU = Top.pickOnlyChoice();
2393 CandPolicy NoPolicy;
2394 SchedCandidate TopCand(NoPolicy);
2395 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2396 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2401 else if (ForceBottomUp) {
2402 SU = Bot.pickOnlyChoice();
2404 CandPolicy NoPolicy;
2405 SchedCandidate BotCand(NoPolicy);
2406 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2407 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2413 SU = pickNodeBidirectional(IsTopNode);
2415 } while (SU->isScheduled);
2417 if (SU->isTopReady())
2418 Top.removeReady(SU);
2419 if (SU->isBottomReady())
2420 Bot.removeReady(SU);
2422 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2426 void ConvergingScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
2428 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2431 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2433 // Find already scheduled copies with a single physreg dependence and move
2434 // them just above the scheduled instruction.
2435 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2437 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2439 SUnit *DepSU = I->getSUnit();
2440 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2442 MachineInstr *Copy = DepSU->getInstr();
2443 if (!Copy->isCopy())
2445 DEBUG(dbgs() << " Rescheduling physreg copy ";
2446 I->getSUnit()->dump(DAG));
2447 DAG->moveInstruction(Copy, InsertPos);
2451 /// Update the scheduler's state after scheduling a node. This is the same node
2452 /// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
2453 /// it's state based on the current cycle before MachineSchedStrategy does.
2455 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2456 /// them here. See comments in biasPhysRegCopy.
2457 void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2459 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.CurrCycle);
2461 if (SU->hasPhysRegUses)
2462 reschedulePhysRegCopies(SU, true);
2465 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.CurrCycle);
2467 if (SU->hasPhysRegDefs)
2468 reschedulePhysRegCopies(SU, false);
2472 /// Create the standard converging machine scheduler. This will be used as the
2473 /// default scheduler if the target does not set a default.
2474 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
2475 assert((!ForceTopDown || !ForceBottomUp) &&
2476 "-misched-topdown incompatible with -misched-bottomup");
2477 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2478 // Register DAG post-processors.
2480 // FIXME: extend the mutation API to allow earlier mutations to instantiate
2481 // data and pass it to later mutations. Have a single mutation that gathers
2482 // the interesting nodes in one pass.
2483 DAG->addMutation(new CopyConstrain(DAG->TII, DAG->TRI));
2484 if (EnableLoadCluster)
2485 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
2486 if (EnableMacroFusion)
2487 DAG->addMutation(new MacroFusion(DAG->TII));
2490 static MachineSchedRegistry
2491 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2492 createConvergingSched);
2494 //===----------------------------------------------------------------------===//
2495 // ILP Scheduler. Currently for experimental analysis of heuristics.
2496 //===----------------------------------------------------------------------===//
2499 /// \brief Order nodes by the ILP metric.
2501 const SchedDFSResult *DFSResult;
2502 const BitVector *ScheduledTrees;
2505 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
2507 /// \brief Apply a less-than relation on node priority.
2509 /// (Return true if A comes after B in the Q.)
2510 bool operator()(const SUnit *A, const SUnit *B) const {
2511 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2512 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2513 if (SchedTreeA != SchedTreeB) {
2514 // Unscheduled trees have lower priority.
2515 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2516 return ScheduledTrees->test(SchedTreeB);
2518 // Trees with shallower connections have have lower priority.
2519 if (DFSResult->getSubtreeLevel(SchedTreeA)
2520 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2521 return DFSResult->getSubtreeLevel(SchedTreeA)
2522 < DFSResult->getSubtreeLevel(SchedTreeB);
2526 return DFSResult->getILP(A) < DFSResult->getILP(B);
2528 return DFSResult->getILP(A) > DFSResult->getILP(B);
2532 /// \brief Schedule based on the ILP metric.
2533 class ILPScheduler : public MachineSchedStrategy {
2534 /// In case all subtrees are eventually connected to a common root through
2535 /// data dependence (e.g. reduction), place an upper limit on their size.
2537 /// FIXME: A subtree limit is generally good, but in the situation commented
2538 /// above, where multiple similar subtrees feed a common root, we should
2539 /// only split at a point where the resulting subtrees will be balanced.
2540 /// (a motivating test case must be found).
2541 static const unsigned SubtreeLimit = 16;
2546 std::vector<SUnit*> ReadyQ;
2548 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
2550 virtual void initialize(ScheduleDAGMI *dag) {
2552 DAG->computeDFSResult();
2553 Cmp.DFSResult = DAG->getDFSResult();
2554 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
2558 virtual void registerRoots() {
2559 // Restore the heap in ReadyQ with the updated DFS results.
2560 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2563 /// Implement MachineSchedStrategy interface.
2564 /// -----------------------------------------
2566 /// Callback to select the highest priority node from the ready Q.
2567 virtual SUnit *pickNode(bool &IsTopNode) {
2568 if (ReadyQ.empty()) return NULL;
2569 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2570 SUnit *SU = ReadyQ.back();
2573 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
2574 << " ILP: " << DAG->getDFSResult()->getILP(SU)
2575 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2576 << DAG->getDFSResult()->getSubtreeLevel(
2577 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
2578 << "Scheduling " << *SU->getInstr());
2582 /// \brief Scheduler callback to notify that a new subtree is scheduled.
2583 virtual void scheduleTree(unsigned SubtreeID) {
2584 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2587 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2588 /// DFSResults, and resort the priority Q.
2589 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2590 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
2593 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2595 virtual void releaseBottomNode(SUnit *SU) {
2596 ReadyQ.push_back(SU);
2597 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2602 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2603 return new ScheduleDAGMI(C, new ILPScheduler(true));
2605 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2606 return new ScheduleDAGMI(C, new ILPScheduler(false));
2608 static MachineSchedRegistry ILPMaxRegistry(
2609 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2610 static MachineSchedRegistry ILPMinRegistry(
2611 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2613 //===----------------------------------------------------------------------===//
2614 // Machine Instruction Shuffler for Correctness Testing
2615 //===----------------------------------------------------------------------===//
2619 /// Apply a less-than relation on the node order, which corresponds to the
2620 /// instruction order prior to scheduling. IsReverse implements greater-than.
2621 template<bool IsReverse>
2623 bool operator()(SUnit *A, SUnit *B) const {
2625 return A->NodeNum > B->NodeNum;
2627 return A->NodeNum < B->NodeNum;
2631 /// Reorder instructions as much as possible.
2632 class InstructionShuffler : public MachineSchedStrategy {
2636 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2637 // gives nodes with a higher number higher priority causing the latest
2638 // instructions to be scheduled first.
2639 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2641 // When scheduling bottom-up, use greater-than as the queue priority.
2642 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2645 InstructionShuffler(bool alternate, bool topdown)
2646 : IsAlternating(alternate), IsTopDown(topdown) {}
2648 virtual void initialize(ScheduleDAGMI *) {
2653 /// Implement MachineSchedStrategy interface.
2654 /// -----------------------------------------
2656 virtual SUnit *pickNode(bool &IsTopNode) {
2660 if (TopQ.empty()) return NULL;
2663 } while (SU->isScheduled);
2668 if (BottomQ.empty()) return NULL;
2671 } while (SU->isScheduled);
2675 IsTopDown = !IsTopDown;
2679 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2681 virtual void releaseTopNode(SUnit *SU) {
2684 virtual void releaseBottomNode(SUnit *SU) {
2690 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
2691 bool Alternate = !ForceTopDown && !ForceBottomUp;
2692 bool TopDown = !ForceBottomUp;
2693 assert((TopDown || !ForceTopDown) &&
2694 "-misched-topdown incompatible with -misched-bottomup");
2695 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
2697 static MachineSchedRegistry ShufflerRegistry(
2698 "shuffle", "Shuffle machine instructions alternating directions",
2699 createInstructionShuffler);
2702 //===----------------------------------------------------------------------===//
2703 // GraphWriter support for ScheduleDAGMI.
2704 //===----------------------------------------------------------------------===//
2709 template<> struct GraphTraits<
2710 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
2713 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
2715 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2717 static std::string getGraphName(const ScheduleDAG *G) {
2718 return G->MF.getName();
2721 static bool renderGraphFromBottomUp() {
2725 static bool isNodeHidden(const SUnit *Node) {
2726 return (Node->NumPreds > 10 || Node->NumSuccs > 10);
2729 static bool hasNodeAddressLabel(const SUnit *Node,
2730 const ScheduleDAG *Graph) {
2734 /// If you want to override the dot attributes printed for a particular
2735 /// edge, override this method.
2736 static std::string getEdgeAttributes(const SUnit *Node,
2738 const ScheduleDAG *Graph) {
2739 if (EI.isArtificialDep())
2740 return "color=cyan,style=dashed";
2742 return "color=blue,style=dashed";
2746 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
2748 raw_string_ostream SS(Str);
2749 SS << "SU(" << SU->NodeNum << ')';
2752 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
2753 return G->getGraphNodeLabel(SU);
2756 static std::string getNodeAttributes(const SUnit *N,
2757 const ScheduleDAG *Graph) {
2758 std::string Str("shape=Mrecord");
2759 const SchedDFSResult *DFS =
2760 static_cast<const ScheduleDAGMI*>(Graph)->getDFSResult();
2762 Str += ",style=filled,fillcolor=\"#";
2763 Str += DOT::getColorString(DFS->getSubtreeID(N));
2772 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
2773 /// rendered using 'dot'.
2775 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
2777 ViewGraph(this, Name, false, Title);
2779 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
2780 << "systems with Graphviz or gv!\n";
2784 /// Out-of-line implementation with no arguments is handy for gdb.
2785 void ScheduleDAGMI::viewGraph() {
2786 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());