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> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
57 cl::desc("Enable cyclic critical path analysis."), cl::init(false));
59 static cl::opt<bool> EnableLoadCluster("misched-cluster", cl::Hidden,
60 cl::desc("Enable load clustering."), cl::init(true));
62 // Experimental heuristics
63 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
64 cl::desc("Enable scheduling for macro fusion."), cl::init(true));
66 static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
67 cl::desc("Verify machine instrs before and after machine scheduling"));
69 // DAG subtrees must have at least this many nodes.
70 static const unsigned MinSubtreeSize = 8;
72 //===----------------------------------------------------------------------===//
73 // Machine Instruction Scheduling Pass and Registry
74 //===----------------------------------------------------------------------===//
76 MachineSchedContext::MachineSchedContext():
77 MF(0), MLI(0), MDT(0), PassConfig(0), AA(0), LIS(0) {
78 RegClassInfo = new RegisterClassInfo();
81 MachineSchedContext::~MachineSchedContext() {
86 /// MachineScheduler runs after coalescing and before register allocation.
87 class MachineScheduler : public MachineSchedContext,
88 public MachineFunctionPass {
92 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
94 virtual void releaseMemory() {}
96 virtual bool runOnMachineFunction(MachineFunction&);
98 virtual void print(raw_ostream &O, const Module* = 0) const;
100 static char ID; // Class identification, replacement for typeinfo
104 char MachineScheduler::ID = 0;
106 char &llvm::MachineSchedulerID = MachineScheduler::ID;
108 INITIALIZE_PASS_BEGIN(MachineScheduler, "misched",
109 "Machine Instruction Scheduler", false, false)
110 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
111 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
112 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
113 INITIALIZE_PASS_END(MachineScheduler, "misched",
114 "Machine Instruction Scheduler", false, false)
116 MachineScheduler::MachineScheduler()
117 : MachineFunctionPass(ID) {
118 initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
121 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
122 AU.setPreservesCFG();
123 AU.addRequiredID(MachineDominatorsID);
124 AU.addRequired<MachineLoopInfo>();
125 AU.addRequired<AliasAnalysis>();
126 AU.addRequired<TargetPassConfig>();
127 AU.addRequired<SlotIndexes>();
128 AU.addPreserved<SlotIndexes>();
129 AU.addRequired<LiveIntervals>();
130 AU.addPreserved<LiveIntervals>();
131 MachineFunctionPass::getAnalysisUsage(AU);
134 MachinePassRegistry MachineSchedRegistry::Registry;
136 /// A dummy default scheduler factory indicates whether the scheduler
137 /// is overridden on the command line.
138 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
142 /// MachineSchedOpt allows command line selection of the scheduler.
143 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
144 RegisterPassParser<MachineSchedRegistry> >
145 MachineSchedOpt("misched",
146 cl::init(&useDefaultMachineSched), cl::Hidden,
147 cl::desc("Machine instruction scheduler to use"));
149 static MachineSchedRegistry
150 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
151 useDefaultMachineSched);
153 /// Forward declare the standard machine scheduler. This will be used as the
154 /// default scheduler if the target does not set a default.
155 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C);
158 /// Decrement this iterator until reaching the top or a non-debug instr.
159 static MachineBasicBlock::const_iterator
160 priorNonDebug(MachineBasicBlock::const_iterator I,
161 MachineBasicBlock::const_iterator Beg) {
162 assert(I != Beg && "reached the top of the region, cannot decrement");
164 if (!I->isDebugValue())
170 /// Non-const version.
171 static MachineBasicBlock::iterator
172 priorNonDebug(MachineBasicBlock::iterator I,
173 MachineBasicBlock::const_iterator Beg) {
174 return const_cast<MachineInstr*>(
175 &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg));
178 /// If this iterator is a debug value, increment until reaching the End or a
179 /// non-debug instruction.
180 static MachineBasicBlock::iterator
181 nextIfDebug(MachineBasicBlock::iterator I, MachineBasicBlock::iterator End) {
182 for(; I != End; ++I) {
183 if (!I->isDebugValue())
189 /// Top-level MachineScheduler pass driver.
191 /// Visit blocks in function order. Divide each block into scheduling regions
192 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
193 /// consistent with the DAG builder, which traverses the interior of the
194 /// scheduling regions bottom-up.
196 /// This design avoids exposing scheduling boundaries to the DAG builder,
197 /// simplifying the DAG builder's support for "special" target instructions.
198 /// At the same time the design allows target schedulers to operate across
199 /// scheduling boundaries, for example to bundle the boudary instructions
200 /// without reordering them. This creates complexity, because the target
201 /// scheduler must update the RegionBegin and RegionEnd positions cached by
202 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
203 /// design would be to split blocks at scheduling boundaries, but LLVM has a
204 /// general bias against block splitting purely for implementation simplicity.
205 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
206 DEBUG(dbgs() << "Before MISsched:\n"; mf.print(dbgs()));
208 // Initialize the context of the pass.
210 MLI = &getAnalysis<MachineLoopInfo>();
211 MDT = &getAnalysis<MachineDominatorTree>();
212 PassConfig = &getAnalysis<TargetPassConfig>();
213 AA = &getAnalysis<AliasAnalysis>();
215 LIS = &getAnalysis<LiveIntervals>();
216 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
218 if (VerifyScheduling) {
220 MF->verify(this, "Before machine scheduling.");
222 RegClassInfo->runOnMachineFunction(*MF);
224 // Select the scheduler, or set the default.
225 MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
226 if (Ctor == useDefaultMachineSched) {
227 // Get the default scheduler set by the target.
228 Ctor = MachineSchedRegistry::getDefault();
230 Ctor = createConvergingSched;
231 MachineSchedRegistry::setDefault(Ctor);
234 // Instantiate the selected scheduler.
235 OwningPtr<ScheduleDAGInstrs> Scheduler(Ctor(this));
237 // Visit all machine basic blocks.
239 // TODO: Visit blocks in global postorder or postorder within the bottom-up
240 // loop tree. Then we can optionally compute global RegPressure.
241 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
242 MBB != MBBEnd; ++MBB) {
244 Scheduler->startBlock(MBB);
246 // Break the block into scheduling regions [I, RegionEnd), and schedule each
247 // region as soon as it is discovered. RegionEnd points the scheduling
248 // boundary at the bottom of the region. The DAG does not include RegionEnd,
249 // but the region does (i.e. the next RegionEnd is above the previous
250 // RegionBegin). If the current block has no terminator then RegionEnd ==
251 // MBB->end() for the bottom region.
253 // The Scheduler may insert instructions during either schedule() or
254 // exitRegion(), even for empty regions. So the local iterators 'I' and
255 // 'RegionEnd' are invalid across these calls.
256 unsigned RemainingInstrs = MBB->size();
257 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
258 RegionEnd != MBB->begin(); RegionEnd = Scheduler->begin()) {
260 // Avoid decrementing RegionEnd for blocks with no terminator.
261 if (RegionEnd != MBB->end()
262 || TII->isSchedulingBoundary(llvm::prior(RegionEnd), MBB, *MF)) {
264 // Count the boundary instruction.
268 // The next region starts above the previous region. Look backward in the
269 // instruction stream until we find the nearest boundary.
270 unsigned NumRegionInstrs = 0;
271 MachineBasicBlock::iterator I = RegionEnd;
272 for(;I != MBB->begin(); --I, --RemainingInstrs, ++NumRegionInstrs) {
273 if (TII->isSchedulingBoundary(llvm::prior(I), MBB, *MF))
276 // Notify the scheduler of the region, even if we may skip scheduling
277 // it. Perhaps it still needs to be bundled.
278 Scheduler->enterRegion(MBB, I, RegionEnd, NumRegionInstrs);
280 // Skip empty scheduling regions (0 or 1 schedulable instructions).
281 if (I == RegionEnd || I == llvm::prior(RegionEnd)) {
282 // Close the current region. Bundle the terminator if needed.
283 // This invalidates 'RegionEnd' and 'I'.
284 Scheduler->exitRegion();
287 DEBUG(dbgs() << "********** MI Scheduling **********\n");
288 DEBUG(dbgs() << MF->getName()
289 << ":BB#" << MBB->getNumber() << " " << MBB->getName()
290 << "\n From: " << *I << " To: ";
291 if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
292 else dbgs() << "End";
293 dbgs() << " RegionInstrs: " << NumRegionInstrs
294 << " Remaining: " << RemainingInstrs << "\n");
296 // Schedule a region: possibly reorder instructions.
297 // This invalidates 'RegionEnd' and 'I'.
298 Scheduler->schedule();
300 // Close the current region.
301 Scheduler->exitRegion();
303 // Scheduling has invalidated the current iterator 'I'. Ask the
304 // scheduler for the top of it's scheduled region.
305 RegionEnd = Scheduler->begin();
307 assert(RemainingInstrs == 0 && "Instruction count mismatch!");
308 Scheduler->finishBlock();
310 Scheduler->finalizeSchedule();
312 if (VerifyScheduling)
313 MF->verify(this, "After machine scheduling.");
317 void MachineScheduler::print(raw_ostream &O, const Module* m) const {
321 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
322 void ReadyQueue::dump() {
323 dbgs() << Name << ": ";
324 for (unsigned i = 0, e = Queue.size(); i < e; ++i)
325 dbgs() << Queue[i]->NodeNum << " ";
330 //===----------------------------------------------------------------------===//
331 // ScheduleDAGMI - Base class for MachineInstr scheduling with LiveIntervals
333 //===----------------------------------------------------------------------===//
335 ScheduleDAGMI::~ScheduleDAGMI() {
337 DeleteContainerPointers(Mutations);
341 bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
342 return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
345 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
346 if (SuccSU != &ExitSU) {
347 // Do not use WillCreateCycle, it assumes SD scheduling.
348 // If Pred is reachable from Succ, then the edge creates a cycle.
349 if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
351 Topo.AddPred(SuccSU, PredDep.getSUnit());
353 SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
354 // Return true regardless of whether a new edge needed to be inserted.
358 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
359 /// NumPredsLeft reaches zero, release the successor node.
361 /// FIXME: Adjust SuccSU height based on MinLatency.
362 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
363 SUnit *SuccSU = SuccEdge->getSUnit();
365 if (SuccEdge->isWeak()) {
366 --SuccSU->WeakPredsLeft;
367 if (SuccEdge->isCluster())
368 NextClusterSucc = SuccSU;
372 if (SuccSU->NumPredsLeft == 0) {
373 dbgs() << "*** Scheduling failed! ***\n";
375 dbgs() << " has been released too many times!\n";
379 --SuccSU->NumPredsLeft;
380 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
381 SchedImpl->releaseTopNode(SuccSU);
384 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
385 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
386 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
388 releaseSucc(SU, &*I);
392 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
393 /// NumSuccsLeft reaches zero, release the predecessor node.
395 /// FIXME: Adjust PredSU height based on MinLatency.
396 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
397 SUnit *PredSU = PredEdge->getSUnit();
399 if (PredEdge->isWeak()) {
400 --PredSU->WeakSuccsLeft;
401 if (PredEdge->isCluster())
402 NextClusterPred = PredSU;
406 if (PredSU->NumSuccsLeft == 0) {
407 dbgs() << "*** Scheduling failed! ***\n";
409 dbgs() << " has been released too many times!\n";
413 --PredSU->NumSuccsLeft;
414 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
415 SchedImpl->releaseBottomNode(PredSU);
418 /// releasePredecessors - Call releasePred on each of SU's predecessors.
419 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
420 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
422 releasePred(SU, &*I);
426 /// This is normally called from the main scheduler loop but may also be invoked
427 /// by the scheduling strategy to perform additional code motion.
428 void ScheduleDAGMI::moveInstruction(MachineInstr *MI,
429 MachineBasicBlock::iterator InsertPos) {
430 // Advance RegionBegin if the first instruction moves down.
431 if (&*RegionBegin == MI)
434 // Update the instruction stream.
435 BB->splice(InsertPos, BB, MI);
437 // Update LiveIntervals
438 LIS->handleMove(MI, /*UpdateFlags=*/true);
440 // Recede RegionBegin if an instruction moves above the first.
441 if (RegionBegin == InsertPos)
445 bool ScheduleDAGMI::checkSchedLimit() {
447 if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
448 CurrentTop = CurrentBottom;
451 ++NumInstrsScheduled;
456 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
457 /// crossing a scheduling boundary. [begin, end) includes all instructions in
458 /// the region, including the boundary itself and single-instruction regions
459 /// that don't get scheduled.
460 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
461 MachineBasicBlock::iterator begin,
462 MachineBasicBlock::iterator end,
463 unsigned regioninstrs)
465 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
467 // For convenience remember the end of the liveness region.
469 (RegionEnd == bb->end()) ? RegionEnd : llvm::next(RegionEnd);
472 // Setup the register pressure trackers for the top scheduled top and bottom
473 // scheduled regions.
474 void ScheduleDAGMI::initRegPressure() {
475 TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin);
476 BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd);
478 // Close the RPTracker to finalize live ins.
479 RPTracker.closeRegion();
481 DEBUG(RPTracker.dump());
483 // Initialize the live ins and live outs.
484 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
485 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
487 // Close one end of the tracker so we can call
488 // getMaxUpward/DownwardPressureDelta before advancing across any
489 // instructions. This converts currently live regs into live ins/outs.
490 TopRPTracker.closeTop();
491 BotRPTracker.closeBottom();
493 BotRPTracker.initLiveThru(RPTracker);
494 if (!BotRPTracker.getLiveThru().empty()) {
495 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
496 DEBUG(dbgs() << "Live Thru: ";
497 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
500 // For each live out vreg reduce the pressure change associated with other
501 // uses of the same vreg below the live-out reaching def.
502 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
504 // Account for liveness generated by the region boundary.
505 if (LiveRegionEnd != RegionEnd) {
506 SmallVector<unsigned, 8> LiveUses;
507 BotRPTracker.recede(&LiveUses);
508 updatePressureDiffs(LiveUses);
511 assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
513 // Cache the list of excess pressure sets in this region. This will also track
514 // the max pressure in the scheduled code for these sets.
515 RegionCriticalPSets.clear();
516 const std::vector<unsigned> &RegionPressure =
517 RPTracker.getPressure().MaxSetPressure;
518 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
519 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
520 if (RegionPressure[i] > Limit) {
521 DEBUG(dbgs() << TRI->getRegPressureSetName(i)
522 << " Limit " << Limit
523 << " Actual " << RegionPressure[i] << "\n");
524 RegionCriticalPSets.push_back(PressureChange(i));
527 DEBUG(dbgs() << "Excess PSets: ";
528 for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
529 dbgs() << TRI->getRegPressureSetName(
530 RegionCriticalPSets[i].getPSet()) << " ";
534 // FIXME: When the pressure tracker deals in pressure differences then we won't
535 // iterate over all RegionCriticalPSets[i].
537 updateScheduledPressure(const std::vector<unsigned> &NewMaxPressure) {
538 for (unsigned i = 0, e = RegionCriticalPSets.size(); i < e; ++i) {
539 unsigned ID = RegionCriticalPSets[i].getPSet();
540 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[i].getUnitInc()
541 && NewMaxPressure[ID] <= INT16_MAX)
542 RegionCriticalPSets[i].setUnitInc(NewMaxPressure[ID]);
545 for (unsigned i = 0, e = NewMaxPressure.size(); i < e; ++i) {
546 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
547 if (NewMaxPressure[i] > Limit ) {
548 dbgs() << " " << TRI->getRegPressureSetName(i) << ": "
549 << NewMaxPressure[i] << " > " << Limit << "\n";
554 /// Update the PressureDiff array for liveness after scheduling this
556 void ScheduleDAGMI::updatePressureDiffs(ArrayRef<unsigned> LiveUses) {
557 for (unsigned LUIdx = 0, LUEnd = LiveUses.size(); LUIdx != LUEnd; ++LUIdx) {
558 /// FIXME: Currently assuming single-use physregs.
559 unsigned Reg = LiveUses[LUIdx];
560 if (!TRI->isVirtualRegister(Reg))
562 // This may be called before CurrentBottom has been initialized. However,
563 // BotRPTracker must have a valid position. We want the value live into the
564 // instruction or live out of the block, so ask for the previous
565 // instruction's live-out.
566 const LiveInterval &LI = LIS->getInterval(Reg);
568 if (BotRPTracker.getPos() == BB->end())
569 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
571 LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(BotRPTracker.getPos()));
574 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
575 assert(VNI && "No live value at use.");
576 for (VReg2UseMap::iterator
577 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
579 // If this use comes before the reaching def, it cannot be a last use, so
580 // descrease its pressure change.
581 if (!SU->isScheduled && SU != &ExitSU) {
582 LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(SU->getInstr()));
583 if (LRQ.valueIn() == VNI)
584 getPressureDiff(SU).addPressureChange(Reg, true, &MRI);
590 /// schedule - Called back from MachineScheduler::runOnMachineFunction
591 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
592 /// only includes instructions that have DAG nodes, not scheduling boundaries.
594 /// This is a skeletal driver, with all the functionality pushed into helpers,
595 /// so that it can be easilly extended by experimental schedulers. Generally,
596 /// implementing MachineSchedStrategy should be sufficient to implement a new
597 /// scheduling algorithm. However, if a scheduler further subclasses
598 /// ScheduleDAGMI then it will want to override this virtual method in order to
599 /// update any specialized state.
600 void ScheduleDAGMI::schedule() {
601 buildDAGWithRegPressure();
603 Topo.InitDAGTopologicalSorting();
607 SmallVector<SUnit*, 8> TopRoots, BotRoots;
608 findRootsAndBiasEdges(TopRoots, BotRoots);
610 // Initialize the strategy before modifying the DAG.
611 // This may initialize a DFSResult to be used for queue priority.
612 SchedImpl->initialize(this);
614 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
615 SUnits[su].dumpAll(this));
616 if (ViewMISchedDAGs) viewGraph();
618 // Initialize ready queues now that the DAG and priority data are finalized.
619 initQueues(TopRoots, BotRoots);
621 bool IsTopNode = false;
622 while (SUnit *SU = SchedImpl->pickNode(IsTopNode)) {
623 assert(!SU->isScheduled && "Node already scheduled");
624 if (!checkSchedLimit())
627 scheduleMI(SU, IsTopNode);
629 updateQueues(SU, IsTopNode);
631 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
636 unsigned BBNum = begin()->getParent()->getNumber();
637 dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
643 /// Build the DAG and setup three register pressure trackers.
644 void ScheduleDAGMI::buildDAGWithRegPressure() {
645 // Initialize the register pressure tracker used by buildSchedGraph.
646 RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
647 /*TrackUntiedDefs=*/true);
649 // Account for liveness generate by the region boundary.
650 if (LiveRegionEnd != RegionEnd)
653 // Build the DAG, and compute current register pressure.
654 buildSchedGraph(AA, &RPTracker, &SUPressureDiffs);
656 // Initialize top/bottom trackers after computing region pressure.
660 /// Apply each ScheduleDAGMutation step in order.
661 void ScheduleDAGMI::postprocessDAG() {
662 for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
663 Mutations[i]->apply(this);
667 void ScheduleDAGMI::computeDFSResult() {
669 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
671 ScheduledTrees.clear();
672 DFSResult->resize(SUnits.size());
673 DFSResult->compute(SUnits);
674 ScheduledTrees.resize(DFSResult->getNumSubtrees());
677 void ScheduleDAGMI::findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
678 SmallVectorImpl<SUnit*> &BotRoots) {
679 for (std::vector<SUnit>::iterator
680 I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
682 assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
684 // Order predecessors so DFSResult follows the critical path.
685 SU->biasCriticalPath();
687 // A SUnit is ready to top schedule if it has no predecessors.
688 if (!I->NumPredsLeft)
689 TopRoots.push_back(SU);
690 // A SUnit is ready to bottom schedule if it has no successors.
691 if (!I->NumSuccsLeft)
692 BotRoots.push_back(SU);
694 ExitSU.biasCriticalPath();
697 /// Compute the max cyclic critical path through the DAG. The scheduling DAG
698 /// only provides the critical path for single block loops. To handle loops that
699 /// span blocks, we could use the vreg path latencies provided by
700 /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
701 /// available for use in the scheduler.
703 /// The cyclic path estimation identifies a def-use pair that crosses the back
704 /// edge and considers the depth and height of the nodes. For example, consider
705 /// the following instruction sequence where each instruction has unit latency
706 /// and defines an epomymous virtual register:
708 /// a->b(a,c)->c(b)->d(c)->exit
710 /// The cyclic critical path is a two cycles: b->c->b
711 /// The acyclic critical path is four cycles: a->b->c->d->exit
712 /// LiveOutHeight = height(c) = len(c->d->exit) = 2
713 /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
714 /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
715 /// LiveInDepth = depth(b) = len(a->b) = 1
717 /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
718 /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
719 /// CyclicCriticalPath = min(2, 2) = 2
720 unsigned ScheduleDAGMI::computeCyclicCriticalPath() {
721 // This only applies to single block loop.
722 if (!BB->isSuccessor(BB))
725 unsigned MaxCyclicLatency = 0;
726 // Visit each live out vreg def to find def/use pairs that cross iterations.
727 ArrayRef<unsigned> LiveOuts = RPTracker.getPressure().LiveOutRegs;
728 for (ArrayRef<unsigned>::iterator RI = LiveOuts.begin(), RE = LiveOuts.end();
731 if (!TRI->isVirtualRegister(Reg))
733 const LiveInterval &LI = LIS->getInterval(Reg);
734 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
738 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
739 const SUnit *DefSU = getSUnit(DefMI);
743 unsigned LiveOutHeight = DefSU->getHeight();
744 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
745 // Visit all local users of the vreg def.
746 for (VReg2UseMap::iterator
747 UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
748 if (UI->SU == &ExitSU)
751 // Only consider uses of the phi.
752 LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(UI->SU->getInstr()));
753 if (!LRQ.valueIn()->isPHIDef())
756 // Assume that a path spanning two iterations is a cycle, which could
757 // overestimate in strange cases. This allows cyclic latency to be
758 // estimated as the minimum slack of the vreg's depth or height.
759 unsigned CyclicLatency = 0;
760 if (LiveOutDepth > UI->SU->getDepth())
761 CyclicLatency = LiveOutDepth - UI->SU->getDepth();
763 unsigned LiveInHeight = UI->SU->getHeight() + DefSU->Latency;
764 if (LiveInHeight > LiveOutHeight) {
765 if (LiveInHeight - LiveOutHeight < CyclicLatency)
766 CyclicLatency = LiveInHeight - LiveOutHeight;
771 DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
772 << UI->SU->NodeNum << ") = " << CyclicLatency << "c\n");
773 if (CyclicLatency > MaxCyclicLatency)
774 MaxCyclicLatency = CyclicLatency;
777 DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
778 return MaxCyclicLatency;
781 /// Identify DAG roots and setup scheduler queues.
782 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
783 ArrayRef<SUnit*> BotRoots) {
784 NextClusterSucc = NULL;
785 NextClusterPred = NULL;
787 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
789 // Nodes with unreleased weak edges can still be roots.
790 // Release top roots in forward order.
791 for (SmallVectorImpl<SUnit*>::const_iterator
792 I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
793 SchedImpl->releaseTopNode(*I);
795 // Release bottom roots in reverse order so the higher priority nodes appear
796 // first. This is more natural and slightly more efficient.
797 for (SmallVectorImpl<SUnit*>::const_reverse_iterator
798 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
799 SchedImpl->releaseBottomNode(*I);
802 releaseSuccessors(&EntrySU);
803 releasePredecessors(&ExitSU);
805 SchedImpl->registerRoots();
807 // Advance past initial DebugValues.
808 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
809 CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
810 TopRPTracker.setPos(CurrentTop);
812 CurrentBottom = RegionEnd;
815 /// Move an instruction and update register pressure.
816 void ScheduleDAGMI::scheduleMI(SUnit *SU, bool IsTopNode) {
817 // Move the instruction to its new location in the instruction stream.
818 MachineInstr *MI = SU->getInstr();
821 assert(SU->isTopReady() && "node still has unscheduled dependencies");
822 if (&*CurrentTop == MI)
823 CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
825 moveInstruction(MI, CurrentTop);
826 TopRPTracker.setPos(MI);
829 // Update top scheduled pressure.
830 TopRPTracker.advance();
831 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
832 updateScheduledPressure(TopRPTracker.getPressure().MaxSetPressure);
835 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
836 MachineBasicBlock::iterator priorII =
837 priorNonDebug(CurrentBottom, CurrentTop);
839 CurrentBottom = priorII;
841 if (&*CurrentTop == MI) {
842 CurrentTop = nextIfDebug(++CurrentTop, priorII);
843 TopRPTracker.setPos(CurrentTop);
845 moveInstruction(MI, CurrentBottom);
848 // Update bottom scheduled pressure.
849 SmallVector<unsigned, 8> LiveUses;
850 BotRPTracker.recede(&LiveUses);
851 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
852 updatePressureDiffs(LiveUses);
853 updateScheduledPressure(BotRPTracker.getPressure().MaxSetPressure);
857 /// Update scheduler queues after scheduling an instruction.
858 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
859 // Release dependent instructions for scheduling.
861 releaseSuccessors(SU);
863 releasePredecessors(SU);
865 SU->isScheduled = true;
868 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
869 if (!ScheduledTrees.test(SubtreeID)) {
870 ScheduledTrees.set(SubtreeID);
871 DFSResult->scheduleTree(SubtreeID);
872 SchedImpl->scheduleTree(SubtreeID);
876 // Notify the scheduling strategy after updating the DAG.
877 SchedImpl->schedNode(SU, IsTopNode);
880 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
881 void ScheduleDAGMI::placeDebugValues() {
882 // If first instruction was a DBG_VALUE then put it back.
884 BB->splice(RegionBegin, BB, FirstDbgValue);
885 RegionBegin = FirstDbgValue;
888 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
889 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
890 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
891 MachineInstr *DbgValue = P.first;
892 MachineBasicBlock::iterator OrigPrevMI = P.second;
893 if (&*RegionBegin == DbgValue)
895 BB->splice(++OrigPrevMI, BB, DbgValue);
896 if (OrigPrevMI == llvm::prior(RegionEnd))
897 RegionEnd = DbgValue;
900 FirstDbgValue = NULL;
903 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
904 void ScheduleDAGMI::dumpSchedule() const {
905 for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
906 if (SUnit *SU = getSUnit(&(*MI)))
909 dbgs() << "Missing SUnit\n";
914 //===----------------------------------------------------------------------===//
915 // LoadClusterMutation - DAG post-processing to cluster loads.
916 //===----------------------------------------------------------------------===//
919 /// \brief Post-process the DAG to create cluster edges between neighboring
921 class LoadClusterMutation : public ScheduleDAGMutation {
926 LoadInfo(SUnit *su, unsigned reg, unsigned ofs)
927 : SU(su), BaseReg(reg), Offset(ofs) {}
929 static bool LoadInfoLess(const LoadClusterMutation::LoadInfo &LHS,
930 const LoadClusterMutation::LoadInfo &RHS);
932 const TargetInstrInfo *TII;
933 const TargetRegisterInfo *TRI;
935 LoadClusterMutation(const TargetInstrInfo *tii,
936 const TargetRegisterInfo *tri)
937 : TII(tii), TRI(tri) {}
939 virtual void apply(ScheduleDAGMI *DAG);
941 void clusterNeighboringLoads(ArrayRef<SUnit*> Loads, ScheduleDAGMI *DAG);
945 bool LoadClusterMutation::LoadInfoLess(
946 const LoadClusterMutation::LoadInfo &LHS,
947 const LoadClusterMutation::LoadInfo &RHS) {
948 if (LHS.BaseReg != RHS.BaseReg)
949 return LHS.BaseReg < RHS.BaseReg;
950 return LHS.Offset < RHS.Offset;
953 void LoadClusterMutation::clusterNeighboringLoads(ArrayRef<SUnit*> Loads,
954 ScheduleDAGMI *DAG) {
955 SmallVector<LoadClusterMutation::LoadInfo,32> LoadRecords;
956 for (unsigned Idx = 0, End = Loads.size(); Idx != End; ++Idx) {
957 SUnit *SU = Loads[Idx];
960 if (TII->getLdStBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
961 LoadRecords.push_back(LoadInfo(SU, BaseReg, Offset));
963 if (LoadRecords.size() < 2)
965 std::sort(LoadRecords.begin(), LoadRecords.end(), LoadInfoLess);
966 unsigned ClusterLength = 1;
967 for (unsigned Idx = 0, End = LoadRecords.size(); Idx < (End - 1); ++Idx) {
968 if (LoadRecords[Idx].BaseReg != LoadRecords[Idx+1].BaseReg) {
973 SUnit *SUa = LoadRecords[Idx].SU;
974 SUnit *SUb = LoadRecords[Idx+1].SU;
975 if (TII->shouldClusterLoads(SUa->getInstr(), SUb->getInstr(), ClusterLength)
976 && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
978 DEBUG(dbgs() << "Cluster loads SU(" << SUa->NodeNum << ") - SU("
979 << SUb->NodeNum << ")\n");
980 // Copy successor edges from SUa to SUb. Interleaving computation
981 // dependent on SUa can prevent load combining due to register reuse.
982 // Predecessor edges do not need to be copied from SUb to SUa since nearby
983 // loads should have effectively the same inputs.
984 for (SUnit::const_succ_iterator
985 SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
986 if (SI->getSUnit() == SUb)
988 DEBUG(dbgs() << " Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
989 DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
998 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
999 void LoadClusterMutation::apply(ScheduleDAGMI *DAG) {
1000 // Map DAG NodeNum to store chain ID.
1001 DenseMap<unsigned, unsigned> StoreChainIDs;
1002 // Map each store chain to a set of dependent loads.
1003 SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1004 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1005 SUnit *SU = &DAG->SUnits[Idx];
1006 if (!SU->getInstr()->mayLoad())
1008 unsigned ChainPredID = DAG->SUnits.size();
1009 for (SUnit::const_pred_iterator
1010 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1012 ChainPredID = PI->getSUnit()->NodeNum;
1016 // Check if this chain-like pred has been seen
1017 // before. ChainPredID==MaxNodeID for loads at the top of the schedule.
1018 unsigned NumChains = StoreChainDependents.size();
1019 std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1020 StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1022 StoreChainDependents.resize(NumChains + 1);
1023 StoreChainDependents[Result.first->second].push_back(SU);
1025 // Iterate over the store chains.
1026 for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1027 clusterNeighboringLoads(StoreChainDependents[Idx], DAG);
1030 //===----------------------------------------------------------------------===//
1031 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
1032 //===----------------------------------------------------------------------===//
1035 /// \brief Post-process the DAG to create cluster edges between instructions
1036 /// that may be fused by the processor into a single operation.
1037 class MacroFusion : public ScheduleDAGMutation {
1038 const TargetInstrInfo *TII;
1040 MacroFusion(const TargetInstrInfo *tii): TII(tii) {}
1042 virtual void apply(ScheduleDAGMI *DAG);
1046 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
1047 /// fused operations.
1048 void MacroFusion::apply(ScheduleDAGMI *DAG) {
1049 // For now, assume targets can only fuse with the branch.
1050 MachineInstr *Branch = DAG->ExitSU.getInstr();
1054 for (unsigned Idx = DAG->SUnits.size(); Idx > 0;) {
1055 SUnit *SU = &DAG->SUnits[--Idx];
1056 if (!TII->shouldScheduleAdjacent(SU->getInstr(), Branch))
1059 // Create a single weak edge from SU to ExitSU. The only effect is to cause
1060 // bottom-up scheduling to heavily prioritize the clustered SU. There is no
1061 // need to copy predecessor edges from ExitSU to SU, since top-down
1062 // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1063 // of SU, we could create an artificial edge from the deepest root, but it
1064 // hasn't been needed yet.
1065 bool Success = DAG->addEdge(&DAG->ExitSU, SDep(SU, SDep::Cluster));
1067 assert(Success && "No DAG nodes should be reachable from ExitSU");
1069 DEBUG(dbgs() << "Macro Fuse SU(" << SU->NodeNum << ")\n");
1074 //===----------------------------------------------------------------------===//
1075 // CopyConstrain - DAG post-processing to encourage copy elimination.
1076 //===----------------------------------------------------------------------===//
1079 /// \brief Post-process the DAG to create weak edges from all uses of a copy to
1080 /// the one use that defines the copy's source vreg, most likely an induction
1081 /// variable increment.
1082 class CopyConstrain : public ScheduleDAGMutation {
1084 SlotIndex RegionBeginIdx;
1085 // RegionEndIdx is the slot index of the last non-debug instruction in the
1086 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
1087 SlotIndex RegionEndIdx;
1089 CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1091 virtual void apply(ScheduleDAGMI *DAG);
1094 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMI *DAG);
1098 /// constrainLocalCopy handles two possibilities:
1103 /// I3: dst = src (copy)
1104 /// (create pred->succ edges I0->I1, I2->I1)
1107 /// I0: dst = src (copy)
1111 /// (create pred->succ edges I1->I2, I3->I2)
1113 /// Although the MachineScheduler is currently constrained to single blocks,
1114 /// this algorithm should handle extended blocks. An EBB is a set of
1115 /// contiguously numbered blocks such that the previous block in the EBB is
1116 /// always the single predecessor.
1117 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMI *DAG) {
1118 LiveIntervals *LIS = DAG->getLIS();
1119 MachineInstr *Copy = CopySU->getInstr();
1121 // Check for pure vreg copies.
1122 unsigned SrcReg = Copy->getOperand(1).getReg();
1123 if (!TargetRegisterInfo::isVirtualRegister(SrcReg))
1126 unsigned DstReg = Copy->getOperand(0).getReg();
1127 if (!TargetRegisterInfo::isVirtualRegister(DstReg))
1130 // Check if either the dest or source is local. If it's live across a back
1131 // edge, it's not local. Note that if both vregs are live across the back
1132 // edge, we cannot successfully contrain the copy without cyclic scheduling.
1133 unsigned LocalReg = DstReg;
1134 unsigned GlobalReg = SrcReg;
1135 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1136 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1139 LocalLI = &LIS->getInterval(LocalReg);
1140 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1143 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1145 // Find the global segment after the start of the local LI.
1146 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1147 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1148 // local live range. We could create edges from other global uses to the local
1149 // start, but the coalescer should have already eliminated these cases, so
1150 // don't bother dealing with it.
1151 if (GlobalSegment == GlobalLI->end())
1154 // If GlobalSegment is killed at the LocalLI->start, the call to find()
1155 // returned the next global segment. But if GlobalSegment overlaps with
1156 // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1157 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1158 if (GlobalSegment->contains(LocalLI->beginIndex()))
1161 if (GlobalSegment == GlobalLI->end())
1164 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1165 if (GlobalSegment != GlobalLI->begin()) {
1166 // Two address defs have no hole.
1167 if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->end,
1168 GlobalSegment->start)) {
1171 // If the prior global segment may be defined by the same two-address
1172 // instruction that also defines LocalLI, then can't make a hole here.
1173 if (SlotIndex::isSameInstr(llvm::prior(GlobalSegment)->start,
1174 LocalLI->beginIndex())) {
1177 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1178 // it would be a disconnected component in the live range.
1179 assert(llvm::prior(GlobalSegment)->start < LocalLI->beginIndex() &&
1180 "Disconnected LRG within the scheduling region.");
1182 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1186 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1190 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1191 // constraining the uses of the last local def to precede GlobalDef.
1192 SmallVector<SUnit*,8> LocalUses;
1193 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1194 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1195 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1196 for (SUnit::const_succ_iterator
1197 I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1199 if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1201 if (I->getSUnit() == GlobalSU)
1203 if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1205 LocalUses.push_back(I->getSUnit());
1207 // Open the top of the GlobalLI hole by constraining any earlier global uses
1208 // to precede the start of LocalLI.
1209 SmallVector<SUnit*,8> GlobalUses;
1210 MachineInstr *FirstLocalDef =
1211 LIS->getInstructionFromIndex(LocalLI->beginIndex());
1212 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1213 for (SUnit::const_pred_iterator
1214 I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1215 if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1217 if (I->getSUnit() == FirstLocalSU)
1219 if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1221 GlobalUses.push_back(I->getSUnit());
1223 DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1224 // Add the weak edges.
1225 for (SmallVectorImpl<SUnit*>::const_iterator
1226 I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1227 DEBUG(dbgs() << " Local use SU(" << (*I)->NodeNum << ") -> SU("
1228 << GlobalSU->NodeNum << ")\n");
1229 DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1231 for (SmallVectorImpl<SUnit*>::const_iterator
1232 I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1233 DEBUG(dbgs() << " Global use SU(" << (*I)->NodeNum << ") -> SU("
1234 << FirstLocalSU->NodeNum << ")\n");
1235 DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1239 /// \brief Callback from DAG postProcessing to create weak edges to encourage
1240 /// copy elimination.
1241 void CopyConstrain::apply(ScheduleDAGMI *DAG) {
1242 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1243 if (FirstPos == DAG->end())
1245 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(&*FirstPos);
1246 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1247 &*priorNonDebug(DAG->end(), DAG->begin()));
1249 for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1250 SUnit *SU = &DAG->SUnits[Idx];
1251 if (!SU->getInstr()->isCopy())
1254 constrainLocalCopy(SU, DAG);
1258 //===----------------------------------------------------------------------===//
1259 // ConvergingScheduler - Implementation of the generic MachineSchedStrategy.
1260 //===----------------------------------------------------------------------===//
1263 /// ConvergingScheduler shrinks the unscheduled zone using heuristics to balance
1265 class ConvergingScheduler : public MachineSchedStrategy {
1267 /// Represent the type of SchedCandidate found within a single queue.
1268 /// pickNodeBidirectional depends on these listed by decreasing priority.
1270 NoCand, PhysRegCopy, RegExcess, RegCritical, Cluster, Weak, RegMax,
1271 ResourceReduce, ResourceDemand, BotHeightReduce, BotPathReduce,
1272 TopDepthReduce, TopPathReduce, NextDefUse, NodeOrder};
1275 static const char *getReasonStr(ConvergingScheduler::CandReason Reason);
1278 /// Policy for scheduling the next instruction in the candidate's zone.
1281 unsigned ReduceResIdx;
1282 unsigned DemandResIdx;
1284 CandPolicy(): ReduceLatency(false), ReduceResIdx(0), DemandResIdx(0) {}
1287 /// Status of an instruction's critical resource consumption.
1288 struct SchedResourceDelta {
1289 // Count critical resources in the scheduled region required by SU.
1290 unsigned CritResources;
1292 // Count critical resources from another region consumed by SU.
1293 unsigned DemandedResources;
1295 SchedResourceDelta(): CritResources(0), DemandedResources(0) {}
1297 bool operator==(const SchedResourceDelta &RHS) const {
1298 return CritResources == RHS.CritResources
1299 && DemandedResources == RHS.DemandedResources;
1301 bool operator!=(const SchedResourceDelta &RHS) const {
1302 return !operator==(RHS);
1306 /// Store the state used by ConvergingScheduler heuristics, required for the
1307 /// lifetime of one invocation of pickNode().
1308 struct SchedCandidate {
1311 // The best SUnit candidate.
1314 // The reason for this candidate.
1317 // Set of reasons that apply to multiple candidates.
1318 uint32_t RepeatReasonSet;
1320 // Register pressure values for the best candidate.
1321 RegPressureDelta RPDelta;
1323 // Critical resource consumption of the best candidate.
1324 SchedResourceDelta ResDelta;
1326 SchedCandidate(const CandPolicy &policy)
1327 : Policy(policy), SU(NULL), Reason(NoCand), RepeatReasonSet(0) {}
1329 bool isValid() const { return SU; }
1331 // Copy the status of another candidate without changing policy.
1332 void setBest(SchedCandidate &Best) {
1333 assert(Best.Reason != NoCand && "uninitialized Sched candidate");
1335 Reason = Best.Reason;
1336 RPDelta = Best.RPDelta;
1337 ResDelta = Best.ResDelta;
1340 bool isRepeat(CandReason R) { return RepeatReasonSet & (1 << R); }
1341 void setRepeat(CandReason R) { RepeatReasonSet |= (1 << R); }
1343 void initResourceDelta(const ScheduleDAGMI *DAG,
1344 const TargetSchedModel *SchedModel);
1347 /// Summarize the unscheduled region.
1348 struct SchedRemainder {
1349 // Critical path through the DAG in expected latency.
1350 unsigned CriticalPath;
1351 unsigned CyclicCritPath;
1353 // Scaled count of micro-ops left to schedule.
1354 unsigned RemIssueCount;
1356 bool IsAcyclicLatencyLimited;
1358 // Unscheduled resources
1359 SmallVector<unsigned, 16> RemainingCounts;
1365 IsAcyclicLatencyLimited = false;
1366 RemainingCounts.clear();
1369 SchedRemainder() { reset(); }
1371 void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel);
1374 /// Each Scheduling boundary is associated with ready queues. It tracks the
1375 /// current cycle in the direction of movement, and maintains the state
1376 /// of "hazards" and other interlocks at the current cycle.
1377 struct SchedBoundary {
1379 const TargetSchedModel *SchedModel;
1380 SchedRemainder *Rem;
1382 ReadyQueue Available;
1386 // For heuristics, keep a list of the nodes that immediately depend on the
1387 // most recently scheduled node.
1388 SmallPtrSet<const SUnit*, 8> NextSUs;
1390 ScheduleHazardRecognizer *HazardRec;
1392 /// Number of cycles it takes to issue the instructions scheduled in this
1393 /// zone. It is defined as: scheduled-micro-ops / issue-width + stalls.
1394 /// See getStalls().
1397 /// Micro-ops issued in the current cycle
1400 /// MinReadyCycle - Cycle of the soonest available instruction.
1401 unsigned MinReadyCycle;
1403 // The expected latency of the critical path in this scheduled zone.
1404 unsigned ExpectedLatency;
1406 // The latency of dependence chains leading into this zone.
1407 // For each node scheduled bottom-up: DLat = max DLat, N.Depth.
1408 // For each cycle scheduled: DLat -= 1.
1409 unsigned DependentLatency;
1411 /// Count the scheduled (issued) micro-ops that can be retired by
1412 /// time=CurrCycle assuming the first scheduled instr is retired at time=0.
1413 unsigned RetiredMOps;
1415 // Count scheduled resources that have been executed. Resources are
1416 // considered executed if they become ready in the time that it takes to
1417 // saturate any resource including the one in question. Counts are scaled
1418 // for direct comparison with other resources. Counts can be compared with
1419 // MOps * getMicroOpFactor and Latency * getLatencyFactor.
1420 SmallVector<unsigned, 16> ExecutedResCounts;
1422 /// Cache the max count for a single resource.
1423 unsigned MaxExecutedResCount;
1425 // Cache the critical resources ID in this scheduled zone.
1426 unsigned ZoneCritResIdx;
1428 // Is the scheduled region resource limited vs. latency limited.
1429 bool IsResourceLimited;
1432 // Remember the greatest operand latency as an upper bound on the number of
1433 // times we should retry the pending queue because of a hazard.
1434 unsigned MaxObservedLatency;
1438 // A new HazardRec is created for each DAG and owned by SchedBoundary.
1443 CheckPending = false;
1448 MinReadyCycle = UINT_MAX;
1449 ExpectedLatency = 0;
1450 DependentLatency = 0;
1452 MaxExecutedResCount = 0;
1454 IsResourceLimited = false;
1456 MaxObservedLatency = 0;
1458 // Reserve a zero-count for invalid CritResIdx.
1459 ExecutedResCounts.resize(1);
1460 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1463 /// Pending queues extend the ready queues with the same ID and the
1464 /// PendingFlag set.
1465 SchedBoundary(unsigned ID, const Twine &Name):
1466 DAG(0), SchedModel(0), Rem(0), Available(ID, Name+".A"),
1467 Pending(ID << ConvergingScheduler::LogMaxQID, Name+".P"),
1472 ~SchedBoundary() { delete HazardRec; }
1474 void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel,
1475 SchedRemainder *rem);
1477 bool isTop() const {
1478 return Available.getID() == ConvergingScheduler::TopQID;
1482 const char *getResourceName(unsigned PIdx) {
1485 return SchedModel->getProcResource(PIdx)->Name;
1489 /// Get the number of latency cycles "covered" by the scheduled
1490 /// instructions. This is the larger of the critical path within the zone
1491 /// and the number of cycles required to issue the instructions.
1492 unsigned getScheduledLatency() const {
1493 return std::max(ExpectedLatency, CurrCycle);
1496 unsigned getUnscheduledLatency(SUnit *SU) const {
1497 return isTop() ? SU->getHeight() : SU->getDepth();
1500 unsigned getResourceCount(unsigned ResIdx) const {
1501 return ExecutedResCounts[ResIdx];
1504 /// Get the scaled count of scheduled micro-ops and resources, including
1505 /// executed resources.
1506 unsigned getCriticalCount() const {
1507 if (!ZoneCritResIdx)
1508 return RetiredMOps * SchedModel->getMicroOpFactor();
1509 return getResourceCount(ZoneCritResIdx);
1512 /// Get a scaled count for the minimum execution time of the scheduled
1513 /// micro-ops that are ready to execute by getExecutedCount. Notice the
1515 unsigned getExecutedCount() const {
1516 return std::max(CurrCycle * SchedModel->getLatencyFactor(),
1517 MaxExecutedResCount);
1520 bool checkHazard(SUnit *SU);
1522 unsigned findMaxLatency(ArrayRef<SUnit*> ReadySUs);
1524 unsigned getOtherResourceCount(unsigned &OtherCritIdx);
1526 void setPolicy(CandPolicy &Policy, SchedBoundary &OtherZone);
1528 void releaseNode(SUnit *SU, unsigned ReadyCycle);
1530 void bumpCycle(unsigned NextCycle);
1532 void incExecutedResources(unsigned PIdx, unsigned Count);
1534 unsigned countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle);
1536 void bumpNode(SUnit *SU);
1538 void releasePending();
1540 void removeReady(SUnit *SU);
1542 SUnit *pickOnlyChoice();
1545 void dumpScheduledState();
1551 const TargetSchedModel *SchedModel;
1552 const TargetRegisterInfo *TRI;
1554 // State of the top and bottom scheduled instruction boundaries.
1560 /// SUnit::NodeQueueId: 0 (none), 1 (top), 2 (bot), 3 (both)
1567 ConvergingScheduler():
1568 DAG(0), SchedModel(0), TRI(0), Top(TopQID, "TopQ"), Bot(BotQID, "BotQ") {}
1570 virtual void initialize(ScheduleDAGMI *dag);
1572 virtual SUnit *pickNode(bool &IsTopNode);
1574 virtual void schedNode(SUnit *SU, bool IsTopNode);
1576 virtual void releaseTopNode(SUnit *SU);
1578 virtual void releaseBottomNode(SUnit *SU);
1580 virtual void registerRoots();
1583 void checkAcyclicLatency();
1585 void tryCandidate(SchedCandidate &Cand,
1586 SchedCandidate &TryCand,
1587 SchedBoundary &Zone,
1588 const RegPressureTracker &RPTracker,
1589 RegPressureTracker &TempTracker);
1591 SUnit *pickNodeBidirectional(bool &IsTopNode);
1593 void pickNodeFromQueue(SchedBoundary &Zone,
1594 const RegPressureTracker &RPTracker,
1595 SchedCandidate &Candidate);
1597 void reschedulePhysRegCopies(SUnit *SU, bool isTop);
1600 void traceCandidate(const SchedCandidate &Cand);
1605 void ConvergingScheduler::SchedRemainder::
1606 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1608 if (!SchedModel->hasInstrSchedModel())
1610 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1611 for (std::vector<SUnit>::iterator
1612 I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1613 const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1614 RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1615 * SchedModel->getMicroOpFactor();
1616 for (TargetSchedModel::ProcResIter
1617 PI = SchedModel->getWriteProcResBegin(SC),
1618 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1619 unsigned PIdx = PI->ProcResourceIdx;
1620 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1621 RemainingCounts[PIdx] += (Factor * PI->Cycles);
1626 void ConvergingScheduler::SchedBoundary::
1627 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1630 SchedModel = smodel;
1632 if (SchedModel->hasInstrSchedModel())
1633 ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
1636 void ConvergingScheduler::initialize(ScheduleDAGMI *dag) {
1638 SchedModel = DAG->getSchedModel();
1641 Rem.init(DAG, SchedModel);
1642 Top.init(DAG, SchedModel, &Rem);
1643 Bot.init(DAG, SchedModel, &Rem);
1645 // Initialize resource counts.
1647 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
1648 // are disabled, then these HazardRecs will be disabled.
1649 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
1650 const TargetMachine &TM = DAG->MF.getTarget();
1651 Top.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1652 Bot.HazardRec = TM.getInstrInfo()->CreateTargetMIHazardRecognizer(Itin, DAG);
1654 assert((!ForceTopDown || !ForceBottomUp) &&
1655 "-misched-topdown incompatible with -misched-bottomup");
1658 void ConvergingScheduler::releaseTopNode(SUnit *SU) {
1659 if (SU->isScheduled)
1662 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1666 unsigned PredReadyCycle = I->getSUnit()->TopReadyCycle;
1667 unsigned Latency = I->getLatency();
1669 Top.MaxObservedLatency = std::max(Latency, Top.MaxObservedLatency);
1671 if (SU->TopReadyCycle < PredReadyCycle + Latency)
1672 SU->TopReadyCycle = PredReadyCycle + Latency;
1674 Top.releaseNode(SU, SU->TopReadyCycle);
1677 void ConvergingScheduler::releaseBottomNode(SUnit *SU) {
1678 if (SU->isScheduled)
1681 assert(SU->getInstr() && "Scheduled SUnit must have instr");
1683 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1687 unsigned SuccReadyCycle = I->getSUnit()->BotReadyCycle;
1688 unsigned Latency = I->getLatency();
1690 Bot.MaxObservedLatency = std::max(Latency, Bot.MaxObservedLatency);
1692 if (SU->BotReadyCycle < SuccReadyCycle + Latency)
1693 SU->BotReadyCycle = SuccReadyCycle + Latency;
1695 Bot.releaseNode(SU, SU->BotReadyCycle);
1698 /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
1699 /// critical path by more cycles than it takes to drain the instruction buffer.
1700 /// We estimate an upper bounds on in-flight instructions as:
1702 /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
1703 /// InFlightIterations = AcyclicPath / CyclesPerIteration
1704 /// InFlightResources = InFlightIterations * LoopResources
1706 /// TODO: Check execution resources in addition to IssueCount.
1707 void ConvergingScheduler::checkAcyclicLatency() {
1708 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
1711 // Scaled number of cycles per loop iteration.
1712 unsigned IterCount =
1713 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
1715 // Scaled acyclic critical path.
1716 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
1717 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
1718 unsigned InFlightCount =
1719 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
1720 unsigned BufferLimit =
1721 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
1723 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
1725 DEBUG(dbgs() << "IssueCycles="
1726 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
1727 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
1728 << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
1729 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
1730 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
1731 if (Rem.IsAcyclicLatencyLimited)
1732 dbgs() << " ACYCLIC LATENCY LIMIT\n");
1735 void ConvergingScheduler::registerRoots() {
1736 Rem.CriticalPath = DAG->ExitSU.getDepth();
1738 // Some roots may not feed into ExitSU. Check all of them in case.
1739 for (std::vector<SUnit*>::const_iterator
1740 I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
1741 if ((*I)->getDepth() > Rem.CriticalPath)
1742 Rem.CriticalPath = (*I)->getDepth();
1744 DEBUG(dbgs() << "Critical Path: " << Rem.CriticalPath << '\n');
1746 if (EnableCyclicPath) {
1747 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
1748 checkAcyclicLatency();
1752 /// Does this SU have a hazard within the current instruction group.
1754 /// The scheduler supports two modes of hazard recognition. The first is the
1755 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1756 /// supports highly complicated in-order reservation tables
1757 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1759 /// The second is a streamlined mechanism that checks for hazards based on
1760 /// simple counters that the scheduler itself maintains. It explicitly checks
1761 /// for instruction dispatch limitations, including the number of micro-ops that
1762 /// can dispatch per cycle.
1764 /// TODO: Also check whether the SU must start a new group.
1765 bool ConvergingScheduler::SchedBoundary::checkHazard(SUnit *SU) {
1766 if (HazardRec->isEnabled())
1767 return HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard;
1769 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1770 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
1771 DEBUG(dbgs() << " SU(" << SU->NodeNum << ") uops="
1772 << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1778 // Find the unscheduled node in ReadySUs with the highest latency.
1779 unsigned ConvergingScheduler::SchedBoundary::
1780 findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1782 unsigned RemLatency = 0;
1783 for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
1785 unsigned L = getUnscheduledLatency(*I);
1786 if (L > RemLatency) {
1792 DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1793 << LateSU->NodeNum << ") " << RemLatency << "c\n");
1798 // Count resources in this zone and the remaining unscheduled
1799 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1800 // resource index, or zero if the zone is issue limited.
1801 unsigned ConvergingScheduler::SchedBoundary::
1802 getOtherResourceCount(unsigned &OtherCritIdx) {
1804 if (!SchedModel->hasInstrSchedModel())
1807 unsigned OtherCritCount = Rem->RemIssueCount
1808 + (RetiredMOps * SchedModel->getMicroOpFactor());
1809 DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
1810 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
1811 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1812 PIdx != PEnd; ++PIdx) {
1813 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1814 if (OtherCount > OtherCritCount) {
1815 OtherCritCount = OtherCount;
1816 OtherCritIdx = PIdx;
1820 DEBUG(dbgs() << " " << Available.getName() << " + Remain CritRes: "
1821 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1822 << " " << getResourceName(OtherCritIdx) << "\n");
1824 return OtherCritCount;
1827 /// Set the CandPolicy for this zone given the current resources and latencies
1828 /// inside and outside the zone.
1829 void ConvergingScheduler::SchedBoundary::setPolicy(CandPolicy &Policy,
1830 SchedBoundary &OtherZone) {
1831 // Now that potential stalls have been considered, apply preemptive heuristics
1832 // based on the the total latency and resources inside and outside this
1835 // Compute remaining latency. We need this both to determine whether the
1836 // overall schedule has become latency-limited and whether the instructions
1837 // outside this zone are resource or latency limited.
1839 // The "dependent" latency is updated incrementally during scheduling as the
1840 // max height/depth of scheduled nodes minus the cycles since it was
1842 // DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
1844 // The "independent" latency is the max ready queue depth:
1845 // ILat = max N.depth for N in Available|Pending
1847 // RemainingLatency is the greater of independent and dependent latency.
1848 unsigned RemLatency = DependentLatency;
1849 RemLatency = std::max(RemLatency, findMaxLatency(Available.elements()));
1850 RemLatency = std::max(RemLatency, findMaxLatency(Pending.elements()));
1852 // Compute the critical resource outside the zone.
1853 unsigned OtherCritIdx;
1854 unsigned OtherCount = OtherZone.getOtherResourceCount(OtherCritIdx);
1856 bool OtherResLimited = false;
1857 if (SchedModel->hasInstrSchedModel()) {
1858 unsigned LFactor = SchedModel->getLatencyFactor();
1859 OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
1861 if (!OtherResLimited && (RemLatency + CurrCycle > Rem->CriticalPath)) {
1862 Policy.ReduceLatency |= true;
1863 DEBUG(dbgs() << " " << Available.getName() << " RemainingLatency "
1864 << RemLatency << " + " << CurrCycle << "c > CritPath "
1865 << Rem->CriticalPath << "\n");
1867 // If the same resource is limiting inside and outside the zone, do nothing.
1868 if (ZoneCritResIdx == OtherCritIdx)
1872 if (IsResourceLimited) {
1873 dbgs() << " " << Available.getName() << " ResourceLimited: "
1874 << getResourceName(ZoneCritResIdx) << "\n";
1876 if (OtherResLimited)
1877 dbgs() << " RemainingLimit: " << getResourceName(OtherCritIdx) << "\n";
1878 if (!IsResourceLimited && !OtherResLimited)
1879 dbgs() << " Latency limited both directions.\n");
1881 if (IsResourceLimited && !Policy.ReduceResIdx)
1882 Policy.ReduceResIdx = ZoneCritResIdx;
1884 if (OtherResLimited)
1885 Policy.DemandResIdx = OtherCritIdx;
1888 void ConvergingScheduler::SchedBoundary::releaseNode(SUnit *SU,
1889 unsigned ReadyCycle) {
1890 if (ReadyCycle < MinReadyCycle)
1891 MinReadyCycle = ReadyCycle;
1893 // Check for interlocks first. For the purpose of other heuristics, an
1894 // instruction that cannot issue appears as if it's not in the ReadyQueue.
1895 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1896 if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU))
1901 // Record this node as an immediate dependent of the scheduled node.
1905 /// Move the boundary of scheduled code by one cycle.
1906 void ConvergingScheduler::SchedBoundary::bumpCycle(unsigned NextCycle) {
1907 if (SchedModel->getMicroOpBufferSize() == 0) {
1908 assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1909 if (MinReadyCycle > NextCycle)
1910 NextCycle = MinReadyCycle;
1912 // Update the current micro-ops, which will issue in the next cycle.
1913 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1914 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
1916 // Decrement DependentLatency based on the next cycle.
1917 if ((NextCycle - CurrCycle) > DependentLatency)
1918 DependentLatency = 0;
1920 DependentLatency -= (NextCycle - CurrCycle);
1922 if (!HazardRec->isEnabled()) {
1923 // Bypass HazardRec virtual calls.
1924 CurrCycle = NextCycle;
1927 // Bypass getHazardType calls in case of long latency.
1928 for (; CurrCycle != NextCycle; ++CurrCycle) {
1930 HazardRec->AdvanceCycle();
1932 HazardRec->RecedeCycle();
1935 CheckPending = true;
1936 unsigned LFactor = SchedModel->getLatencyFactor();
1938 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
1941 DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
1944 void ConvergingScheduler::SchedBoundary::incExecutedResources(unsigned PIdx,
1946 ExecutedResCounts[PIdx] += Count;
1947 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
1948 MaxExecutedResCount = ExecutedResCounts[PIdx];
1951 /// Add the given processor resource to this scheduled zone.
1953 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
1954 /// during which this resource is consumed.
1956 /// \return the next cycle at which the instruction may execute without
1957 /// oversubscribing resources.
1958 unsigned ConvergingScheduler::SchedBoundary::
1959 countResource(unsigned PIdx, unsigned Cycles, unsigned ReadyCycle) {
1960 unsigned Factor = SchedModel->getResourceFactor(PIdx);
1961 unsigned Count = Factor * Cycles;
1962 DEBUG(dbgs() << " " << getResourceName(PIdx)
1963 << " +" << Cycles << "x" << Factor << "u\n");
1965 // Update Executed resources counts.
1966 incExecutedResources(PIdx, Count);
1967 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
1968 Rem->RemainingCounts[PIdx] -= Count;
1970 // Check if this resource exceeds the current critical resource. If so, it
1971 // becomes the critical resource.
1972 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
1973 ZoneCritResIdx = PIdx;
1974 DEBUG(dbgs() << " *** Critical resource "
1975 << getResourceName(PIdx) << ": "
1976 << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
1978 // TODO: We don't yet model reserved resources. It's not hard though.
1982 /// Move the boundary of scheduled code by one SUnit.
1983 void ConvergingScheduler::SchedBoundary::bumpNode(SUnit *SU) {
1984 // Update the reservation table.
1985 if (HazardRec->isEnabled()) {
1986 if (!isTop() && SU->isCall) {
1987 // Calls are scheduled with their preceding instructions. For bottom-up
1988 // scheduling, clear the pipeline state before emitting.
1991 HazardRec->EmitInstruction(SU);
1993 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1994 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
1995 CurrMOps += IncMOps;
1996 // checkHazard prevents scheduling multiple instructions per cycle that exceed
1997 // issue width. However, we commonly reach the maximum. In this case
1998 // opportunistically bump the cycle to avoid uselessly checking everything in
1999 // the readyQ. Furthermore, a single instruction may produce more than one
2000 // cycle's worth of micro-ops.
2002 // TODO: Also check if this SU must end a dispatch group.
2003 unsigned NextCycle = CurrCycle;
2004 if (CurrMOps >= SchedModel->getIssueWidth()) {
2006 DEBUG(dbgs() << " *** Max MOps " << CurrMOps
2007 << " at cycle " << CurrCycle << '\n');
2009 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
2010 DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
2012 switch (SchedModel->getMicroOpBufferSize()) {
2014 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2017 if (ReadyCycle > NextCycle) {
2018 NextCycle = ReadyCycle;
2019 DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
2023 // We don't currently model the OOO reorder buffer, so consider all
2024 // scheduled MOps to be "retired".
2027 RetiredMOps += IncMOps;
2029 // Update resource counts and critical resource.
2030 if (SchedModel->hasInstrSchedModel()) {
2031 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2032 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2033 Rem->RemIssueCount -= DecRemIssue;
2034 if (ZoneCritResIdx) {
2035 // Scale scheduled micro-ops for comparing with the critical resource.
2036 unsigned ScaledMOps =
2037 RetiredMOps * SchedModel->getMicroOpFactor();
2039 // If scaled micro-ops are now more than the previous critical resource by
2040 // a full cycle, then micro-ops issue becomes critical.
2041 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2042 >= (int)SchedModel->getLatencyFactor()) {
2044 DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
2045 << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
2048 for (TargetSchedModel::ProcResIter
2049 PI = SchedModel->getWriteProcResBegin(SC),
2050 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2052 countResource(PI->ProcResourceIdx, PI->Cycles, ReadyCycle);
2053 if (RCycle > NextCycle)
2057 // Update ExpectedLatency and DependentLatency.
2058 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2059 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2060 if (SU->getDepth() > TopLatency) {
2061 TopLatency = SU->getDepth();
2062 DEBUG(dbgs() << " " << Available.getName()
2063 << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
2065 if (SU->getHeight() > BotLatency) {
2066 BotLatency = SU->getHeight();
2067 DEBUG(dbgs() << " " << Available.getName()
2068 << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
2070 // If we stall for any reason, bump the cycle.
2071 if (NextCycle > CurrCycle) {
2072 bumpCycle(NextCycle);
2075 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
2076 // resource limited. If a stall occured, bumpCycle does this.
2077 unsigned LFactor = SchedModel->getLatencyFactor();
2079 (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2082 DEBUG(dumpScheduledState());
2085 /// Release pending ready nodes in to the available queue. This makes them
2086 /// visible to heuristics.
2087 void ConvergingScheduler::SchedBoundary::releasePending() {
2088 // If the available queue is empty, it is safe to reset MinReadyCycle.
2089 if (Available.empty())
2090 MinReadyCycle = UINT_MAX;
2092 // Check to see if any of the pending instructions are ready to issue. If
2093 // so, add them to the available queue.
2094 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2095 for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2096 SUnit *SU = *(Pending.begin()+i);
2097 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
2099 if (ReadyCycle < MinReadyCycle)
2100 MinReadyCycle = ReadyCycle;
2102 if (!IsBuffered && ReadyCycle > CurrCycle)
2105 if (checkHazard(SU))
2109 Pending.remove(Pending.begin()+i);
2112 DEBUG(if (!Pending.empty()) Pending.dump());
2113 CheckPending = false;
2116 /// Remove SU from the ready set for this boundary.
2117 void ConvergingScheduler::SchedBoundary::removeReady(SUnit *SU) {
2118 if (Available.isInQueue(SU))
2119 Available.remove(Available.find(SU));
2121 assert(Pending.isInQueue(SU) && "bad ready count");
2122 Pending.remove(Pending.find(SU));
2126 /// If this queue only has one ready candidate, return it. As a side effect,
2127 /// defer any nodes that now hit a hazard, and advance the cycle until at least
2128 /// one node is ready. If multiple instructions are ready, return NULL.
2129 SUnit *ConvergingScheduler::SchedBoundary::pickOnlyChoice() {
2134 // Defer any ready instrs that now have a hazard.
2135 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2136 if (checkHazard(*I)) {
2138 I = Available.remove(I);
2144 for (unsigned i = 0; Available.empty(); ++i) {
2145 assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedLatency) &&
2146 "permanent hazard"); (void)i;
2147 bumpCycle(CurrCycle + 1);
2150 if (Available.size() == 1)
2151 return *Available.begin();
2156 // This is useful information to dump after bumpNode.
2157 // Note that the Queue contents are more useful before pickNodeFromQueue.
2158 void ConvergingScheduler::SchedBoundary::dumpScheduledState() {
2161 if (ZoneCritResIdx) {
2162 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2163 ResCount = getResourceCount(ZoneCritResIdx);
2166 ResFactor = SchedModel->getMicroOpFactor();
2167 ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
2169 unsigned LFactor = SchedModel->getLatencyFactor();
2170 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2171 << " Retired: " << RetiredMOps;
2172 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
2173 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
2174 << ResCount / ResFactor << " " << getResourceName(ZoneCritResIdx)
2175 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
2176 << (IsResourceLimited ? " - Resource" : " - Latency")
2181 void ConvergingScheduler::SchedCandidate::
2182 initResourceDelta(const ScheduleDAGMI *DAG,
2183 const TargetSchedModel *SchedModel) {
2184 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2187 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2188 for (TargetSchedModel::ProcResIter
2189 PI = SchedModel->getWriteProcResBegin(SC),
2190 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2191 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2192 ResDelta.CritResources += PI->Cycles;
2193 if (PI->ProcResourceIdx == Policy.DemandResIdx)
2194 ResDelta.DemandedResources += PI->Cycles;
2199 /// Return true if this heuristic determines order.
2200 static bool tryLess(int TryVal, int CandVal,
2201 ConvergingScheduler::SchedCandidate &TryCand,
2202 ConvergingScheduler::SchedCandidate &Cand,
2203 ConvergingScheduler::CandReason Reason) {
2204 if (TryVal < CandVal) {
2205 TryCand.Reason = Reason;
2208 if (TryVal > CandVal) {
2209 if (Cand.Reason > Reason)
2210 Cand.Reason = Reason;
2213 Cand.setRepeat(Reason);
2217 static bool tryGreater(int TryVal, int CandVal,
2218 ConvergingScheduler::SchedCandidate &TryCand,
2219 ConvergingScheduler::SchedCandidate &Cand,
2220 ConvergingScheduler::CandReason Reason) {
2221 if (TryVal > CandVal) {
2222 TryCand.Reason = Reason;
2225 if (TryVal < CandVal) {
2226 if (Cand.Reason > Reason)
2227 Cand.Reason = Reason;
2230 Cand.setRepeat(Reason);
2234 static bool tryPressure(const PressureChange &TryP,
2235 const PressureChange &CandP,
2236 ConvergingScheduler::SchedCandidate &TryCand,
2237 ConvergingScheduler::SchedCandidate &Cand,
2238 ConvergingScheduler::CandReason Reason) {
2239 int TryRank = TryP.getPSetOrMax();
2240 int CandRank = CandP.getPSetOrMax();
2241 // If both candidates affect the same set, go with the smallest increase.
2242 if (TryRank == CandRank) {
2243 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2246 // If one candidate decreases and the other increases, go with it.
2247 // Invalid candidates have UnitInc==0.
2248 if (tryLess(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2252 // If the candidates are decreasing pressure, reverse priority.
2253 if (TryP.getUnitInc() < 0)
2254 std::swap(TryRank, CandRank);
2255 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2258 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2259 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2262 /// Minimize physical register live ranges. Regalloc wants them adjacent to
2263 /// their physreg def/use.
2265 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2266 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2267 /// with the operation that produces or consumes the physreg. We'll do this when
2268 /// regalloc has support for parallel copies.
2269 static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2270 const MachineInstr *MI = SU->getInstr();
2274 unsigned ScheduledOper = isTop ? 1 : 0;
2275 unsigned UnscheduledOper = isTop ? 0 : 1;
2276 // If we have already scheduled the physreg produce/consumer, immediately
2277 // schedule the copy.
2278 if (TargetRegisterInfo::isPhysicalRegister(
2279 MI->getOperand(ScheduledOper).getReg()))
2281 // If the physreg is at the boundary, defer it. Otherwise schedule it
2282 // immediately to free the dependent. We can hoist the copy later.
2283 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2284 if (TargetRegisterInfo::isPhysicalRegister(
2285 MI->getOperand(UnscheduledOper).getReg()))
2286 return AtBoundary ? -1 : 1;
2290 static bool tryLatency(ConvergingScheduler::SchedCandidate &TryCand,
2291 ConvergingScheduler::SchedCandidate &Cand,
2292 ConvergingScheduler::SchedBoundary &Zone) {
2294 if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2295 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2296 TryCand, Cand, ConvergingScheduler::TopDepthReduce))
2299 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2300 TryCand, Cand, ConvergingScheduler::TopPathReduce))
2304 if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2305 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2306 TryCand, Cand, ConvergingScheduler::BotHeightReduce))
2309 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2310 TryCand, Cand, ConvergingScheduler::BotPathReduce))
2316 /// Apply a set of heursitics to a new candidate. Heuristics are currently
2317 /// hierarchical. This may be more efficient than a graduated cost model because
2318 /// we don't need to evaluate all aspects of the model for each node in the
2319 /// queue. But it's really done to make the heuristics easier to debug and
2320 /// statistically analyze.
2322 /// \param Cand provides the policy and current best candidate.
2323 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2324 /// \param Zone describes the scheduled zone that we are extending.
2325 /// \param RPTracker describes reg pressure within the scheduled zone.
2326 /// \param TempTracker is a scratch pressure tracker to reuse in queries.
2327 void ConvergingScheduler::tryCandidate(SchedCandidate &Cand,
2328 SchedCandidate &TryCand,
2329 SchedBoundary &Zone,
2330 const RegPressureTracker &RPTracker,
2331 RegPressureTracker &TempTracker) {
2333 // Always initialize TryCand's RPDelta.
2335 TempTracker.getMaxDownwardPressureDelta(
2336 TryCand.SU->getInstr(),
2338 DAG->getRegionCriticalPSets(),
2339 DAG->getRegPressure().MaxSetPressure);
2342 if (VerifyScheduling) {
2343 TempTracker.getMaxUpwardPressureDelta(
2344 TryCand.SU->getInstr(),
2345 &DAG->getPressureDiff(TryCand.SU),
2347 DAG->getRegionCriticalPSets(),
2348 DAG->getRegPressure().MaxSetPressure);
2351 RPTracker.getUpwardPressureDelta(
2352 TryCand.SU->getInstr(),
2353 DAG->getPressureDiff(TryCand.SU),
2355 DAG->getRegionCriticalPSets(),
2356 DAG->getRegPressure().MaxSetPressure);
2360 // Initialize the candidate if needed.
2361 if (!Cand.isValid()) {
2362 TryCand.Reason = NodeOrder;
2366 if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2367 biasPhysRegCopy(Cand.SU, Zone.isTop()),
2368 TryCand, Cand, PhysRegCopy))
2371 // Avoid exceeding the target's limit. If signed PSetID is negative, it is
2372 // invalid; convert it to INT_MAX to give it lowest priority.
2373 if (tryPressure(TryCand.RPDelta.Excess, Cand.RPDelta.Excess, TryCand, Cand,
2377 // For loops that are acyclic path limited, aggressively schedule for latency.
2378 if (Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, Zone))
2381 // Avoid increasing the max critical pressure in the scheduled region.
2382 if (tryPressure(TryCand.RPDelta.CriticalMax, Cand.RPDelta.CriticalMax,
2383 TryCand, Cand, RegCritical))
2386 // Keep clustered nodes together to encourage downstream peephole
2387 // optimizations which may reduce resource requirements.
2389 // This is a best effort to set things up for a post-RA pass. Optimizations
2390 // like generating loads of multiple registers should ideally be done within
2391 // the scheduler pass by combining the loads during DAG postprocessing.
2392 const SUnit *NextClusterSU =
2393 Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2394 if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2395 TryCand, Cand, Cluster))
2398 // Weak edges are for clustering and other constraints.
2399 if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2400 getWeakLeft(Cand.SU, Zone.isTop()),
2401 TryCand, Cand, Weak)) {
2404 // Avoid increasing the max pressure of the entire region.
2405 if (tryPressure(TryCand.RPDelta.CurrentMax, Cand.RPDelta.CurrentMax,
2406 TryCand, Cand, RegMax))
2409 // Avoid critical resource consumption and balance the schedule.
2410 TryCand.initResourceDelta(DAG, SchedModel);
2411 if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2412 TryCand, Cand, ResourceReduce))
2414 if (tryGreater(TryCand.ResDelta.DemandedResources,
2415 Cand.ResDelta.DemandedResources,
2416 TryCand, Cand, ResourceDemand))
2419 // Avoid serializing long latency dependence chains.
2420 // For acyclic path limited loops, latency was already checked above.
2421 if (Cand.Policy.ReduceLatency && !Rem.IsAcyclicLatencyLimited
2422 && tryLatency(TryCand, Cand, Zone)) {
2426 // Prefer immediate defs/users of the last scheduled instruction. This is a
2427 // local pressure avoidance strategy that also makes the machine code
2429 if (tryGreater(Zone.NextSUs.count(TryCand.SU), Zone.NextSUs.count(Cand.SU),
2430 TryCand, Cand, NextDefUse))
2433 // Fall through to original instruction order.
2434 if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2435 || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2436 TryCand.Reason = NodeOrder;
2441 const char *ConvergingScheduler::getReasonStr(
2442 ConvergingScheduler::CandReason Reason) {
2444 case NoCand: return "NOCAND ";
2445 case PhysRegCopy: return "PREG-COPY";
2446 case RegExcess: return "REG-EXCESS";
2447 case RegCritical: return "REG-CRIT ";
2448 case Cluster: return "CLUSTER ";
2449 case Weak: return "WEAK ";
2450 case RegMax: return "REG-MAX ";
2451 case ResourceReduce: return "RES-REDUCE";
2452 case ResourceDemand: return "RES-DEMAND";
2453 case TopDepthReduce: return "TOP-DEPTH ";
2454 case TopPathReduce: return "TOP-PATH ";
2455 case BotHeightReduce:return "BOT-HEIGHT";
2456 case BotPathReduce: return "BOT-PATH ";
2457 case NextDefUse: return "DEF-USE ";
2458 case NodeOrder: return "ORDER ";
2460 llvm_unreachable("Unknown reason!");
2463 void ConvergingScheduler::traceCandidate(const SchedCandidate &Cand) {
2465 unsigned ResIdx = 0;
2466 unsigned Latency = 0;
2467 switch (Cand.Reason) {
2471 P = Cand.RPDelta.Excess;
2474 P = Cand.RPDelta.CriticalMax;
2477 P = Cand.RPDelta.CurrentMax;
2479 case ResourceReduce:
2480 ResIdx = Cand.Policy.ReduceResIdx;
2482 case ResourceDemand:
2483 ResIdx = Cand.Policy.DemandResIdx;
2485 case TopDepthReduce:
2486 Latency = Cand.SU->getDepth();
2489 Latency = Cand.SU->getHeight();
2491 case BotHeightReduce:
2492 Latency = Cand.SU->getHeight();
2495 Latency = Cand.SU->getDepth();
2498 dbgs() << " SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2500 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2501 << ":" << P.getUnitInc() << " ";
2505 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2509 dbgs() << " " << Latency << " cycles ";
2516 /// Pick the best candidate from the top queue.
2518 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2519 /// DAG building. To adjust for the current scheduling location we need to
2520 /// maintain the number of vreg uses remaining to be top-scheduled.
2521 void ConvergingScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2522 const RegPressureTracker &RPTracker,
2523 SchedCandidate &Cand) {
2524 ReadyQueue &Q = Zone.Available;
2528 // getMaxPressureDelta temporarily modifies the tracker.
2529 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2531 for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2533 SchedCandidate TryCand(Cand.Policy);
2535 tryCandidate(Cand, TryCand, Zone, RPTracker, TempTracker);
2536 if (TryCand.Reason != NoCand) {
2537 // Initialize resource delta if needed in case future heuristics query it.
2538 if (TryCand.ResDelta == SchedResourceDelta())
2539 TryCand.initResourceDelta(DAG, SchedModel);
2540 Cand.setBest(TryCand);
2541 DEBUG(traceCandidate(Cand));
2546 static void tracePick(const ConvergingScheduler::SchedCandidate &Cand,
2548 DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2549 << ConvergingScheduler::getReasonStr(Cand.Reason) << '\n');
2552 /// Pick the best candidate node from either the top or bottom queue.
2553 SUnit *ConvergingScheduler::pickNodeBidirectional(bool &IsTopNode) {
2554 // Schedule as far as possible in the direction of no choice. This is most
2555 // efficient, but also provides the best heuristics for CriticalPSets.
2556 if (SUnit *SU = Bot.pickOnlyChoice()) {
2558 DEBUG(dbgs() << "Pick Bot NOCAND\n");
2561 if (SUnit *SU = Top.pickOnlyChoice()) {
2563 DEBUG(dbgs() << "Pick Top NOCAND\n");
2566 CandPolicy NoPolicy;
2567 SchedCandidate BotCand(NoPolicy);
2568 SchedCandidate TopCand(NoPolicy);
2569 Bot.setPolicy(BotCand.Policy, Top);
2570 Top.setPolicy(TopCand.Policy, Bot);
2572 // Prefer bottom scheduling when heuristics are silent.
2573 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2574 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2576 // If either Q has a single candidate that provides the least increase in
2577 // Excess pressure, we can immediately schedule from that Q.
2579 // RegionCriticalPSets summarizes the pressure within the scheduled region and
2580 // affects picking from either Q. If scheduling in one direction must
2581 // increase pressure for one of the excess PSets, then schedule in that
2582 // direction first to provide more freedom in the other direction.
2583 if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2584 || (BotCand.Reason == RegCritical
2585 && !BotCand.isRepeat(RegCritical)))
2588 tracePick(BotCand, IsTopNode);
2591 // Check if the top Q has a better candidate.
2592 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2593 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2595 // Choose the queue with the most important (lowest enum) reason.
2596 if (TopCand.Reason < BotCand.Reason) {
2598 tracePick(TopCand, IsTopNode);
2601 // Otherwise prefer the bottom candidate, in node order if all else failed.
2603 tracePick(BotCand, IsTopNode);
2607 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2608 SUnit *ConvergingScheduler::pickNode(bool &IsTopNode) {
2609 if (DAG->top() == DAG->bottom()) {
2610 assert(Top.Available.empty() && Top.Pending.empty() &&
2611 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2617 SU = Top.pickOnlyChoice();
2619 CandPolicy NoPolicy;
2620 SchedCandidate TopCand(NoPolicy);
2621 pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2622 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2627 else if (ForceBottomUp) {
2628 SU = Bot.pickOnlyChoice();
2630 CandPolicy NoPolicy;
2631 SchedCandidate BotCand(NoPolicy);
2632 pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2633 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2639 SU = pickNodeBidirectional(IsTopNode);
2641 } while (SU->isScheduled);
2643 if (SU->isTopReady())
2644 Top.removeReady(SU);
2645 if (SU->isBottomReady())
2646 Bot.removeReady(SU);
2648 DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
2652 void ConvergingScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
2654 MachineBasicBlock::iterator InsertPos = SU->getInstr();
2657 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
2659 // Find already scheduled copies with a single physreg dependence and move
2660 // them just above the scheduled instruction.
2661 for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
2663 if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
2665 SUnit *DepSU = I->getSUnit();
2666 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
2668 MachineInstr *Copy = DepSU->getInstr();
2669 if (!Copy->isCopy())
2671 DEBUG(dbgs() << " Rescheduling physreg copy ";
2672 I->getSUnit()->dump(DAG));
2673 DAG->moveInstruction(Copy, InsertPos);
2677 /// Update the scheduler's state after scheduling a node. This is the same node
2678 /// that was just returned by pickNode(). However, ScheduleDAGMI needs to update
2679 /// it's state based on the current cycle before MachineSchedStrategy does.
2681 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
2682 /// them here. See comments in biasPhysRegCopy.
2683 void ConvergingScheduler::schedNode(SUnit *SU, bool IsTopNode) {
2685 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.CurrCycle);
2687 if (SU->hasPhysRegUses)
2688 reschedulePhysRegCopies(SU, true);
2691 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.CurrCycle);
2693 if (SU->hasPhysRegDefs)
2694 reschedulePhysRegCopies(SU, false);
2698 /// Create the standard converging machine scheduler. This will be used as the
2699 /// default scheduler if the target does not set a default.
2700 static ScheduleDAGInstrs *createConvergingSched(MachineSchedContext *C) {
2701 assert((!ForceTopDown || !ForceBottomUp) &&
2702 "-misched-topdown incompatible with -misched-bottomup");
2703 ScheduleDAGMI *DAG = new ScheduleDAGMI(C, new ConvergingScheduler());
2704 // Register DAG post-processors.
2706 // FIXME: extend the mutation API to allow earlier mutations to instantiate
2707 // data and pass it to later mutations. Have a single mutation that gathers
2708 // the interesting nodes in one pass.
2709 DAG->addMutation(new CopyConstrain(DAG->TII, DAG->TRI));
2710 if (EnableLoadCluster)
2711 DAG->addMutation(new LoadClusterMutation(DAG->TII, DAG->TRI));
2712 if (EnableMacroFusion)
2713 DAG->addMutation(new MacroFusion(DAG->TII));
2716 static MachineSchedRegistry
2717 ConvergingSchedRegistry("converge", "Standard converging scheduler.",
2718 createConvergingSched);
2720 //===----------------------------------------------------------------------===//
2721 // ILP Scheduler. Currently for experimental analysis of heuristics.
2722 //===----------------------------------------------------------------------===//
2725 /// \brief Order nodes by the ILP metric.
2727 const SchedDFSResult *DFSResult;
2728 const BitVector *ScheduledTrees;
2731 ILPOrder(bool MaxILP): DFSResult(0), ScheduledTrees(0), MaximizeILP(MaxILP) {}
2733 /// \brief Apply a less-than relation on node priority.
2735 /// (Return true if A comes after B in the Q.)
2736 bool operator()(const SUnit *A, const SUnit *B) const {
2737 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
2738 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
2739 if (SchedTreeA != SchedTreeB) {
2740 // Unscheduled trees have lower priority.
2741 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
2742 return ScheduledTrees->test(SchedTreeB);
2744 // Trees with shallower connections have have lower priority.
2745 if (DFSResult->getSubtreeLevel(SchedTreeA)
2746 != DFSResult->getSubtreeLevel(SchedTreeB)) {
2747 return DFSResult->getSubtreeLevel(SchedTreeA)
2748 < DFSResult->getSubtreeLevel(SchedTreeB);
2752 return DFSResult->getILP(A) < DFSResult->getILP(B);
2754 return DFSResult->getILP(A) > DFSResult->getILP(B);
2758 /// \brief Schedule based on the ILP metric.
2759 class ILPScheduler : public MachineSchedStrategy {
2760 /// In case all subtrees are eventually connected to a common root through
2761 /// data dependence (e.g. reduction), place an upper limit on their size.
2763 /// FIXME: A subtree limit is generally good, but in the situation commented
2764 /// above, where multiple similar subtrees feed a common root, we should
2765 /// only split at a point where the resulting subtrees will be balanced.
2766 /// (a motivating test case must be found).
2767 static const unsigned SubtreeLimit = 16;
2772 std::vector<SUnit*> ReadyQ;
2774 ILPScheduler(bool MaximizeILP): DAG(0), Cmp(MaximizeILP) {}
2776 virtual void initialize(ScheduleDAGMI *dag) {
2778 DAG->computeDFSResult();
2779 Cmp.DFSResult = DAG->getDFSResult();
2780 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
2784 virtual void registerRoots() {
2785 // Restore the heap in ReadyQ with the updated DFS results.
2786 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2789 /// Implement MachineSchedStrategy interface.
2790 /// -----------------------------------------
2792 /// Callback to select the highest priority node from the ready Q.
2793 virtual SUnit *pickNode(bool &IsTopNode) {
2794 if (ReadyQ.empty()) return NULL;
2795 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2796 SUnit *SU = ReadyQ.back();
2799 DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
2800 << " ILP: " << DAG->getDFSResult()->getILP(SU)
2801 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
2802 << DAG->getDFSResult()->getSubtreeLevel(
2803 DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
2804 << "Scheduling " << *SU->getInstr());
2808 /// \brief Scheduler callback to notify that a new subtree is scheduled.
2809 virtual void scheduleTree(unsigned SubtreeID) {
2810 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2813 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
2814 /// DFSResults, and resort the priority Q.
2815 virtual void schedNode(SUnit *SU, bool IsTopNode) {
2816 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
2819 virtual void releaseTopNode(SUnit *) { /*only called for top roots*/ }
2821 virtual void releaseBottomNode(SUnit *SU) {
2822 ReadyQ.push_back(SU);
2823 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
2828 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
2829 return new ScheduleDAGMI(C, new ILPScheduler(true));
2831 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
2832 return new ScheduleDAGMI(C, new ILPScheduler(false));
2834 static MachineSchedRegistry ILPMaxRegistry(
2835 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
2836 static MachineSchedRegistry ILPMinRegistry(
2837 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
2839 //===----------------------------------------------------------------------===//
2840 // Machine Instruction Shuffler for Correctness Testing
2841 //===----------------------------------------------------------------------===//
2845 /// Apply a less-than relation on the node order, which corresponds to the
2846 /// instruction order prior to scheduling. IsReverse implements greater-than.
2847 template<bool IsReverse>
2849 bool operator()(SUnit *A, SUnit *B) const {
2851 return A->NodeNum > B->NodeNum;
2853 return A->NodeNum < B->NodeNum;
2857 /// Reorder instructions as much as possible.
2858 class InstructionShuffler : public MachineSchedStrategy {
2862 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
2863 // gives nodes with a higher number higher priority causing the latest
2864 // instructions to be scheduled first.
2865 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
2867 // When scheduling bottom-up, use greater-than as the queue priority.
2868 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
2871 InstructionShuffler(bool alternate, bool topdown)
2872 : IsAlternating(alternate), IsTopDown(topdown) {}
2874 virtual void initialize(ScheduleDAGMI *) {
2879 /// Implement MachineSchedStrategy interface.
2880 /// -----------------------------------------
2882 virtual SUnit *pickNode(bool &IsTopNode) {
2886 if (TopQ.empty()) return NULL;
2889 } while (SU->isScheduled);
2894 if (BottomQ.empty()) return NULL;
2897 } while (SU->isScheduled);
2901 IsTopDown = !IsTopDown;
2905 virtual void schedNode(SUnit *SU, bool IsTopNode) {}
2907 virtual void releaseTopNode(SUnit *SU) {
2910 virtual void releaseBottomNode(SUnit *SU) {
2916 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
2917 bool Alternate = !ForceTopDown && !ForceBottomUp;
2918 bool TopDown = !ForceBottomUp;
2919 assert((TopDown || !ForceTopDown) &&
2920 "-misched-topdown incompatible with -misched-bottomup");
2921 return new ScheduleDAGMI(C, new InstructionShuffler(Alternate, TopDown));
2923 static MachineSchedRegistry ShufflerRegistry(
2924 "shuffle", "Shuffle machine instructions alternating directions",
2925 createInstructionShuffler);
2928 //===----------------------------------------------------------------------===//
2929 // GraphWriter support for ScheduleDAGMI.
2930 //===----------------------------------------------------------------------===//
2935 template<> struct GraphTraits<
2936 ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
2939 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
2941 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
2943 static std::string getGraphName(const ScheduleDAG *G) {
2944 return G->MF.getName();
2947 static bool renderGraphFromBottomUp() {
2951 static bool isNodeHidden(const SUnit *Node) {
2952 return (Node->NumPreds > 10 || Node->NumSuccs > 10);
2955 static bool hasNodeAddressLabel(const SUnit *Node,
2956 const ScheduleDAG *Graph) {
2960 /// If you want to override the dot attributes printed for a particular
2961 /// edge, override this method.
2962 static std::string getEdgeAttributes(const SUnit *Node,
2964 const ScheduleDAG *Graph) {
2965 if (EI.isArtificialDep())
2966 return "color=cyan,style=dashed";
2968 return "color=blue,style=dashed";
2972 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
2974 raw_string_ostream SS(Str);
2975 SS << "SU(" << SU->NodeNum << ')';
2978 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
2979 return G->getGraphNodeLabel(SU);
2982 static std::string getNodeAttributes(const SUnit *N,
2983 const ScheduleDAG *Graph) {
2984 std::string Str("shape=Mrecord");
2985 const SchedDFSResult *DFS =
2986 static_cast<const ScheduleDAGMI*>(Graph)->getDFSResult();
2988 Str += ",style=filled,fillcolor=\"#";
2989 Str += DOT::getColorString(DFS->getSubtreeID(N));
2998 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
2999 /// rendered using 'dot'.
3001 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3003 ViewGraph(this, Name, false, Title);
3005 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3006 << "systems with Graphviz or gv!\n";
3010 /// Out-of-line implementation with no arguments is handy for gdb.
3011 void ScheduleDAGMI::viewGraph() {
3012 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());