1 //===----- SchedulePostRAList.cpp - list 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 // This implements a top-down list scheduler, using standard algorithms.
11 // The basic approach uses a priority queue of available nodes to schedule.
12 // One at a time, nodes are taken from the priority queue (thus in priority
13 // order), checked for legality to schedule, and emitted if legal.
15 // Nodes may not be legal to schedule either due to structural hazards (e.g.
16 // pipeline or resource constraints) or because an input to the instruction has
17 // not completed execution.
19 //===----------------------------------------------------------------------===//
21 #define DEBUG_TYPE "post-RA-sched"
22 #include "AntiDepBreaker.h"
23 #include "AggressiveAntiDepBreaker.h"
24 #include "CriticalAntiDepBreaker.h"
25 #include "RegisterClassInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/LatencyPriorityQueue.h"
28 #include "llvm/CodeGen/SchedulerRegistry.h"
29 #include "llvm/CodeGen/MachineDominators.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineLoopInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
35 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/ADT/BitVector.h"
47 #include "llvm/ADT/Statistic.h"
50 STATISTIC(NumNoops, "Number of noops inserted");
51 STATISTIC(NumStalls, "Number of pipeline stalls");
52 STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
54 // Post-RA scheduling is enabled with
55 // TargetSubtargetInfo.enablePostRAScheduler(). This flag can be used to
56 // override the target.
58 EnablePostRAScheduler("post-RA-scheduler",
59 cl::desc("Enable scheduling after register allocation"),
60 cl::init(false), cl::Hidden);
61 static cl::opt<std::string>
62 EnableAntiDepBreaking("break-anti-dependencies",
63 cl::desc("Break post-RA scheduling anti-dependencies: "
64 "\"critical\", \"all\", or \"none\""),
65 cl::init("none"), cl::Hidden);
67 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
69 DebugDiv("postra-sched-debugdiv",
70 cl::desc("Debug control MBBs that are scheduled"),
71 cl::init(0), cl::Hidden);
73 DebugMod("postra-sched-debugmod",
74 cl::desc("Debug control MBBs that are scheduled"),
75 cl::init(0), cl::Hidden);
77 AntiDepBreaker::~AntiDepBreaker() { }
80 class PostRAScheduler : public MachineFunctionPass {
82 const TargetInstrInfo *TII;
83 RegisterClassInfo RegClassInfo;
87 PostRAScheduler() : MachineFunctionPass(ID) {}
89 void getAnalysisUsage(AnalysisUsage &AU) const {
91 AU.addRequired<AliasAnalysis>();
92 AU.addRequired<TargetPassConfig>();
93 AU.addRequired<MachineDominatorTree>();
94 AU.addPreserved<MachineDominatorTree>();
95 AU.addRequired<MachineLoopInfo>();
96 AU.addPreserved<MachineLoopInfo>();
97 MachineFunctionPass::getAnalysisUsage(AU);
100 bool runOnMachineFunction(MachineFunction &Fn);
102 char PostRAScheduler::ID = 0;
104 class SchedulePostRATDList : public ScheduleDAGInstrs {
105 /// AvailableQueue - The priority queue to use for the available SUnits.
107 LatencyPriorityQueue AvailableQueue;
109 /// PendingQueue - This contains all of the instructions whose operands have
110 /// been issued, but their results are not ready yet (due to the latency of
111 /// the operation). Once the operands becomes available, the instruction is
112 /// added to the AvailableQueue.
113 std::vector<SUnit*> PendingQueue;
115 /// Topo - A topological ordering for SUnits.
116 ScheduleDAGTopologicalSort Topo;
118 /// HazardRec - The hazard recognizer to use.
119 ScheduleHazardRecognizer *HazardRec;
121 /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
122 AntiDepBreaker *AntiDepBreak;
124 /// AA - AliasAnalysis for making memory reference queries.
127 /// LiveRegs - true if the register is live.
130 /// The schedule. Null SUnit*'s represent noop instructions.
131 std::vector<SUnit*> Sequence;
134 SchedulePostRATDList(
135 MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
136 AliasAnalysis *AA, const RegisterClassInfo&,
137 TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
138 SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs);
140 ~SchedulePostRATDList();
142 /// startBlock - Initialize register live-range state for scheduling in
145 void startBlock(MachineBasicBlock *BB);
147 /// Initialize the scheduler state for the next scheduling region.
148 virtual void enterRegion(MachineBasicBlock *bb,
149 MachineBasicBlock::iterator begin,
150 MachineBasicBlock::iterator end,
153 /// Notify that the scheduler has finished scheduling the current region.
154 virtual void exitRegion();
156 /// Schedule - Schedule the instruction range using list scheduling.
162 /// Observe - Update liveness information to account for the current
163 /// instruction, which will not be scheduled.
165 void Observe(MachineInstr *MI, unsigned Count);
167 /// finishBlock - Clean up register live-range state.
171 /// FixupKills - Fix register kill flags that have been made
172 /// invalid due to scheduling
174 void FixupKills(MachineBasicBlock *MBB);
177 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
178 void ReleaseSuccessors(SUnit *SU);
179 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
180 void ListScheduleTopDown();
181 void StartBlockForKills(MachineBasicBlock *BB);
183 // ToggleKillFlag - Toggle a register operand kill flag. Other
184 // adjustments may be made to the instruction if necessary. Return
185 // true if the operand has been deleted, false if not.
186 bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
188 void dumpSchedule() const;
192 char &llvm::PostRASchedulerID = PostRAScheduler::ID;
194 INITIALIZE_PASS(PostRAScheduler, "post-RA-sched",
195 "Post RA top-down list latency scheduler", false, false)
197 SchedulePostRATDList::SchedulePostRATDList(
198 MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
199 AliasAnalysis *AA, const RegisterClassInfo &RCI,
200 TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
201 SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs)
202 : ScheduleDAGInstrs(MF, MLI, MDT, /*IsPostRA=*/true), Topo(SUnits), AA(AA),
203 LiveRegs(TRI->getNumRegs())
205 const TargetMachine &TM = MF.getTarget();
206 const InstrItineraryData *InstrItins = TM.getInstrItineraryData();
208 TM.getInstrInfo()->CreateTargetPostRAHazardRecognizer(InstrItins, this);
210 ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL) ?
211 (AntiDepBreaker *)new AggressiveAntiDepBreaker(MF, RCI, CriticalPathRCs) :
212 ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL) ?
213 (AntiDepBreaker *)new CriticalAntiDepBreaker(MF, RCI) : NULL));
216 SchedulePostRATDList::~SchedulePostRATDList() {
221 /// Initialize state associated with the next scheduling region.
222 void SchedulePostRATDList::enterRegion(MachineBasicBlock *bb,
223 MachineBasicBlock::iterator begin,
224 MachineBasicBlock::iterator end,
226 ScheduleDAGInstrs::enterRegion(bb, begin, end, endcount);
230 /// Print the schedule before exiting the region.
231 void SchedulePostRATDList::exitRegion() {
233 dbgs() << "*** Final schedule ***\n";
237 ScheduleDAGInstrs::exitRegion();
240 /// dumpSchedule - dump the scheduled Sequence.
241 void SchedulePostRATDList::dumpSchedule() const {
242 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
243 if (SUnit *SU = Sequence[i])
246 dbgs() << "**** NOOP ****\n";
250 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
251 TII = Fn.getTarget().getInstrInfo();
252 MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
253 MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
254 AliasAnalysis *AA = &getAnalysis<AliasAnalysis>();
255 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
257 RegClassInfo.runOnMachineFunction(Fn);
259 // Check for explicit enable/disable of post-ra scheduling.
260 TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =
261 TargetSubtargetInfo::ANTIDEP_NONE;
262 SmallVector<const TargetRegisterClass*, 4> CriticalPathRCs;
263 if (EnablePostRAScheduler.getPosition() > 0) {
264 if (!EnablePostRAScheduler)
267 // Check that post-RA scheduling is enabled for this target.
268 // This may upgrade the AntiDepMode.
269 const TargetSubtargetInfo &ST = Fn.getTarget().getSubtarget<TargetSubtargetInfo>();
270 if (!ST.enablePostRAScheduler(PassConfig->getOptLevel(), AntiDepMode,
275 // Check for antidep breaking override...
276 if (EnableAntiDepBreaking.getPosition() > 0) {
277 AntiDepMode = (EnableAntiDepBreaking == "all")
278 ? TargetSubtargetInfo::ANTIDEP_ALL
279 : ((EnableAntiDepBreaking == "critical")
280 ? TargetSubtargetInfo::ANTIDEP_CRITICAL
281 : TargetSubtargetInfo::ANTIDEP_NONE);
284 DEBUG(dbgs() << "PostRAScheduler\n");
286 SchedulePostRATDList Scheduler(Fn, MLI, MDT, AA, RegClassInfo, AntiDepMode,
289 // Loop over all of the basic blocks
290 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
291 MBB != MBBe; ++MBB) {
293 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
295 static int bbcnt = 0;
296 if (bbcnt++ % DebugDiv != DebugMod)
298 dbgs() << "*** DEBUG scheduling " << Fn.getFunction()->getName()
299 << ":BB#" << MBB->getNumber() << " ***\n";
303 // Initialize register live-range state for scheduling in this block.
304 Scheduler.startBlock(MBB);
306 // Schedule each sequence of instructions not interrupted by a label
307 // or anything else that effectively needs to shut down scheduling.
308 MachineBasicBlock::iterator Current = MBB->end();
309 unsigned Count = MBB->size(), CurrentCount = Count;
310 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
311 MachineInstr *MI = llvm::prior(I);
312 // Calls are not scheduling boundaries before register allocation, but
313 // post-ra we don't gain anything by scheduling across calls since we
314 // don't need to worry about register pressure.
315 if (MI->isCall() || TII->isSchedulingBoundary(MI, MBB, Fn)) {
316 Scheduler.enterRegion(MBB, I, Current, CurrentCount);
317 Scheduler.schedule();
318 Scheduler.exitRegion();
319 Scheduler.EmitSchedule();
321 CurrentCount = Count - 1;
322 Scheduler.Observe(MI, CurrentCount);
327 Count -= MI->getBundleSize();
329 assert(Count == 0 && "Instruction count mismatch!");
330 assert((MBB->begin() == Current || CurrentCount != 0) &&
331 "Instruction count mismatch!");
332 Scheduler.enterRegion(MBB, MBB->begin(), Current, CurrentCount);
333 Scheduler.schedule();
334 Scheduler.exitRegion();
335 Scheduler.EmitSchedule();
337 // Clean up register live-range state.
338 Scheduler.finishBlock();
340 // Update register kills
341 Scheduler.FixupKills(MBB);
347 /// StartBlock - Initialize register live-range state for scheduling in
350 void SchedulePostRATDList::startBlock(MachineBasicBlock *BB) {
351 // Call the superclass.
352 ScheduleDAGInstrs::startBlock(BB);
354 // Reset the hazard recognizer and anti-dep breaker.
356 if (AntiDepBreak != NULL)
357 AntiDepBreak->StartBlock(BB);
360 /// Schedule - Schedule the instruction range using list scheduling.
362 void SchedulePostRATDList::schedule() {
363 // Build the scheduling graph.
366 if (AntiDepBreak != NULL) {
368 AntiDepBreak->BreakAntiDependencies(SUnits, RegionBegin, RegionEnd,
369 EndIndex, DbgValues);
372 // We made changes. Update the dependency graph.
373 // Theoretically we could update the graph in place:
374 // When a live range is changed to use a different register, remove
375 // the def's anti-dependence *and* output-dependence edges due to
376 // that register, and add new anti-dependence and output-dependence
377 // edges based on the next live range of the register.
378 ScheduleDAG::clearDAG();
381 NumFixedAnti += Broken;
385 DEBUG(dbgs() << "********** List Scheduling **********\n");
386 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
387 SUnits[su].dumpAll(this));
389 AvailableQueue.initNodes(SUnits);
390 ListScheduleTopDown();
391 AvailableQueue.releaseState();
394 /// Observe - Update liveness information to account for the current
395 /// instruction, which will not be scheduled.
397 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
398 if (AntiDepBreak != NULL)
399 AntiDepBreak->Observe(MI, Count, EndIndex);
402 /// FinishBlock - Clean up register live-range state.
404 void SchedulePostRATDList::finishBlock() {
405 if (AntiDepBreak != NULL)
406 AntiDepBreak->FinishBlock();
408 // Call the superclass.
409 ScheduleDAGInstrs::finishBlock();
412 /// StartBlockForKills - Initialize register live-range state for updating kills
414 void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
415 // Start with no live registers.
418 // Determine the live-out physregs for this block.
419 if (!BB->empty() && BB->back().isReturn()) {
420 // In a return block, examine the function live-out regs.
421 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
422 E = MRI.liveout_end(); I != E; ++I) {
425 // Repeat, for all subregs.
426 for (const uint16_t *Subreg = TRI->getSubRegisters(Reg);
428 LiveRegs.set(*Subreg);
432 // In a non-return block, examine the live-in regs of all successors.
433 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
434 SE = BB->succ_end(); SI != SE; ++SI) {
435 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
436 E = (*SI)->livein_end(); I != E; ++I) {
439 // Repeat, for all subregs.
440 for (const uint16_t *Subreg = TRI->getSubRegisters(Reg);
442 LiveRegs.set(*Subreg);
448 bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
449 MachineOperand &MO) {
450 // Setting kill flag...
456 // If MO itself is live, clear the kill flag...
457 if (LiveRegs.test(MO.getReg())) {
462 // If any subreg of MO is live, then create an imp-def for that
463 // subreg and keep MO marked as killed.
466 const unsigned SuperReg = MO.getReg();
467 for (const uint16_t *Subreg = TRI->getSubRegisters(SuperReg);
469 if (LiveRegs.test(*Subreg)) {
470 MI->addOperand(MachineOperand::CreateReg(*Subreg,
484 /// FixupKills - Fix the register kill flags, they may have been made
485 /// incorrect by instruction reordering.
487 void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
488 DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
490 BitVector killedRegs(TRI->getNumRegs());
491 BitVector ReservedRegs = TRI->getReservedRegs(MF);
493 StartBlockForKills(MBB);
495 // Examine block from end to start...
496 unsigned Count = MBB->size();
497 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
499 MachineInstr *MI = --I;
500 if (MI->isDebugValue())
503 // Update liveness. Registers that are defed but not used in this
504 // instruction are now dead. Mark register and all subregs as they
505 // are completely defined.
506 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
507 MachineOperand &MO = MI->getOperand(i);
509 LiveRegs.clearBitsNotInMask(MO.getRegMask());
510 if (!MO.isReg()) continue;
511 unsigned Reg = MO.getReg();
512 if (Reg == 0) continue;
513 if (!MO.isDef()) continue;
514 // Ignore two-addr defs.
515 if (MI->isRegTiedToUseOperand(i)) continue;
519 // Repeat for all subregs.
520 for (const uint16_t *Subreg = TRI->getSubRegisters(Reg);
522 LiveRegs.reset(*Subreg);
525 // Examine all used registers and set/clear kill flag. When a
526 // register is used multiple times we only set the kill flag on
529 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
530 MachineOperand &MO = MI->getOperand(i);
531 if (!MO.isReg() || !MO.isUse()) continue;
532 unsigned Reg = MO.getReg();
533 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
536 if (!killedRegs.test(Reg)) {
538 // A register is not killed if any subregs are live...
539 for (const uint16_t *Subreg = TRI->getSubRegisters(Reg);
541 if (LiveRegs.test(*Subreg)) {
547 // If subreg is not live, then register is killed if it became
548 // live in this instruction
550 kill = !LiveRegs.test(Reg);
553 if (MO.isKill() != kill) {
554 DEBUG(dbgs() << "Fixing " << MO << " in ");
555 // Warning: ToggleKillFlag may invalidate MO.
556 ToggleKillFlag(MI, MO);
563 // Mark any used register (that is not using undef) and subregs as
565 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
566 MachineOperand &MO = MI->getOperand(i);
567 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
568 unsigned Reg = MO.getReg();
569 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
573 for (const uint16_t *Subreg = TRI->getSubRegisters(Reg);
575 LiveRegs.set(*Subreg);
580 //===----------------------------------------------------------------------===//
581 // Top-Down Scheduling
582 //===----------------------------------------------------------------------===//
584 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
585 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
586 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
587 SUnit *SuccSU = SuccEdge->getSUnit();
590 if (SuccSU->NumPredsLeft == 0) {
591 dbgs() << "*** Scheduling failed! ***\n";
593 dbgs() << " has been released too many times!\n";
597 --SuccSU->NumPredsLeft;
599 // Standard scheduler algorithms will recompute the depth of the successor
601 // SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
603 // However, we lazily compute node depth instead. Note that
604 // ScheduleNodeTopDown has already updated the depth of this node which causes
605 // all descendents to be marked dirty. Setting the successor depth explicitly
606 // here would cause depth to be recomputed for all its ancestors. If the
607 // successor is not yet ready (because of a transitively redundant edge) then
608 // this causes depth computation to be quadratic in the size of the DAG.
610 // If all the node's predecessors are scheduled, this node is ready
611 // to be scheduled. Ignore the special ExitSU node.
612 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
613 PendingQueue.push_back(SuccSU);
616 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
617 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
618 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
620 ReleaseSucc(SU, &*I);
624 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
625 /// count of its successors. If a successor pending count is zero, add it to
626 /// the Available queue.
627 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
628 DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
629 DEBUG(SU->dump(this));
631 Sequence.push_back(SU);
632 assert(CurCycle >= SU->getDepth() &&
633 "Node scheduled above its depth!");
634 SU->setDepthToAtLeast(CurCycle);
636 ReleaseSuccessors(SU);
637 SU->isScheduled = true;
638 AvailableQueue.scheduledNode(SU);
641 /// ListScheduleTopDown - The main loop of list scheduling for top-down
643 void SchedulePostRATDList::ListScheduleTopDown() {
644 unsigned CurCycle = 0;
646 // We're scheduling top-down but we're visiting the regions in
647 // bottom-up order, so we don't know the hazards at the start of a
648 // region. So assume no hazards (this should usually be ok as most
649 // blocks are a single region).
652 // Release any successors of the special Entry node.
653 ReleaseSuccessors(&EntrySU);
655 // Add all leaves to Available queue.
656 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
657 // It is available if it has no predecessors.
658 bool available = SUnits[i].Preds.empty();
660 AvailableQueue.push(&SUnits[i]);
661 SUnits[i].isAvailable = true;
665 // In any cycle where we can't schedule any instructions, we must
666 // stall or emit a noop, depending on the target.
667 bool CycleHasInsts = false;
669 // While Available queue is not empty, grab the node with the highest
670 // priority. If it is not ready put it back. Schedule the node.
671 std::vector<SUnit*> NotReady;
672 Sequence.reserve(SUnits.size());
673 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
674 // Check to see if any of the pending instructions are ready to issue. If
675 // so, add them to the available queue.
676 unsigned MinDepth = ~0u;
677 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
678 if (PendingQueue[i]->getDepth() <= CurCycle) {
679 AvailableQueue.push(PendingQueue[i]);
680 PendingQueue[i]->isAvailable = true;
681 PendingQueue[i] = PendingQueue.back();
682 PendingQueue.pop_back();
684 } else if (PendingQueue[i]->getDepth() < MinDepth)
685 MinDepth = PendingQueue[i]->getDepth();
688 DEBUG(dbgs() << "\n*** Examining Available\n"; AvailableQueue.dump(this));
690 SUnit *FoundSUnit = 0;
691 bool HasNoopHazards = false;
692 while (!AvailableQueue.empty()) {
693 SUnit *CurSUnit = AvailableQueue.pop();
695 ScheduleHazardRecognizer::HazardType HT =
696 HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
697 if (HT == ScheduleHazardRecognizer::NoHazard) {
698 FoundSUnit = CurSUnit;
702 // Remember if this is a noop hazard.
703 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
705 NotReady.push_back(CurSUnit);
708 // Add the nodes that aren't ready back onto the available list.
709 if (!NotReady.empty()) {
710 AvailableQueue.push_all(NotReady);
714 // If we found a node to schedule...
716 // ... schedule the node...
717 ScheduleNodeTopDown(FoundSUnit, CurCycle);
718 HazardRec->EmitInstruction(FoundSUnit);
719 CycleHasInsts = true;
720 if (HazardRec->atIssueLimit()) {
721 DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle << '\n');
722 HazardRec->AdvanceCycle();
724 CycleHasInsts = false;
728 DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
729 HazardRec->AdvanceCycle();
730 } else if (!HasNoopHazards) {
731 // Otherwise, we have a pipeline stall, but no other problem,
732 // just advance the current cycle and try again.
733 DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
734 HazardRec->AdvanceCycle();
737 // Otherwise, we have no instructions to issue and we have instructions
738 // that will fault if we don't do this right. This is the case for
739 // processors without pipeline interlocks and other cases.
740 DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
741 HazardRec->EmitNoop();
742 Sequence.push_back(0); // NULL here means noop
747 CycleHasInsts = false;
752 unsigned ScheduledNodes = VerifyScheduledDAG(/*isBottomUp=*/false);
754 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
757 assert(Sequence.size() - Noops == ScheduledNodes &&
758 "The number of nodes scheduled doesn't match the expected number!");
762 // EmitSchedule - Emit the machine code in scheduled order.
763 void SchedulePostRATDList::EmitSchedule() {
764 RegionBegin = RegionEnd;
766 // If first instruction was a DBG_VALUE then put it back.
768 BB->splice(RegionEnd, BB, FirstDbgValue);
770 // Then re-insert them according to the given schedule.
771 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
772 if (SUnit *SU = Sequence[i])
773 BB->splice(RegionEnd, BB, SU->getInstr());
775 // Null SUnit* is a noop.
776 TII->insertNoop(*BB, RegionEnd);
778 // Update the Begin iterator, as the first instruction in the block
779 // may have been scheduled later.
781 RegionBegin = prior(RegionEnd);
784 // Reinsert any remaining debug_values.
785 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
786 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
787 std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
788 MachineInstr *DbgValue = P.first;
789 MachineBasicBlock::iterator OrigPrivMI = P.second;
790 BB->splice(++OrigPrivMI, BB, DbgValue);
793 FirstDbgValue = NULL;