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/Passes.h"
23 #include "llvm/CodeGen/RegisterClassInfo.h"
24 #include "llvm/CodeGen/ScheduleDFS.h"
25 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
35 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
36 cl::desc("Force top-down list scheduling"));
37 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
38 cl::desc("Force bottom-up list scheduling"));
42 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
43 cl::desc("Pop up a window to show MISched dags after they are processed"));
45 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
46 cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
48 static bool ViewMISchedDAGs = false;
51 // Experimental heuristics
52 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
53 cl::desc("Enable load clustering."), cl::init(true));
55 // Experimental heuristics
56 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
57 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
59 //===----------------------------------------------------------------------===//
60 // Machine Instruction Scheduling Pass and Registry
61 //===----------------------------------------------------------------------===//
63 MachineSchedContext::MachineSchedContext():
64 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
65 RegClassInfo = new RegisterClassInfo();
68 MachineSchedContext::~MachineSchedContext() {
73 /// MachineScheduler runs after coalescing and before register allocation.
74 class MachineScheduler : public MachineSchedContext,
75 public MachineFunctionPass {
79 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
81 virtual void releaseMemory() {}
83 virtual bool runOnMachineFunction(MachineFunction&);
85 virtual void print(raw_ostream &O, const Module* = 0) const;
87 static char ID; // Class identification, replacement for typeinfo
91 char MachineScheduler::ID = 0;
93 char &llvm::MachineSchedulerID = MachineScheduler::ID;
95 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
96 "Machine Instruction Scheduler", false, false)
97 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
98 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
99 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
100 INITIALIZE_PASS_END(MachineScheduler, "misched",
101 "Machine Instruction Scheduler", false, false)
103 MachineScheduler::MachineScheduler()
104 : MachineFunctionPass(ID) {
105 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
108 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
109 AU.setPreservesCFG();
110 AU.addRequiredID(MachineDominatorsID);
111 AU.addRequired<MachineLoopInfo>();
112 AU.addRequired<AliasAnalysis>();
113 AU.addRequired<TargetPassConfig>();
114 AU.addRequired<SlotIndexes>();
115 AU.addPreserved<SlotIndexes>();
116 AU.addRequired<LiveIntervals>();
117 AU.addPreserved<LiveIntervals>();
118 MachineFunctionPass::getAnalysisUsage(AU);
121 MachinePassRegistry MachineSchedRegistry::Registry;
123 /// A dummy default scheduler factory indicates whether the scheduler
124 /// is overridden on the command line.
125 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
129 /// MachineSchedOpt allows command line selection of the scheduler.
130 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
131 RegisterPassParser<MachineSchedRegistry> >
132 MachineSchedOpt("misched",
133 cl::init(&useDefaultMachineSched), cl::Hidden,
134 cl::desc("Machine instruction scheduler to use"));
136 static MachineSchedRegistry
137 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
138 useDefaultMachineSched);
140 /// Forward declare the standard machine scheduler. This will be used as the
141 /// default scheduler if the target does not set a default.
142 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
145 /// Decrement this iterator until reaching the top or a non-debug instr.
146 static MachineBasicBlock::iterator
147 priorNonDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator Beg) {
148 assert(I != Beg && "reached the top of the region, cannot decrement");
150 if (!I->isDebugValue())
156 /// If this iterator is a debug value, increment until reaching the End or a
157 /// non-debug instruction.
158 static MachineBasicBlock::iterator
159 nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
160 for(; I != End; ++I) {
161 if (!I->isDebugValue())
167 /// Top-level MachineScheduler pass driver.
169 /// Visit blocks in function order. Divide each block into scheduling regions
170 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
171 /// consistent with the DAG builder, which traverses the interior of the
172 /// scheduling regions bottom-up.
174 /// This design avoids exposing scheduling boundaries to the DAG builder,
175 /// simplifying the DAG builder's support for "special" target instructions.
176 /// At the same time the design allows target schedulers to operate across
177 /// scheduling boundaries, for example to bundle the boudary instructions
178 /// without reordering them. This creates complexity, because the target
179 /// scheduler must update the RegionBegin and RegionEnd positions cached by
180 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
181 /// design would be to split blocks at scheduling boundaries, but LLVM has a
182 /// general bias against block splitting purely for implementation simplicity.
183 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
184 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
186 // Initialize the context of the pass.
188 MLI = &getAnalysis<MachineLoopInfo>();
189 MDT = &getAnalysis<MachineDominatorTree>();
190 PassConfig = &getAnalysis<TargetPassConfig>();
191 AA = &getAnalysis<AliasAnalysis>();
193 LIS = &getAnalysis<LiveIntervals>();
194 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
196 RegClassInfo->runOnMachineFunction(*MF);
198 // Select the scheduler, or set the default.
199 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
200 if (Ctor == useDefaultMachineSched) {
201 // Get the default scheduler set by the target.
202 Ctor = MachineSchedRegistry::getDefault();
204 Ctor = createConvergingSched;
205 MachineSchedRegistry::setDefault(Ctor);
208 // Instantiate the selected scheduler.
209 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
211 // Visit all machine basic blocks.
213 // TODO: Visit blocks in global postorder or postorder within the bottom-up
214 // loop tree. Then we can optionally compute global RegPressure.
215 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
216 MBB != MBBEnd; ++MBB) {
218 Scheduler->startBlock(MBB);
220 // Break the block into scheduling regions [I, RegionEnd), and schedule each
221 // region as soon as it is discovered. RegionEnd points the scheduling
222 // boundary at the bottom of the region. The DAG does not include RegionEnd,
223 // but the region does (i.e. the next RegionEnd is above the previous
224 // RegionBegin). If the current block has no terminator then RegionEnd ==
225 // MBB->end() for the bottom region.
227 // The Scheduler may insert instructions during either schedule() or
228 // exitRegion(), even for empty regions. So the local iterators 'I' and
229 // 'RegionEnd' are invalid across these calls.
230 unsigned RemainingInstrs = MBB->size();
231 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
232 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
234 // Avoid decrementing RegionEnd for blocks with no terminator.
235 if (RegionEnd != MBB->end()
236 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
238 // Count the boundary instruction.
242 // The next region starts above the previous region. Look backward in the
243 // instruction stream until we find the nearest boundary.
244 MachineBasicBlock::iterator I = RegionEnd;
245 for(;I != MBB->begin(); --I, --RemainingInstrs) {
246 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
249 // Notify the scheduler of the region, even if we may skip scheduling
250 // it. Perhaps it still needs to be bundled.
251 Scheduler->enterRegion(MBB, I, RegionEnd, RemainingInstrs);
253 // Skip empty scheduling regions (0 or 1 schedulable instructions).
254 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
255 // Close the current region. Bundle the terminator if needed.
256 // This invalidates 'RegionEnd' and 'I'.
257 Scheduler->exitRegion();
260 DEBUG(dbgs() << "********** MI Scheduling **********\n");
261 DEBUG(dbgs() << MF->getName()
262 << ":BB#" << MBB->getNumber() << "\n From: " << *I << " To: ";
263 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
264 else dbgs() << "End";
265 dbgs() << " Remaining: " << RemainingInstrs << "\n");
267 // Schedule a region: possibly reorder instructions.
268 // This invalidates 'RegionEnd' and 'I'.
269 Scheduler->schedule();
271 // Close the current region.
272 Scheduler->exitRegion();
274 // Scheduling has invalidated the current iterator 'I'. Ask the
275 // scheduler for the top of it's scheduled region.
276 RegionEnd = Scheduler->begin();
278 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
279 Scheduler->finishBlock();
281 Scheduler->finalizeSchedule();
282 DEBUG(LIS->print(dbgs()));
286 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
290 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
291 void ReadyQueue::dump() {
292 dbgs() << Name << ": ";
293 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
294 dbgs() << Queue[i]->NodeNum << " ";
299 //===----------------------------------------------------------------------===//
300 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
302 //===----------------------------------------------------------------------===//
304 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
305 if (SuccSU != &ExitSU) {
306 // Do not use WillCreateCycle, it assumes SD scheduling.
307 // If Pred is reachable from Succ, then the edge creates a cycle.
308 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
310 Topo.AddPred(SuccSU, PredDep.getSUnit());
312 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
313 // Return true regardless of whether a new edge needed to be inserted.
317 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
318 /// NumPredsLeft reaches zero, release the successor node.
320 /// FIXME: Adjust SuccSU height based on MinLatency.
321 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
322 SUnit *SuccSU = SuccEdge->getSUnit();
324 if (SuccEdge->isWeak()) {
325 --SuccSU->WeakPredsLeft;
326 if (SuccEdge->isCluster())
327 NextClusterSucc = SuccSU;
331 if (SuccSU->NumPredsLeft == 0) {
332 dbgs() << "*** Scheduling failed! ***\n";
334 dbgs() << " has been released too many times!\n";
338 --SuccSU->NumPredsLeft;
339 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
340 SchedImpl->releaseTopNode(SuccSU);
343 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
344 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
345 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
347 releaseSucc(SU, &*I);
351 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
352 /// NumSuccsLeft reaches zero, release the predecessor node.
354 /// FIXME: Adjust PredSU height based on MinLatency.
355 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
356 SUnit *PredSU = PredEdge->getSUnit();
358 if (PredEdge->isWeak()) {
359 --PredSU->WeakSuccsLeft;
360 if (PredEdge->isCluster())
361 NextClusterPred = PredSU;
365 if (PredSU->NumSuccsLeft == 0) {
366 dbgs() << "*** Scheduling failed! ***\n";
368 dbgs() << " has been released too many times!\n";
372 --PredSU->NumSuccsLeft;
373 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
374 SchedImpl->releaseBottomNode(PredSU);
377 /// releasePredecessors - Call releasePred on each of SU's predecessors.
378 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
379 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
381 releasePred(SU, &*I);
385 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
386 MachineBasicBlock::iterator InsertPos) {
387 // Advance RegionBegin if the first instruction moves down.
388 if (&*RegionBegin == MI)
391 // Update the instruction stream.
392 BB->splice(InsertPos, BB, MI);
394 // Update LiveIntervals
395 LIS->handleMove(MI, /*UpdateFlags=*/true);
397 // Recede RegionBegin if an instruction moves above the first.
398 if (RegionBegin == InsertPos)
402 bool ScheduleDAGMI::checkSchedLimit() {
404 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
405 CurrentTop = CurrentBottom;
408 ++NumInstrsScheduled;
413 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
414 /// crossing a scheduling boundary. [begin, end) includes all instructions in
415 /// the region, including the boundary itself and single-instruction regions
416 /// that don't get scheduled.
417 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
418 MachineBasicBlock::iterator begin,
419 MachineBasicBlock::iterator end,
422 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
424 // For convenience remember the end of the liveness region.
426 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
429 // Setup the register pressure trackers for the top scheduled top and bottom
430 // scheduled regions.
431 void ScheduleDAGMI::initRegPressure() {
432 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
433 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
435 // Close the RPTracker to finalize live ins.
436 RPTracker.closeRegion();
438 DEBUG(RPTracker.getPressure().dump(TRI));
440 // Initialize the live ins and live outs.
441 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
442 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
444 // Close one end of the tracker so we can call
445 // getMaxUpward/DownwardPressureDelta before advancing across any
446 // instructions. This converts currently live regs into live ins/outs.
447 TopRPTracker.closeTop();
448 BotRPTracker.closeBottom();
450 // Account for liveness generated by the region boundary.
451 if (LiveRegionEnd != RegionEnd)
452 BotRPTracker.recede();
454 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
456 // Cache the list of excess pressure sets in this region. This will also track
457 // the max pressure in the scheduled code for these sets.
458 RegionCriticalPSets.clear();
459 std::vector<unsigned> RegionPressure = RPTracker.getPressure().MaxSetPressure;
460 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
461 unsigned Limit = TRI->getRegPressureSetLimit(i);
462 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
464 << " Actual " << RegionPressure[i] << "\n");
465 if (RegionPressure[i] > Limit)
466 RegionCriticalPSets.push_back(PressureElement(i, 0));
468 DEBUG(dbgs() << "Excess PSets: ";
469 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
470 dbgs() << TRI->getRegPressureSetName(
471 RegionCriticalPSets[i].PSetID) << " ";
475 // FIXME: When the pressure tracker deals in pressure differences then we won't
476 // iterate over all RegionCriticalPSets[i].
478 updateScheduledPressure(std::vector<unsigned> NewMaxPressure) {
479 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
480 unsigned ID = RegionCriticalPSets[i].PSetID;
481 int &MaxUnits = RegionCriticalPSets[i].UnitIncrease;
482 if ((int)NewMaxPressure[ID] > MaxUnits)
483 MaxUnits = NewMaxPressure[ID];
487 /// schedule - Called back from MachineScheduler::runOnMachineFunction
488 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
489 /// only includes instructions that have DAG nodes, not scheduling boundaries.
491 /// This is a skeletal driver, with all the functionality pushed into helpers,
492 /// so that it can be easilly extended by experimental schedulers. Generally,
493 /// implementing MachineSchedStrategy should be sufficient to implement a new
494 /// scheduling algorithm. However, if a scheduler further subclasses
495 /// ScheduleDAGMI then it will want to override this virtual method in order to
496 /// update any specialized state.
497 void ScheduleDAGMI::schedule() {
498 buildDAGWithRegPressure();
500 Topo.InitDAGTopologicalSorting();
504 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
505 SUnits[su].dumpAll(this));
507 if (ViewMISchedDAGs) viewGraph();
511 bool IsTopNode = false;
512 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
513 assert(!SU->isScheduled && "Node already scheduled");
514 if (!checkSchedLimit())
517 scheduleMI(SU, IsTopNode);
519 updateQueues(SU, IsTopNode);
521 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
526 unsigned BBNum = begin()->getParent()->getNumber();
527 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
533 /// Build the DAG and setup three register pressure trackers.
534 void ScheduleDAGMI::buildDAGWithRegPressure() {
535 // Initialize the register pressure tracker used by buildSchedGraph.
536 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
538 // Account for liveness generate by the region boundary.
539 if (LiveRegionEnd != RegionEnd)
542 // Build the DAG, and compute current register pressure.
543 buildSchedGraph(AA, &RPTracker);
544 if (ViewMISchedDAGs) viewGraph();
546 // Initialize top/bottom trackers after computing region pressure.
550 /// Apply each ScheduleDAGMutation step in order.
551 void ScheduleDAGMI::postprocessDAG() {
552 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
553 Mutations[i]->apply(this);
557 // Release all DAG roots for scheduling.
559 // Nodes with unreleased weak edges can still be roots.
560 void ScheduleDAGMI::releaseRoots() {
561 SmallVector<SUnit*, 16> BotRoots;
563 for (std::vector<SUnit>::iterator
564 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
567 // Order predecessors so DFSResult follows the critical path.
568 SU->biasCriticalPath();
570 // A SUnit is ready to top schedule if it has no predecessors.
571 if (!I->NumPredsLeft && SU != &EntrySU)
572 SchedImpl->releaseTopNode(SU);
573 // A SUnit is ready to bottom schedule if it has no successors.
574 if (!I->NumSuccsLeft && SU != &ExitSU)
575 BotRoots.push_back(SU);
577 // Release bottom roots in reverse order so the higher priority nodes appear
578 // first. This is more natural and slightly more efficient.
579 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
580 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I)
581 SchedImpl->releaseBottomNode(*I);
584 /// Identify DAG roots and setup scheduler queues.
585 void ScheduleDAGMI::initQueues() {
586 NextClusterSucc = NULL;
587 NextClusterPred = NULL;
589 // Initialize the strategy before modifying the DAG.
590 SchedImpl->initialize(this);
592 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
595 releaseSuccessors(&EntrySU);
596 releasePredecessors(&ExitSU);
598 SchedImpl->registerRoots();
600 // Advance past initial DebugValues.
601 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
602 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
603 TopRPTracker.setPos(CurrentTop);
605 CurrentBottom = RegionEnd;
608 /// Move an instruction and update register pressure.
609 void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
610 // Move the instruction to its new location in the instruction stream.
611 MachineInstr *MI = SU->getInstr();
614 assert(SU->isTopReady() && "node still has unscheduled dependencies");
615 if (&*CurrentTop == MI)
616 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
618 moveInstruction(MI, CurrentTop);
619 TopRPTracker.setPos(MI);
622 // Update top scheduled pressure.
623 TopRPTracker.advance();
624 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
625 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
628 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
629 MachineBasicBlock::iterator priorII =
630 priorNonDebug(CurrentBottom, CurrentTop);
632 CurrentBottom = priorII;
634 if (&*CurrentTop == MI) {
635 CurrentTop = nextIfDebug(++CurrentTop, priorII);
636 TopRPTracker.setPos(CurrentTop);
638 moveInstruction(MI, CurrentBottom);
641 // Update bottom scheduled pressure.
642 BotRPTracker.recede();
643 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
644 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
648 /// Update scheduler queues after scheduling an instruction.
649 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
650 // Release dependent instructions for scheduling.
652 releaseSuccessors(SU);
654 releasePredecessors(SU);
656 SU->isScheduled = true;
658 // Notify the scheduling strategy after updating the DAG.
659 SchedImpl->schedNode(SU, IsTopNode);
662 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
663 void ScheduleDAGMI::placeDebugValues() {
664 // If first instruction was a DBG_VALUE then put it back.
666 BB->splice(RegionBegin, BB, FirstDbgValue);
667 RegionBegin = FirstDbgValue;
670 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
671 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
672 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
673 MachineInstr *DbgValue = P.first;
674 MachineBasicBlock::iterator OrigPrevMI = P.second;
675 if (&*RegionBegin == DbgValue)
677 BB->splice(++OrigPrevMI, BB, DbgValue);
678 if (OrigPrevMI == llvm::prior(RegionEnd))
679 RegionEnd = DbgValue;
682 FirstDbgValue = NULL;
685 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
686 void ScheduleDAGMI::dumpSchedule() const {
687 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
688 if (SUnit *SU = getSUnit(&(*MI)))
691 dbgs() << "Missing SUnit\n";
696 //===----------------------------------------------------------------------===//
697 // LoadClusterMutation - DAG post-processing to cluster loads.
698 //===----------------------------------------------------------------------===//
701 /// \brief Post-process the DAG to create cluster edges between neighboring
703 class LoadClusterMutation : public ScheduleDAGMutation {
708 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
709 : SU(su), BaseReg(reg), Offset(ofs) {}
711 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
712 const LoadClusterMutation::LoadInfo &RHS);
714 const TargetInstrInfo *TII;
715 const TargetRegisterInfo *TRI;
717 LoadClusterMutation(const TargetInstrInfo *tii,
718 const TargetRegisterInfo *tri)
719 : TII(tii), TRI(tri) {}
721 virtual void apply(ScheduleDAGMI *DAG);
723 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
727 bool LoadClusterMutation::LoadInfoLess(
728 const LoadClusterMutation::LoadInfo &LHS,
729 const LoadClusterMutation::LoadInfo &RHS) {
730 if (LHS.BaseReg != RHS.BaseReg)
731 return LHS.BaseReg < RHS.BaseReg;
732 return LHS.Offset < RHS.Offset;
735 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
736 ScheduleDAGMI *DAG) {
737 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
738 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
739 SUnit *SU = Loads[Idx];
742 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
743 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
745 if (LoadRecords.size() < 2)
747 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
748 unsigned ClusterLength = 1;
749 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
750 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
755 SUnit *SUa = LoadRecords[Idx].SU;
756 SUnit *SUb = LoadRecords[Idx+1].SU;
757 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
758 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
760 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
761 << SUb->NodeNum << ")\n");
762 // Copy successor edges from SUa to SUb. Interleaving computation
763 // dependent on SUa can prevent load combining due to register reuse.
764 // Predecessor edges do not need to be copied from SUb to SUa since nearby
765 // loads should have effectively the same inputs.
766 for (SUnit::const_succ_iterator
767 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
768 if (SI->getSUnit() == SUb)
770 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
771 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
780 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
781 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
782 // Map DAG NodeNum to store chain ID.
783 DenseMap<unsigned, unsigned> StoreChainIDs;
784 // Map each store chain to a set of dependent loads.
785 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
786 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
787 SUnit *SU = &DAG->SUnits[Idx];
788 if (!SU->getInstr()->mayLoad())
790 unsigned ChainPredID = DAG->SUnits.size();
791 for (SUnit::const_pred_iterator
792 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
794 ChainPredID = PI->getSUnit()->NodeNum;
798 // Check if this chain-like pred has been seen
799 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
800 unsigned NumChains = StoreChainDependents.size();
801 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
802 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
804 StoreChainDependents.resize(NumChains + 1);
805 StoreChainDependents[Result.first->second].push_back(SU);
807 // Iterate over the store chains.
808 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
809 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
812 //===----------------------------------------------------------------------===//
813 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
814 //===----------------------------------------------------------------------===//
817 /// \brief Post-process the DAG to create cluster edges between instructions
818 /// that may be fused by the processor into a single operation.
819 class MacroFusion : public ScheduleDAGMutation {
820 const TargetInstrInfo *TII;
822 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
824 virtual void apply(ScheduleDAGMI *DAG);
828 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
829 /// fused operations.
830 void MacroFusion::apply(ScheduleDAGMI *DAG) {
831 // For now, assume targets can only fuse with the branch.
832 MachineInstr *Branch = DAG->ExitSU.getInstr();
836 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
837 SUnit *SU = &DAG->SUnits[--Idx];
838 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
841 // Create a single weak edge from SU to ExitSU. The only effect is to cause
842 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
843 // need to copy predecessor edges from ExitSU to SU, since top-down
844 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
845 // of SU, we could create an artificial edge from the deepest root, but it
846 // hasn't been needed yet.
847 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
849 assert(Success && "No DAG nodes should be reachable from ExitSU");
851 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
856 //===----------------------------------------------------------------------===//
857 // ConvergingScheduler - Implementation of the standard MachineSchedStrategy.
858 //===----------------------------------------------------------------------===//
861 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
863 class ConvergingScheduler : public MachineSchedStrategy {
865 /// Represent the type of SchedCandidate found within a single queue.
866 /// pickNodeBidirectional depends on these listed by decreasing priority.
868 NoCand, SingleExcess, SingleCritical, Cluster,
869 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
870 TopDepthReduce, TopPathReduce, SingleMax, MultiPressure, NextDefUse,
874 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
877 /// Policy for scheduling the next instruction in the candidate's zone.
880 unsigned ReduceResIdx;
881 unsigned DemandResIdx;
883 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
886 /// Status of an instruction's critical resource consumption.
887 struct SchedResourceDelta {
888 // Count critical resources in the scheduled region required by SU.
889 unsigned CritResources;
891 // Count critical resources from another region consumed by SU.
892 unsigned DemandedResources;
894 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
896 bool operator==(const SchedResourceDelta &RHS) const {
897 return CritResources == RHS.CritResources
898 && DemandedResources == RHS.DemandedResources;
900 bool operator!=(const SchedResourceDelta &RHS) const {
901 return !operator==(RHS);
905 /// Store the state used by ConvergingScheduler heuristics, required for the
906 /// lifetime of one invocation of pickNode().
907 struct SchedCandidate {
910 // The best SUnit candidate.
913 // The reason for this candidate.
916 // Register pressure values for the best candidate.
917 RegPressureDelta RPDelta;
919 // Critical resource consumption of the best candidate.
920 SchedResourceDelta ResDelta;
922 SchedCandidate(const CandPolicy &policy)
923 : Policy(policy), SU(NULL), Reason(NoCand) {}
925 bool isValid() const { return SU; }
927 // Copy the status of another candidate without changing policy.
928 void setBest(SchedCandidate &Best) {
929 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
931 Reason = Best.Reason;
932 RPDelta = Best.RPDelta;
933 ResDelta = Best.ResDelta;
936 void initResourceDelta(const ScheduleDAGMI *DAG,
937 const TargetSchedModel *SchedModel);
940 /// Summarize the unscheduled region.
941 struct SchedRemainder {
942 // Critical path through the DAG in expected latency.
943 unsigned CriticalPath;
945 // Unscheduled resources
946 SmallVector<unsigned, 16> RemainingCounts;
947 // Critical resource for the unscheduled zone.
949 // Number of micro-ops left to schedule.
950 unsigned RemainingMicroOps;
954 RemainingCounts.clear();
956 RemainingMicroOps = 0;
959 SchedRemainder() { reset(); }
961 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
963 unsigned getMaxRemainingCount(const TargetSchedModel *SchedModel) const {
964 if (!SchedModel->hasInstrSchedModel())
968 RemainingMicroOps * SchedModel->getMicroOpFactor(),
969 RemainingCounts[CritResIdx]);
973 /// Each Scheduling boundary is associated with ready queues. It tracks the
974 /// current cycle in the direction of movement, and maintains the state
975 /// of "hazards" and other interlocks at the current cycle.
976 struct SchedBoundary {
978 const TargetSchedModel *SchedModel;
981 ReadyQueue Available;
985 // For heuristics, keep a list of the nodes that immediately depend on the
986 // most recently scheduled node.
987 SmallPtrSet<const SUnit*, 8> NextSUs;
989 ScheduleHazardRecognizer *HazardRec;
994 /// MinReadyCycle - Cycle of the soonest available instruction.
995 unsigned MinReadyCycle;
997 // The expected latency of the critical path in this scheduled zone.
998 unsigned ExpectedLatency;
1000 // Resources used in the scheduled zone beyond this boundary.
1001 SmallVector<unsigned, 16> ResourceCounts;
1003 // Cache the critical resources ID in this scheduled zone.
1004 unsigned CritResIdx;
1006 // Is the scheduled region resource limited vs. latency limited.
1007 bool IsResourceLimited;
1009 unsigned ExpectedCount;
1012 // Remember the greatest min operand latency.
1013 unsigned MaxMinLatency;
1019 CheckPending = false;
1024 MinReadyCycle = UINT_MAX;
1025 ExpectedLatency = 0;
1026 ResourceCounts.resize(1);
1027 assert(!ResourceCounts[0] && "nonzero count for bad resource");
1029 IsResourceLimited = false;
1034 // Reserve a zero-count for invalid CritResIdx.
1035 ResourceCounts.resize(1);
1038 /// Pending queues extend the ready queues with the same ID and the
1039 /// PendingFlag set.
1040 SchedBoundary(unsigned ID, const Twine &Name):
1041 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
1042 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P") {
1046 ~SchedBoundary() { delete HazardRec; }
1048 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1049 SchedRemainder *rem);
1051 bool isTop() const {
1052 return Available.getID() == ConvergingScheduler::TopQID;
1055 unsigned getUnscheduledLatency(SUnit *SU) const {
1057 return SU->getHeight();
1058 return SU->getDepth() + SU->Latency;
1061 unsigned getCriticalCount() const {
1062 return ResourceCounts[CritResIdx];
1065 bool checkHazard(SUnit *SU);
1067 void setLatencyPolicy(CandPolicy &Policy);
1069 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1073 void countResource(unsigned PIdx, unsigned Cycles);
1075 void bumpNode(SUnit *SU);
1077 void releasePending();
1079 void removeReady(SUnit *SU);
1081 SUnit *pickOnlyChoice();
1086 const TargetSchedModel *SchedModel;
1087 const TargetRegisterInfo *TRI;
1089 // State of the top and bottom scheduled instruction boundaries.
1095 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
1102 ConvergingScheduler():
1103 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
1105 virtual void initialize(ScheduleDAGMI *dag);
1107 virtual SUnit *pickNode(bool &IsTopNode);
1109 virtual void schedNode(SUnit *SU, bool IsTopNode);
1111 virtual void releaseTopNode(SUnit *SU);
1113 virtual void releaseBottomNode(SUnit *SU);
1115 virtual void registerRoots();
1119 ConvergingScheduler::SchedBoundary &CriticalZone,
1120 ConvergingScheduler::SchedCandidate &CriticalCand,
1121 ConvergingScheduler::SchedBoundary &OppositeZone,
1122 ConvergingScheduler::SchedCandidate &OppositeCand);
1124 void checkResourceLimits(ConvergingScheduler::SchedCandidate &TopCand,
1125 ConvergingScheduler::SchedCandidate &BotCand);
1127 void tryCandidate(SchedCandidate &Cand,
1128 SchedCandidate &TryCand,
1129 SchedBoundary &Zone,
1130 const RegPressureTracker &RPTracker,
1131 RegPressureTracker &TempTracker);
1133 SUnit *pickNodeBidirectional(bool &IsTopNode);
1135 void pickNodeFromQueue(SchedBoundary &Zone,
1136 const RegPressureTracker &RPTracker,
1137 SchedCandidate &Candidate);
1140 void traceCandidate(const SchedCandidate &Cand, const SchedBoundary &Zone);
1145 void ConvergingScheduler::SchedRemainder::
1146 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1148 if (!SchedModel->hasInstrSchedModel())
1150 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1151 for (std::vector<SUnit>::iterator
1152 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1153 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1154 RemainingMicroOps += SchedModel->getNumMicroOps(I->getInstr(), SC);
1155 for (TargetSchedModel::ProcResIter
1156 PI = SchedModel->getWriteProcResBegin(SC),
1157 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1158 unsigned PIdx = PI->ProcResourceIdx;
1159 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1160 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1163 for (unsigned PIdx = 0, PEnd = SchedModel->getNumProcResourceKinds();
1164 PIdx != PEnd; ++PIdx) {
1165 if ((int)(RemainingCounts[PIdx] - RemainingCounts[CritResIdx])
1166 >= (int)SchedModel->getLatencyFactor()) {
1172 void ConvergingScheduler::SchedBoundary::
1173 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1176 SchedModel = smodel;
1178 if (SchedModel->hasInstrSchedModel())
1179 ResourceCounts.resize(SchedModel->getNumProcResourceKinds());
1182 void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1184 SchedModel = DAG->getSchedModel();
1186 Rem.init(DAG, SchedModel);
1187 Top.init(DAG, SchedModel, &Rem);
1188 Bot.init(DAG, SchedModel, &Rem);
1190 // Initialize resource counts.
1192 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1193 // are disabled, then these HazardRecs will be disabled.
1194 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
1195 const TargetMachine &TM = DAG->MF.getTarget();
1196 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1197 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1199 assert((!ForceTopDown || !ForceBottomUp) &&
1200 "-misched-topdown incompatible with -misched-bottomup");
1203 void ConvergingScheduler::releaseTopNode(SUnit *SU) {
1204 if (SU->isScheduled)
1207 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1209 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1210 unsigned MinLatency = I->getMinLatency();
1212 Top.MaxMinLatency = std::max(MinLatency, Top.MaxMinLatency);
1214 if (SU->TopReadyCycle < PredReadyCycle + MinLatency)
1215 SU->TopReadyCycle = PredReadyCycle + MinLatency;
1217 Top.releaseNode(SU, SU->TopReadyCycle);
1220 void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
1221 if (SU->isScheduled)
1224 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1226 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1230 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1231 unsigned MinLatency = I->getMinLatency();
1233 Bot.MaxMinLatency = std::max(MinLatency, Bot.MaxMinLatency);
1235 if (SU->BotReadyCycle < SuccReadyCycle + MinLatency)
1236 SU->BotReadyCycle = SuccReadyCycle + MinLatency;
1238 Bot.releaseNode(SU, SU->BotReadyCycle);
1241 void ConvergingScheduler::registerRoots() {
1242 Rem.CriticalPath = DAG->ExitSU.getDepth();
1243 // Some roots may not feed into ExitSU. Check all of them in case.
1244 for (std::vector<SUnit*>::const_iterator
1245 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1246 if ((*I)->getDepth() > Rem.CriticalPath)
1247 Rem.CriticalPath = (*I)->getDepth();
1249 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1252 /// Does this SU have a hazard within the current instruction group.
1254 /// The scheduler supports two modes of hazard recognition. The first is the
1255 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1256 /// supports highly complicated in-order reservation tables
1257 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1259 /// The second is a streamlined mechanism that checks for hazards based on
1260 /// simple counters that the scheduler itself maintains. It explicitly checks
1261 /// for instruction dispatch limitations, including the number of micro-ops that
1262 /// can dispatch per cycle.
1264 /// TODO: Also check whether the SU must start a new group.
1265 bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1266 if (HazardRec->isEnabled())
1267 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1269 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1270 if ((IssueCount > 0) && (IssueCount + uops > SchedModel->getIssueWidth())) {
1271 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1272 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1278 /// Compute the remaining latency to determine whether ILP should be increased.
1279 void ConvergingScheduler::SchedBoundary::setLatencyPolicy(CandPolicy &Policy) {
1280 // FIXME: compile time. In all, we visit four queues here one we should only
1281 // need to visit the one that was last popped if we cache the result.
1282 unsigned RemLatency = 0;
1283 for (ReadyQueue::iterator I = Available.begin(), E = Available.end();
1285 unsigned L = getUnscheduledLatency(*I);
1289 for (ReadyQueue::iterator I = Pending.begin(), E = Pending.end();
1291 unsigned L = getUnscheduledLatency(*I);
1295 unsigned CriticalPathLimit = Rem->CriticalPath + SchedModel->getILPWindow();
1296 if (RemLatency + ExpectedLatency >= CriticalPathLimit
1297 && RemLatency > Rem->getMaxRemainingCount(SchedModel)) {
1298 Policy.ReduceLatency = true;
1299 DEBUG(dbgs() << "Increase ILP: " << Available.getName() << '\n');
1303 void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1304 unsigned ReadyCycle) {
1306 if (ReadyCycle < MinReadyCycle)
1307 MinReadyCycle = ReadyCycle;
1309 // Check for interlocks first. For the purpose of other heuristics, an
1310 // instruction that cannot issue appears as if it's not in the ReadyQueue.
1311 if (ReadyCycle > CurrCycle || checkHazard(SU))
1316 // Record this node as an immediate dependent of the scheduled node.
1320 /// Move the boundary of scheduled code by one cycle.
1321 void ConvergingScheduler::SchedBoundary::bumpCycle() {
1322 unsigned Width = SchedModel->getIssueWidth();
1323 IssueCount = (IssueCount <= Width) ? 0 : IssueCount - Width;
1325 unsigned NextCycle = CurrCycle + 1;
1326 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1327 if (MinReadyCycle > NextCycle) {
1329 NextCycle = MinReadyCycle;
1332 if (!HazardRec->isEnabled()) {
1333 // Bypass HazardRec virtual calls.
1334 CurrCycle = NextCycle;
1337 // Bypass getHazardType calls in case of long latency.
1338 for (; CurrCycle != NextCycle; ++CurrCycle) {
1340 HazardRec->AdvanceCycle();
1342 HazardRec->RecedeCycle();
1345 CheckPending = true;
1346 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1348 DEBUG(dbgs() << " *** " << Available.getName() << " cycle "
1349 << CurrCycle << '\n');
1352 /// Add the given processor resource to this scheduled zone.
1353 void ConvergingScheduler::SchedBoundary::countResource(unsigned PIdx,
1355 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1356 DEBUG(dbgs() << " " << SchedModel->getProcResource(PIdx)->Name
1357 << " +(" << Cycles << "x" << Factor
1358 << ") / " << SchedModel->getLatencyFactor() << '\n');
1360 unsigned Count = Factor * Cycles;
1361 ResourceCounts[PIdx] += Count;
1362 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1363 Rem->RemainingCounts[PIdx] -= Count;
1365 // Check if this resource exceeds the current critical resource by a full
1366 // cycle. If so, it becomes the critical resource.
1367 if ((int)(ResourceCounts[PIdx] - ResourceCounts[CritResIdx])
1368 >= (int)SchedModel->getLatencyFactor()) {
1370 DEBUG(dbgs() << " *** Critical resource "
1371 << SchedModel->getProcResource(PIdx)->Name << " x"
1372 << ResourceCounts[PIdx] << '\n');
1376 /// Move the boundary of scheduled code by one SUnit.
1377 void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
1378 // Update the reservation table.
1379 if (HazardRec->isEnabled()) {
1380 if (!isTop() && SU->isCall) {
1381 // Calls are scheduled with their preceding instructions. For bottom-up
1382 // scheduling, clear the pipeline state before emitting.
1385 HazardRec->EmitInstruction(SU);
1387 // Update resource counts and critical resource.
1388 if (SchedModel->hasInstrSchedModel()) {
1389 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1390 Rem->RemainingMicroOps -= SchedModel->getNumMicroOps(SU->getInstr(), SC);
1391 for (TargetSchedModel::ProcResIter
1392 PI = SchedModel->getWriteProcResBegin(SC),
1393 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1394 countResource(PI->ProcResourceIdx, PI->Cycles);
1398 if (SU->getDepth() > ExpectedLatency)
1399 ExpectedLatency = SU->getDepth();
1402 if (SU->getHeight() > ExpectedLatency)
1403 ExpectedLatency = SU->getHeight();
1406 IsResourceLimited = getCriticalCount() > std::max(ExpectedLatency, CurrCycle);
1408 // Check the instruction group dispatch limit.
1409 // TODO: Check if this SU must end a dispatch group.
1410 IssueCount += SchedModel->getNumMicroOps(SU->getInstr());
1412 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1413 // issue width. However, we commonly reach the maximum. In this case
1414 // opportunistically bump the cycle to avoid uselessly checking everything in
1415 // the readyQ. Furthermore, a single instruction may produce more than one
1416 // cycle's worth of micro-ops.
1417 if (IssueCount >= SchedModel->getIssueWidth()) {
1418 DEBUG(dbgs() << " *** Max instrs at cycle " << CurrCycle << '\n');
1423 /// Release pending ready nodes in to the available queue. This makes them
1424 /// visible to heuristics.
1425 void ConvergingScheduler::SchedBoundary::releasePending() {
1426 // If the available queue is empty, it is safe to reset MinReadyCycle.
1427 if (Available.empty())
1428 MinReadyCycle = UINT_MAX;
1430 // Check to see if any of the pending instructions are ready to issue. If
1431 // so, add them to the available queue.
1432 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
1433 SUnit *SU = *(Pending.begin()+i);
1434 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
1436 if (ReadyCycle < MinReadyCycle)
1437 MinReadyCycle = ReadyCycle;
1439 if (ReadyCycle > CurrCycle)
1442 if (checkHazard(SU))
1446 Pending.remove(Pending.begin()+i);
1449 DEBUG(if (!Pending.empty()) Pending.dump());
1450 CheckPending = false;
1453 /// Remove SU from the ready set for this boundary.
1454 void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
1455 if (Available.isInQueue(SU))
1456 Available.remove(Available.find(SU));
1458 assert(Pending.isInQueue(SU) && "bad ready count");
1459 Pending.remove(Pending.find(SU));
1463 /// If this queue only has one ready candidate, return it. As a side effect,
1464 /// defer any nodes that now hit a hazard, and advance the cycle until at least
1465 /// one node is ready. If multiple instructions are ready, return NULL.
1466 SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
1470 if (IssueCount > 0) {
1471 // Defer any ready instrs that now have a hazard.
1472 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
1473 if (checkHazard(*I)) {
1475 I = Available.remove(I);
1481 for (unsigned i = 0; Available.empty(); ++i) {
1482 assert(i <= (HazardRec->getMaxLookAhead() + MaxMinLatency) &&
1483 "permanent hazard"); (void)i;
1487 if (Available.size() == 1)
1488 return *Available.begin();
1492 /// Record the candidate policy for opposite zones with different critical
1495 /// If the CriticalZone is latency limited, don't force a policy for the
1496 /// candidates here. Instead, setLatencyPolicy sets ReduceLatency if needed.
1497 void ConvergingScheduler::balanceZones(
1498 ConvergingScheduler::SchedBoundary &CriticalZone,
1499 ConvergingScheduler::SchedCandidate &CriticalCand,
1500 ConvergingScheduler::SchedBoundary &OppositeZone,
1501 ConvergingScheduler::SchedCandidate &OppositeCand) {
1503 if (!CriticalZone.IsResourceLimited)
1505 assert(SchedModel->hasInstrSchedModel() && "required schedmodel");
1507 SchedRemainder *Rem = CriticalZone.Rem;
1509 // If the critical zone is overconsuming a resource relative to the
1510 // remainder, try to reduce it.
1511 unsigned RemainingCritCount =
1512 Rem->RemainingCounts[CriticalZone.CritResIdx];
1513 if ((int)(Rem->getMaxRemainingCount(SchedModel) - RemainingCritCount)
1514 > (int)SchedModel->getLatencyFactor()) {
1515 CriticalCand.Policy.ReduceResIdx = CriticalZone.CritResIdx;
1516 DEBUG(dbgs() << "Balance " << CriticalZone.Available.getName() << " reduce "
1517 << SchedModel->getProcResource(CriticalZone.CritResIdx)->Name
1520 // If the other zone is underconsuming a resource relative to the full zone,
1521 // try to increase it.
1522 unsigned OppositeCount =
1523 OppositeZone.ResourceCounts[CriticalZone.CritResIdx];
1524 if ((int)(OppositeZone.ExpectedCount - OppositeCount)
1525 > (int)SchedModel->getLatencyFactor()) {
1526 OppositeCand.Policy.DemandResIdx = CriticalZone.CritResIdx;
1527 DEBUG(dbgs() << "Balance " << OppositeZone.Available.getName() << " demand "
1528 << SchedModel->getProcResource(OppositeZone.CritResIdx)->Name
1533 /// Determine if the scheduled zones exceed resource limits or critical path and
1534 /// set each candidate's ReduceHeight policy accordingly.
1535 void ConvergingScheduler::checkResourceLimits(
1536 ConvergingScheduler::SchedCandidate &TopCand,
1537 ConvergingScheduler::SchedCandidate &BotCand) {
1539 // Set ReduceLatency to true if needed.
1540 Bot.setLatencyPolicy(BotCand.Policy);
1541 Top.setLatencyPolicy(TopCand.Policy);
1543 // Handle resource-limited regions.
1544 if (Top.IsResourceLimited && Bot.IsResourceLimited
1545 && Top.CritResIdx == Bot.CritResIdx) {
1546 // If the scheduled critical resource in both zones is no longer the
1547 // critical remaining resource, attempt to reduce resource height both ways.
1548 if (Top.CritResIdx != Rem.CritResIdx) {
1549 TopCand.Policy.ReduceResIdx = Top.CritResIdx;
1550 BotCand.Policy.ReduceResIdx = Bot.CritResIdx;
1551 DEBUG(dbgs() << "Reduce scheduled "
1552 << SchedModel->getProcResource(Top.CritResIdx)->Name << '\n');
1556 // Handle latency-limited regions.
1557 if (!Top.IsResourceLimited && !Bot.IsResourceLimited) {
1558 // If the total scheduled expected latency exceeds the region's critical
1559 // path then reduce latency both ways.
1561 // Just because a zone is not resource limited does not mean it is latency
1562 // limited. Unbuffered resource, such as max micro-ops may cause CurrCycle
1563 // to exceed expected latency.
1564 if ((Top.ExpectedLatency + Bot.ExpectedLatency >= Rem.CriticalPath)
1565 && (Rem.CriticalPath > Top.CurrCycle + Bot.CurrCycle)) {
1566 TopCand.Policy.ReduceLatency = true;
1567 BotCand.Policy.ReduceLatency = true;
1568 DEBUG(dbgs() << "Reduce scheduled latency " << Top.ExpectedLatency
1569 << " + " << Bot.ExpectedLatency << '\n');
1573 // The critical resource is different in each zone, so request balancing.
1575 // Compute the cost of each zone.
1576 Top.ExpectedCount = std::max(Top.ExpectedLatency, Top.CurrCycle);
1577 Top.ExpectedCount = std::max(
1578 Top.getCriticalCount(),
1579 Top.ExpectedCount * SchedModel->getLatencyFactor());
1580 Bot.ExpectedCount = std::max(Bot.ExpectedLatency, Bot.CurrCycle);
1581 Bot.ExpectedCount = std::max(
1582 Bot.getCriticalCount(),
1583 Bot.ExpectedCount * SchedModel->getLatencyFactor());
1585 balanceZones(Top, TopCand, Bot, BotCand);
1586 balanceZones(Bot, BotCand, Top, TopCand);
1589 void ConvergingScheduler::SchedCandidate::
1590 initResourceDelta(const ScheduleDAGMI *DAG,
1591 const TargetSchedModel *SchedModel) {
1592 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
1595 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1596 for (TargetSchedModel::ProcResIter
1597 PI = SchedModel->getWriteProcResBegin(SC),
1598 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1599 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
1600 ResDelta.CritResources += PI->Cycles;
1601 if (PI->ProcResourceIdx == Policy.DemandResIdx)
1602 ResDelta.DemandedResources += PI->Cycles;
1606 /// Return true if this heuristic determines order.
1607 static bool tryLess(unsigned TryVal, unsigned CandVal,
1608 ConvergingScheduler::SchedCandidate &TryCand,
1609 ConvergingScheduler::SchedCandidate &Cand,
1610 ConvergingScheduler::CandReason Reason) {
1611 if (TryVal < CandVal) {
1612 TryCand.Reason = Reason;
1615 if (TryVal > CandVal) {
1616 if (Cand.Reason > Reason)
1617 Cand.Reason = Reason;
1623 static bool tryGreater(unsigned TryVal, unsigned CandVal,
1624 ConvergingScheduler::SchedCandidate &TryCand,
1625 ConvergingScheduler::SchedCandidate &Cand,
1626 ConvergingScheduler::CandReason Reason) {
1627 if (TryVal > CandVal) {
1628 TryCand.Reason = Reason;
1631 if (TryVal < CandVal) {
1632 if (Cand.Reason > Reason)
1633 Cand.Reason = Reason;
1639 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
1640 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
1643 /// Apply a set of heursitics to a new candidate. Heuristics are currently
1644 /// hierarchical. This may be more efficient than a graduated cost model because
1645 /// we don't need to evaluate all aspects of the model for each node in the
1646 /// queue. But it's really done to make the heuristics easier to debug and
1647 /// statistically analyze.
1649 /// \param Cand provides the policy and current best candidate.
1650 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
1651 /// \param Zone describes the scheduled zone that we are extending.
1652 /// \param RPTracker describes reg pressure within the scheduled zone.
1653 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
1654 void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
1655 SchedCandidate &TryCand,
1656 SchedBoundary &Zone,
1657 const RegPressureTracker &RPTracker,
1658 RegPressureTracker &TempTracker) {
1660 // Always initialize TryCand's RPDelta.
1661 TempTracker.getMaxPressureDelta(TryCand.SU->getInstr(), TryCand.RPDelta,
1662 DAG->getRegionCriticalPSets(),
1663 DAG->getRegPressure().MaxSetPressure);
1665 // Initialize the candidate if needed.
1666 if (!Cand.isValid()) {
1667 TryCand.Reason = NodeOrder;
1670 // Avoid exceeding the target's limit.
1671 if (tryLess(TryCand.RPDelta.Excess.UnitIncrease,
1672 Cand.RPDelta.Excess.UnitIncrease, TryCand, Cand, SingleExcess))
1674 if (Cand.Reason == SingleExcess)
1675 Cand.Reason = MultiPressure;
1677 // Avoid increasing the max critical pressure in the scheduled region.
1678 if (tryLess(TryCand.RPDelta.CriticalMax.UnitIncrease,
1679 Cand.RPDelta.CriticalMax.UnitIncrease,
1680 TryCand, Cand, SingleCritical))
1682 if (Cand.Reason == SingleCritical)
1683 Cand.Reason = MultiPressure;
1685 // Keep clustered nodes together to encourage downstream peephole
1686 // optimizations which may reduce resource requirements.
1688 // This is a best effort to set things up for a post-RA pass. Optimizations
1689 // like generating loads of multiple registers should ideally be done within
1690 // the scheduler pass by combining the loads during DAG postprocessing.
1691 const SUnit *NextClusterSU =
1692 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
1693 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
1694 TryCand, Cand, Cluster))
1696 // Currently, weak edges are for clustering, so we hard-code that reason.
1697 // However, deferring the current TryCand will not change Cand's reason.
1698 CandReason OrigReason = Cand.Reason;
1699 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
1700 getWeakLeft(Cand.SU, Zone.isTop()),
1701 TryCand, Cand, Cluster)) {
1702 Cand.Reason = OrigReason;
1705 // Avoid critical resource consumption and balance the schedule.
1706 TryCand.initResourceDelta(DAG, SchedModel);
1707 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
1708 TryCand, Cand, ResourceReduce))
1710 if (tryGreater(TryCand.ResDelta.DemandedResources,
1711 Cand.ResDelta.DemandedResources,
1712 TryCand, Cand, ResourceDemand))
1715 // Avoid serializing long latency dependence chains.
1716 if (Cand.Policy.ReduceLatency) {
1718 if (Cand.SU->getDepth() * SchedModel->getLatencyFactor()
1719 > Zone.ExpectedCount) {
1720 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1721 TryCand, Cand, TopDepthReduce))
1724 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1725 TryCand, Cand, TopPathReduce))
1729 if (Cand.SU->getHeight() * SchedModel->getLatencyFactor()
1730 > Zone.ExpectedCount) {
1731 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
1732 TryCand, Cand, BotHeightReduce))
1735 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
1736 TryCand, Cand, BotPathReduce))
1741 // Avoid increasing the max pressure of the entire region.
1742 if (tryLess(TryCand.RPDelta.CurrentMax.UnitIncrease,
1743 Cand.RPDelta.CurrentMax.UnitIncrease, TryCand, Cand, SingleMax))
1745 if (Cand.Reason == SingleMax)
1746 Cand.Reason = MultiPressure;
1748 // Prefer immediate defs/users of the last scheduled instruction. This is a
1749 // nice pressure avoidance strategy that also conserves the processor's
1750 // register renaming resources and keeps the machine code readable.
1751 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
1752 TryCand, Cand, NextDefUse))
1755 // Fall through to original instruction order.
1756 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
1757 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
1758 TryCand.Reason = NodeOrder;
1762 /// pickNodeFromQueue helper that returns true if the LHS reg pressure effect is
1763 /// more desirable than RHS from scheduling standpoint.
1764 static bool compareRPDelta(const RegPressureDelta &LHS,
1765 const RegPressureDelta &RHS) {
1766 // Compare each component of pressure in decreasing order of importance
1767 // without checking if any are valid. Invalid PressureElements are assumed to
1768 // have UnitIncrease==0, so are neutral.
1770 // Avoid increasing the max critical pressure in the scheduled region.
1771 if (LHS.Excess.UnitIncrease != RHS.Excess.UnitIncrease) {
1772 DEBUG(dbgs() << "RP excess top - bot: "
1773 << (LHS.Excess.UnitIncrease - RHS.Excess.UnitIncrease) << '\n');
1774 return LHS.Excess.UnitIncrease < RHS.Excess.UnitIncrease;
1776 // Avoid increasing the max critical pressure in the scheduled region.
1777 if (LHS.CriticalMax.UnitIncrease != RHS.CriticalMax.UnitIncrease) {
1778 DEBUG(dbgs() << "RP critical top - bot: "
1779 << (LHS.CriticalMax.UnitIncrease - RHS.CriticalMax.UnitIncrease)
1781 return LHS.CriticalMax.UnitIncrease < RHS.CriticalMax.UnitIncrease;
1783 // Avoid increasing the max pressure of the entire region.
1784 if (LHS.CurrentMax.UnitIncrease != RHS.CurrentMax.UnitIncrease) {
1785 DEBUG(dbgs() << "RP current top - bot: "
1786 << (LHS.CurrentMax.UnitIncrease - RHS.CurrentMax.UnitIncrease)
1788 return LHS.CurrentMax.UnitIncrease < RHS.CurrentMax.UnitIncrease;
1794 const char *ConvergingScheduler::getReasonStr(
1795 ConvergingScheduler::CandReason Reason) {
1797 case NoCand: return "NOCAND ";
1798 case SingleExcess: return "REG-EXCESS";
1799 case SingleCritical: return "REG-CRIT ";
1800 case Cluster: return "CLUSTER ";
1801 case SingleMax: return "REG-MAX ";
1802 case MultiPressure: return "REG-MULTI ";
1803 case ResourceReduce: return "RES-REDUCE";
1804 case ResourceDemand: return "RES-DEMAND";
1805 case TopDepthReduce: return "TOP-DEPTH ";
1806 case TopPathReduce: return "TOP-PATH ";
1807 case BotHeightReduce:return "BOT-HEIGHT";
1808 case BotPathReduce: return "BOT-PATH ";
1809 case NextDefUse: return "DEF-USE ";
1810 case NodeOrder: return "ORDER ";
1812 llvm_unreachable("Unknown reason!");
1815 void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand,
1816 const SchedBoundary &Zone) {
1817 const char *Label = getReasonStr(Cand.Reason);
1819 unsigned ResIdx = 0;
1820 unsigned Latency = 0;
1821 switch (Cand.Reason) {
1825 P = Cand.RPDelta.Excess;
1827 case SingleCritical:
1828 P = Cand.RPDelta.CriticalMax;
1831 P = Cand.RPDelta.CurrentMax;
1833 case ResourceReduce:
1834 ResIdx = Cand.Policy.ReduceResIdx;
1836 case ResourceDemand:
1837 ResIdx = Cand.Policy.DemandResIdx;
1839 case TopDepthReduce:
1840 Latency = Cand.SU->getDepth();
1843 Latency = Cand.SU->getHeight();
1845 case BotHeightReduce:
1846 Latency = Cand.SU->getHeight();
1849 Latency = Cand.SU->getDepth();
1852 dbgs() << Label << " " << Zone.Available.getName() << " ";
1854 dbgs() << TRI->getRegPressureSetName(P.PSetID) << ":" << P.UnitIncrease
1859 dbgs() << SchedModel->getProcResource(ResIdx)->Name << " ";
1863 dbgs() << Latency << " cycles ";
1870 /// Pick the best candidate from the top queue.
1872 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
1873 /// DAG building. To adjust for the current scheduling location we need to
1874 /// maintain the number of vreg uses remaining to be top-scheduled.
1875 void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
1876 const RegPressureTracker &RPTracker,
1877 SchedCandidate &Cand) {
1878 ReadyQueue &Q = Zone.Available;
1882 // getMaxPressureDelta temporarily modifies the tracker.
1883 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
1885 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
1887 SchedCandidate TryCand(Cand.Policy);
1889 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
1890 if (TryCand.Reason != NoCand) {
1891 // Initialize resource delta if needed in case future heuristics query it.
1892 if (TryCand.ResDelta == SchedResourceDelta())
1893 TryCand.initResourceDelta(DAG, SchedModel);
1894 Cand.setBest(TryCand);
1895 DEBUG(traceCandidate(Cand, Zone));
1900 static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
1902 DEBUG(dbgs() << "Pick " << (IsTop ? "top" : "bot")
1903 << " SU(" << Cand.SU->NodeNum << ") "
1904 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
1907 /// Pick the best candidate node from either the top or bottom queue.
1908 SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
1909 // Schedule as far as possible in the direction of no choice. This is most
1910 // efficient, but also provides the best heuristics for CriticalPSets.
1911 if (SUnit *SU = Bot.pickOnlyChoice()) {
1915 if (SUnit *SU = Top.pickOnlyChoice()) {
1919 CandPolicy NoPolicy;
1920 SchedCandidate BotCand(NoPolicy);
1921 SchedCandidate TopCand(NoPolicy);
1922 checkResourceLimits(TopCand, BotCand);
1924 // Prefer bottom scheduling when heuristics are silent.
1925 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1926 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
1928 // If either Q has a single candidate that provides the least increase in
1929 // Excess pressure, we can immediately schedule from that Q.
1931 // RegionCriticalPSets summarizes the pressure within the scheduled region and
1932 // affects picking from either Q. If scheduling in one direction must
1933 // increase pressure for one of the excess PSets, then schedule in that
1934 // direction first to provide more freedom in the other direction.
1935 if (BotCand.Reason == SingleExcess || BotCand.Reason == SingleCritical) {
1937 tracePick(BotCand, IsTopNode);
1940 // Check if the top Q has a better candidate.
1941 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1942 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
1944 // If either Q has a single candidate that minimizes pressure above the
1945 // original region's pressure pick it.
1946 if (TopCand.Reason <= SingleMax || BotCand.Reason <= SingleMax) {
1947 if (TopCand.Reason < BotCand.Reason) {
1949 tracePick(TopCand, IsTopNode);
1953 tracePick(BotCand, IsTopNode);
1956 // Check for a salient pressure difference and pick the best from either side.
1957 if (compareRPDelta(TopCand.RPDelta, BotCand.RPDelta)) {
1959 tracePick(TopCand, IsTopNode);
1962 // Otherwise prefer the bottom candidate, in node order if all else failed.
1963 if (TopCand.Reason < BotCand.Reason) {
1965 tracePick(TopCand, IsTopNode);
1969 tracePick(BotCand, IsTopNode);
1973 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
1974 SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
1975 if (DAG->top() == DAG->bottom()) {
1976 assert(Top.Available.empty() && Top.Pending.empty() &&
1977 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
1983 SU = Top.pickOnlyChoice();
1985 CandPolicy NoPolicy;
1986 SchedCandidate TopCand(NoPolicy);
1987 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
1988 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
1993 else if (ForceBottomUp) {
1994 SU = Bot.pickOnlyChoice();
1996 CandPolicy NoPolicy;
1997 SchedCandidate BotCand(NoPolicy);
1998 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
1999 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2005 SU = pickNodeBidirectional(IsTopNode);
2007 } while (SU->isScheduled);
2009 if (SU->isTopReady())
2010 Top.removeReady(SU);
2011 if (SU->isBottomReady())
2012 Bot.removeReady(SU);
2014 DEBUG(dbgs() << "*** " << (IsTopNode ? "Top" : "Bottom")
2015 << " Scheduling Instruction in cycle "
2016 << (IsTopNode ? Top.CurrCycle : Bot.CurrCycle) << '\n';
2021 /// Update the scheduler's state after scheduling a node. This is the same node
2022 /// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
2023 /// it's state based on the current cycle before MachineSchedStrategy does.
2024 void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2026 SU->TopReadyCycle = Top.CurrCycle;
2030 SU->BotReadyCycle = Bot.CurrCycle;
2035 /// Create the standard converging machine scheduler. This will be used as the
2036 /// default scheduler if the target does not set a default.
2037 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
2038 assert((!ForceTopDown || !ForceBottomUp) &&
2039 "-misched-topdown incompatible with -misched-bottomup");
2040 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2041 // Register DAG post-processors.
2042 if (EnableLoadCluster)
2043 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
2044 if (EnableMacroFusion)
2045 DAG->addMutation(new MacroFusion(DAG->TII));
2048 static MachineSchedRegistry
2049 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2050 createConvergingSched);
2052 //===----------------------------------------------------------------------===//
2053 // ILP Scheduler. Currently for experimental analysis of heuristics.
2054 //===----------------------------------------------------------------------===//
2057 /// \brief Order nodes by the ILP metric.
2059 SchedDFSResult *DFSResult;
2060 BitVector *ScheduledTrees;
2063 ILPOrder(SchedDFSResult *dfs, BitVector *schedtrees, bool MaxILP)
2064 : DFSResult(dfs), ScheduledTrees(schedtrees), MaximizeILP(MaxILP) {}
2066 /// \brief Apply a less-than relation on node priority.
2068 /// (Return true if A comes after B in the Q.)
2069 bool operator()(const SUnit *A, const SUnit *B) const {
2070 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2071 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2072 if (SchedTreeA != SchedTreeB) {
2073 // Unscheduled trees have lower priority.
2074 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2075 return ScheduledTrees->test(SchedTreeB);
2077 // Trees with shallower connections have have lower priority.
2078 if (DFSResult->getSubtreeLevel(SchedTreeA)
2079 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2080 return DFSResult->getSubtreeLevel(SchedTreeA)
2081 < DFSResult->getSubtreeLevel(SchedTreeB);
2085 return DFSResult->getILP(A) < DFSResult->getILP(B);
2087 return DFSResult->getILP(A) > DFSResult->getILP(B);
2091 /// \brief Schedule based on the ILP metric.
2092 class ILPScheduler : public MachineSchedStrategy {
2093 /// In case all subtrees are eventually connected to a common root through
2094 /// data dependence (e.g. reduction), place an upper limit on their size.
2096 /// FIXME: A subtree limit is generally good, but in the situation commented
2097 /// above, where multiple similar subtrees feed a common root, we should
2098 /// only split at a point where the resulting subtrees will be balanced.
2099 /// (a motivating test case must be found).
2100 static const unsigned SubtreeLimit = 16;
2102 SchedDFSResult DFSResult;
2103 BitVector ScheduledTrees;
2106 std::vector<SUnit*> ReadyQ;
2108 ILPScheduler(bool MaximizeILP)
2109 : DFSResult(/*BottomUp=*/true, SubtreeLimit),
2110 Cmp(&DFSResult, &ScheduledTrees, MaximizeILP) {}
2112 virtual void initialize(ScheduleDAGMI *DAG) {
2115 DFSResult.resize(DAG->SUnits.size());
2116 ScheduledTrees.clear();
2119 virtual void registerRoots() {
2120 DFSResult.compute(ReadyQ);
2121 ScheduledTrees.resize(DFSResult.getNumSubtrees());
2122 // Restore the heap in ReadyQ with the updated DFS results.
2123 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2126 /// Implement MachineSchedStrategy interface.
2127 /// -----------------------------------------
2129 /// Callback to select the highest priority node from the ready Q.
2130 virtual SUnit *pickNode(bool &IsTopNode) {
2131 if (ReadyQ.empty()) return NULL;
2132 pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2133 SUnit *SU = ReadyQ.back();
2136 DEBUG(dbgs() << "*** Scheduling " << "SU(" << SU->NodeNum << "): "
2138 << " ILP: " << DFSResult.getILP(SU)
2139 << " Tree: " << DFSResult.getSubtreeID(SU) << " @"
2140 << DFSResult.getSubtreeLevel(DFSResult.getSubtreeID(SU))<< '\n');
2144 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2145 /// DFSResults, and resort the priority Q.
2146 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2147 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
2148 if (!ScheduledTrees.test(DFSResult.getSubtreeID(SU))) {
2149 ScheduledTrees.set(DFSResult.getSubtreeID(SU));
2150 DFSResult.scheduleTree(DFSResult.getSubtreeID(SU));
2151 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2155 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2157 virtual void releaseBottomNode(SUnit *SU) {
2158 ReadyQ.push_back(SU);
2159 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2164 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2165 return new ScheduleDAGMI(C, new ILPScheduler(true));
2167 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2168 return new ScheduleDAGMI(C, new ILPScheduler(false));
2170 static MachineSchedRegistry ILPMaxRegistry(
2171 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2172 static MachineSchedRegistry ILPMinRegistry(
2173 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2175 //===----------------------------------------------------------------------===//
2176 // Machine Instruction Shuffler for Correctness Testing
2177 //===----------------------------------------------------------------------===//
2181 /// Apply a less-than relation on the node order, which corresponds to the
2182 /// instruction order prior to scheduling. IsReverse implements greater-than.
2183 template<bool IsReverse>
2185 bool operator()(SUnit *A, SUnit *B) const {
2187 return A->NodeNum > B->NodeNum;
2189 return A->NodeNum < B->NodeNum;
2193 /// Reorder instructions as much as possible.
2194 class InstructionShuffler : public MachineSchedStrategy {
2198 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2199 // gives nodes with a higher number higher priority causing the latest
2200 // instructions to be scheduled first.
2201 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2203 // When scheduling bottom-up, use greater-than as the queue priority.
2204 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2207 InstructionShuffler(bool alternate, bool topdown)
2208 : IsAlternating(alternate), IsTopDown(topdown) {}
2210 virtual void initialize(ScheduleDAGMI *) {
2215 /// Implement MachineSchedStrategy interface.
2216 /// -----------------------------------------
2218 virtual SUnit *pickNode(bool &IsTopNode) {
2222 if (TopQ.empty()) return NULL;
2225 } while (SU->isScheduled);
2230 if (BottomQ.empty()) return NULL;
2233 } while (SU->isScheduled);
2237 IsTopDown = !IsTopDown;
2241 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2243 virtual void releaseTopNode(SUnit *SU) {
2246 virtual void releaseBottomNode(SUnit *SU) {
2252 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
2253 bool Alternate = !ForceTopDown && !ForceBottomUp;
2254 bool TopDown = !ForceBottomUp;
2255 assert((TopDown || !ForceTopDown) &&
2256 "-misched-topdown incompatible with -misched-bottomup");
2257 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
2259 static MachineSchedRegistry ShufflerRegistry(
2260 "shuffle", "Shuffle machine instructions alternating directions",
2261 createInstructionShuffler);