1 //===----- SchedulePostRAList.cpp - list scheduler ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
14 //
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.
18 //
19 //===----------------------------------------------------------------------===//
20 
21 #include "llvm/CodeGen/Passes.h"
22 #include "AggressiveAntiDepBreaker.h"
23 #include "AntiDepBreaker.h"
24 #include "CriticalAntiDepBreaker.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/AliasAnalysis.h"
28 #include "llvm/CodeGen/LatencyPriorityQueue.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/RegisterClassInfo.h"
35 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
36 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
37 #include "llvm/CodeGen/SchedulerRegistry.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetSubtargetInfo.h"
46 using namespace llvm;
47 
48 #define DEBUG_TYPE "post-RA-sched"
49 
50 STATISTIC(NumNoops, "Number of noops inserted");
51 STATISTIC(NumStalls, "Number of pipeline stalls");
52 STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
53 
54 // Post-RA scheduling is enabled with
55 // TargetSubtargetInfo.enablePostRAScheduler(). This flag can be used to
56 // override the target.
57 static cl::opt<bool>
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);
66 
67 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
68 static cl::opt<int>
69 DebugDiv("postra-sched-debugdiv",
70                       cl::desc("Debug control MBBs that are scheduled"),
71                       cl::init(0), cl::Hidden);
72 static cl::opt<int>
73 DebugMod("postra-sched-debugmod",
74                       cl::desc("Debug control MBBs that are scheduled"),
75                       cl::init(0), cl::Hidden);
76 
77 AntiDepBreaker::~AntiDepBreaker() { }
78 
79 namespace {
80   class PostRAScheduler : public MachineFunctionPass {
81     const TargetInstrInfo *TII;
82     RegisterClassInfo RegClassInfo;
83 
84   public:
85     static char ID;
86     PostRAScheduler() : MachineFunctionPass(ID) {}
87 
88     void getAnalysisUsage(AnalysisUsage &AU) const override {
89       AU.setPreservesCFG();
90       AU.addRequired<AAResultsWrapperPass>();
91       AU.addRequired<TargetPassConfig>();
92       AU.addRequired<MachineDominatorTree>();
93       AU.addPreserved<MachineDominatorTree>();
94       AU.addRequired<MachineLoopInfo>();
95       AU.addPreserved<MachineLoopInfo>();
96       MachineFunctionPass::getAnalysisUsage(AU);
97     }
98 
99     bool runOnMachineFunction(MachineFunction &Fn) override;
100 
101     bool enablePostRAScheduler(
102         const TargetSubtargetInfo &ST, CodeGenOpt::Level OptLevel,
103         TargetSubtargetInfo::AntiDepBreakMode &Mode,
104         TargetSubtargetInfo::RegClassVector &CriticalPathRCs) const;
105   };
106   char PostRAScheduler::ID = 0;
107 
108   class SchedulePostRATDList : public ScheduleDAGInstrs {
109     /// AvailableQueue - The priority queue to use for the available SUnits.
110     ///
111     LatencyPriorityQueue AvailableQueue;
112 
113     /// PendingQueue - This contains all of the instructions whose operands have
114     /// been issued, but their results are not ready yet (due to the latency of
115     /// the operation).  Once the operands becomes available, the instruction is
116     /// added to the AvailableQueue.
117     std::vector<SUnit*> PendingQueue;
118 
119     /// HazardRec - The hazard recognizer to use.
120     ScheduleHazardRecognizer *HazardRec;
121 
122     /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
123     AntiDepBreaker *AntiDepBreak;
124 
125     /// AA - AliasAnalysis for making memory reference queries.
126     AliasAnalysis *AA;
127 
128     /// The schedule. Null SUnit*'s represent noop instructions.
129     std::vector<SUnit*> Sequence;
130 
131     /// Ordered list of DAG postprocessing steps.
132     std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
133 
134     /// The index in BB of RegionEnd.
135     ///
136     /// This is the instruction number from the top of the current block, not
137     /// the SlotIndex. It is only used by the AntiDepBreaker.
138     unsigned EndIndex;
139 
140   public:
141     SchedulePostRATDList(
142         MachineFunction &MF, MachineLoopInfo &MLI, AliasAnalysis *AA,
143         const RegisterClassInfo &,
144         TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
145         SmallVectorImpl<const TargetRegisterClass *> &CriticalPathRCs);
146 
147     ~SchedulePostRATDList() override;
148 
149     /// startBlock - Initialize register live-range state for scheduling in
150     /// this block.
151     ///
152     void startBlock(MachineBasicBlock *BB) override;
153 
154     // Set the index of RegionEnd within the current BB.
155     void setEndIndex(unsigned EndIdx) { EndIndex = EndIdx; }
156 
157     /// Initialize the scheduler state for the next scheduling region.
158     void enterRegion(MachineBasicBlock *bb,
159                      MachineBasicBlock::iterator begin,
160                      MachineBasicBlock::iterator end,
161                      unsigned regioninstrs) override;
162 
163     /// Notify that the scheduler has finished scheduling the current region.
164     void exitRegion() override;
165 
166     /// Schedule - Schedule the instruction range using list scheduling.
167     ///
168     void schedule() override;
169 
170     void EmitSchedule();
171 
172     /// Observe - Update liveness information to account for the current
173     /// instruction, which will not be scheduled.
174     ///
175     void Observe(MachineInstr &MI, unsigned Count);
176 
177     /// finishBlock - Clean up register live-range state.
178     ///
179     void finishBlock() override;
180 
181   private:
182     /// Apply each ScheduleDAGMutation step in order.
183     void postprocessDAG();
184 
185     void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
186     void ReleaseSuccessors(SUnit *SU);
187     void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
188     void ListScheduleTopDown();
189 
190     void dumpSchedule() const;
191     void emitNoop(unsigned CurCycle);
192   };
193 }
194 
195 char &llvm::PostRASchedulerID = PostRAScheduler::ID;
196 
197 INITIALIZE_PASS(PostRAScheduler, "post-RA-sched",
198                 "Post RA top-down list latency scheduler", false, false)
199 
200 SchedulePostRATDList::SchedulePostRATDList(
201     MachineFunction &MF, MachineLoopInfo &MLI, AliasAnalysis *AA,
202     const RegisterClassInfo &RCI,
203     TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
204     SmallVectorImpl<const TargetRegisterClass *> &CriticalPathRCs)
205     : ScheduleDAGInstrs(MF, &MLI), AA(AA), EndIndex(0) {
206 
207   const InstrItineraryData *InstrItins =
208       MF.getSubtarget().getInstrItineraryData();
209   HazardRec =
210       MF.getSubtarget().getInstrInfo()->CreateTargetPostRAHazardRecognizer(
211           InstrItins, this);
212   MF.getSubtarget().getPostRAMutations(Mutations);
213 
214   assert((AntiDepMode == TargetSubtargetInfo::ANTIDEP_NONE ||
215           MRI.tracksLiveness()) &&
216          "Live-ins must be accurate for anti-dependency breaking");
217   AntiDepBreak =
218     ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL) ?
219      (AntiDepBreaker *)new AggressiveAntiDepBreaker(MF, RCI, CriticalPathRCs) :
220      ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL) ?
221       (AntiDepBreaker *)new CriticalAntiDepBreaker(MF, RCI) : nullptr));
222 }
223 
224 SchedulePostRATDList::~SchedulePostRATDList() {
225   delete HazardRec;
226   delete AntiDepBreak;
227 }
228 
229 /// Initialize state associated with the next scheduling region.
230 void SchedulePostRATDList::enterRegion(MachineBasicBlock *bb,
231                  MachineBasicBlock::iterator begin,
232                  MachineBasicBlock::iterator end,
233                  unsigned regioninstrs) {
234   ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
235   Sequence.clear();
236 }
237 
238 /// Print the schedule before exiting the region.
239 void SchedulePostRATDList::exitRegion() {
240   DEBUG({
241       dbgs() << "*** Final schedule ***\n";
242       dumpSchedule();
243       dbgs() << '\n';
244     });
245   ScheduleDAGInstrs::exitRegion();
246 }
247 
248 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
249 /// dumpSchedule - dump the scheduled Sequence.
250 void SchedulePostRATDList::dumpSchedule() const {
251   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
252     if (SUnit *SU = Sequence[i])
253       SU->dump(this);
254     else
255       dbgs() << "**** NOOP ****\n";
256   }
257 }
258 #endif
259 
260 bool PostRAScheduler::enablePostRAScheduler(
261     const TargetSubtargetInfo &ST,
262     CodeGenOpt::Level OptLevel,
263     TargetSubtargetInfo::AntiDepBreakMode &Mode,
264     TargetSubtargetInfo::RegClassVector &CriticalPathRCs) const {
265   Mode = ST.getAntiDepBreakMode();
266   ST.getCriticalPathRCs(CriticalPathRCs);
267   return ST.enablePostRAScheduler() &&
268          OptLevel >= ST.getOptLevelToEnablePostRAScheduler();
269 }
270 
271 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
272   if (skipOptnoneFunction(*Fn.getFunction()))
273     return false;
274 
275   TII = Fn.getSubtarget().getInstrInfo();
276   MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
277   AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
278   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
279 
280   RegClassInfo.runOnMachineFunction(Fn);
281 
282   // Check for explicit enable/disable of post-ra scheduling.
283   TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =
284     TargetSubtargetInfo::ANTIDEP_NONE;
285   SmallVector<const TargetRegisterClass*, 4> CriticalPathRCs;
286   if (EnablePostRAScheduler.getPosition() > 0) {
287     if (!EnablePostRAScheduler)
288       return false;
289   } else {
290     // Check that post-RA scheduling is enabled for this target.
291     // This may upgrade the AntiDepMode.
292     if (!enablePostRAScheduler(Fn.getSubtarget(), PassConfig->getOptLevel(),
293                                AntiDepMode, CriticalPathRCs))
294       return false;
295   }
296 
297   // Check for antidep breaking override...
298   if (EnableAntiDepBreaking.getPosition() > 0) {
299     AntiDepMode = (EnableAntiDepBreaking == "all")
300       ? TargetSubtargetInfo::ANTIDEP_ALL
301       : ((EnableAntiDepBreaking == "critical")
302          ? TargetSubtargetInfo::ANTIDEP_CRITICAL
303          : TargetSubtargetInfo::ANTIDEP_NONE);
304   }
305 
306   DEBUG(dbgs() << "PostRAScheduler\n");
307 
308   SchedulePostRATDList Scheduler(Fn, MLI, AA, RegClassInfo, AntiDepMode,
309                                  CriticalPathRCs);
310 
311   // Loop over all of the basic blocks
312   for (auto &MBB : Fn) {
313 #ifndef NDEBUG
314     // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
315     if (DebugDiv > 0) {
316       static int bbcnt = 0;
317       if (bbcnt++ % DebugDiv != DebugMod)
318         continue;
319       dbgs() << "*** DEBUG scheduling " << Fn.getName()
320              << ":BB#" << MBB.getNumber() << " ***\n";
321     }
322 #endif
323 
324     // Initialize register live-range state for scheduling in this block.
325     Scheduler.startBlock(&MBB);
326 
327     // Schedule each sequence of instructions not interrupted by a label
328     // or anything else that effectively needs to shut down scheduling.
329     MachineBasicBlock::iterator Current = MBB.end();
330     unsigned Count = MBB.size(), CurrentCount = Count;
331     for (MachineBasicBlock::iterator I = Current; I != MBB.begin();) {
332       MachineInstr *MI = std::prev(I);
333       --Count;
334       // Calls are not scheduling boundaries before register allocation, but
335       // post-ra we don't gain anything by scheduling across calls since we
336       // don't need to worry about register pressure.
337       if (MI->isCall() || TII->isSchedulingBoundary(MI, &MBB, Fn)) {
338         Scheduler.enterRegion(&MBB, I, Current, CurrentCount - Count);
339         Scheduler.setEndIndex(CurrentCount);
340         Scheduler.schedule();
341         Scheduler.exitRegion();
342         Scheduler.EmitSchedule();
343         Current = MI;
344         CurrentCount = Count;
345         Scheduler.Observe(*MI, CurrentCount);
346       }
347       I = MI;
348       if (MI->isBundle())
349         Count -= MI->getBundleSize();
350     }
351     assert(Count == 0 && "Instruction count mismatch!");
352     assert((MBB.begin() == Current || CurrentCount != 0) &&
353            "Instruction count mismatch!");
354     Scheduler.enterRegion(&MBB, MBB.begin(), Current, CurrentCount);
355     Scheduler.setEndIndex(CurrentCount);
356     Scheduler.schedule();
357     Scheduler.exitRegion();
358     Scheduler.EmitSchedule();
359 
360     // Clean up register live-range state.
361     Scheduler.finishBlock();
362 
363     // Update register kills
364     Scheduler.fixupKills(&MBB);
365   }
366 
367   return true;
368 }
369 
370 /// StartBlock - Initialize register live-range state for scheduling in
371 /// this block.
372 ///
373 void SchedulePostRATDList::startBlock(MachineBasicBlock *BB) {
374   // Call the superclass.
375   ScheduleDAGInstrs::startBlock(BB);
376 
377   // Reset the hazard recognizer and anti-dep breaker.
378   HazardRec->Reset();
379   if (AntiDepBreak)
380     AntiDepBreak->StartBlock(BB);
381 }
382 
383 /// Schedule - Schedule the instruction range using list scheduling.
384 ///
385 void SchedulePostRATDList::schedule() {
386   // Build the scheduling graph.
387   buildSchedGraph(AA);
388 
389   if (AntiDepBreak) {
390     unsigned Broken =
391       AntiDepBreak->BreakAntiDependencies(SUnits, RegionBegin, RegionEnd,
392                                           EndIndex, DbgValues);
393 
394     if (Broken != 0) {
395       // We made changes. Update the dependency graph.
396       // Theoretically we could update the graph in place:
397       // When a live range is changed to use a different register, remove
398       // the def's anti-dependence *and* output-dependence edges due to
399       // that register, and add new anti-dependence and output-dependence
400       // edges based on the next live range of the register.
401       ScheduleDAG::clearDAG();
402       buildSchedGraph(AA);
403 
404       NumFixedAnti += Broken;
405     }
406   }
407 
408   postprocessDAG();
409 
410   DEBUG(dbgs() << "********** List Scheduling **********\n");
411   DEBUG(
412     for (const SUnit &SU : SUnits) {
413       SU.dumpAll(this);
414       dbgs() << '\n';
415     }
416   );
417 
418   AvailableQueue.initNodes(SUnits);
419   ListScheduleTopDown();
420   AvailableQueue.releaseState();
421 }
422 
423 /// Observe - Update liveness information to account for the current
424 /// instruction, which will not be scheduled.
425 ///
426 void SchedulePostRATDList::Observe(MachineInstr &MI, unsigned Count) {
427   if (AntiDepBreak)
428     AntiDepBreak->Observe(MI, Count, EndIndex);
429 }
430 
431 /// FinishBlock - Clean up register live-range state.
432 ///
433 void SchedulePostRATDList::finishBlock() {
434   if (AntiDepBreak)
435     AntiDepBreak->FinishBlock();
436 
437   // Call the superclass.
438   ScheduleDAGInstrs::finishBlock();
439 }
440 
441 /// Apply each ScheduleDAGMutation step in order.
442 void SchedulePostRATDList::postprocessDAG() {
443   for (auto &M : Mutations)
444     M->apply(this);
445 }
446 
447 //===----------------------------------------------------------------------===//
448 //  Top-Down Scheduling
449 //===----------------------------------------------------------------------===//
450 
451 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
452 /// the PendingQueue if the count reaches zero.
453 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
454   SUnit *SuccSU = SuccEdge->getSUnit();
455 
456   if (SuccEdge->isWeak()) {
457     --SuccSU->WeakPredsLeft;
458     return;
459   }
460 #ifndef NDEBUG
461   if (SuccSU->NumPredsLeft == 0) {
462     dbgs() << "*** Scheduling failed! ***\n";
463     SuccSU->dump(this);
464     dbgs() << " has been released too many times!\n";
465     llvm_unreachable(nullptr);
466   }
467 #endif
468   --SuccSU->NumPredsLeft;
469 
470   // Standard scheduler algorithms will recompute the depth of the successor
471   // here as such:
472   //   SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
473   //
474   // However, we lazily compute node depth instead. Note that
475   // ScheduleNodeTopDown has already updated the depth of this node which causes
476   // all descendents to be marked dirty. Setting the successor depth explicitly
477   // here would cause depth to be recomputed for all its ancestors. If the
478   // successor is not yet ready (because of a transitively redundant edge) then
479   // this causes depth computation to be quadratic in the size of the DAG.
480 
481   // If all the node's predecessors are scheduled, this node is ready
482   // to be scheduled. Ignore the special ExitSU node.
483   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
484     PendingQueue.push_back(SuccSU);
485 }
486 
487 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
488 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
489   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
490        I != E; ++I) {
491     ReleaseSucc(SU, &*I);
492   }
493 }
494 
495 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
496 /// count of its successors. If a successor pending count is zero, add it to
497 /// the Available queue.
498 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
499   DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
500   DEBUG(SU->dump(this));
501 
502   Sequence.push_back(SU);
503   assert(CurCycle >= SU->getDepth() &&
504          "Node scheduled above its depth!");
505   SU->setDepthToAtLeast(CurCycle);
506 
507   ReleaseSuccessors(SU);
508   SU->isScheduled = true;
509   AvailableQueue.scheduledNode(SU);
510 }
511 
512 /// emitNoop - Add a noop to the current instruction sequence.
513 void SchedulePostRATDList::emitNoop(unsigned CurCycle) {
514   DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
515   HazardRec->EmitNoop();
516   Sequence.push_back(nullptr);   // NULL here means noop
517   ++NumNoops;
518 }
519 
520 /// ListScheduleTopDown - The main loop of list scheduling for top-down
521 /// schedulers.
522 void SchedulePostRATDList::ListScheduleTopDown() {
523   unsigned CurCycle = 0;
524 
525   // We're scheduling top-down but we're visiting the regions in
526   // bottom-up order, so we don't know the hazards at the start of a
527   // region. So assume no hazards (this should usually be ok as most
528   // blocks are a single region).
529   HazardRec->Reset();
530 
531   // Release any successors of the special Entry node.
532   ReleaseSuccessors(&EntrySU);
533 
534   // Add all leaves to Available queue.
535   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
536     // It is available if it has no predecessors.
537     if (!SUnits[i].NumPredsLeft && !SUnits[i].isAvailable) {
538       AvailableQueue.push(&SUnits[i]);
539       SUnits[i].isAvailable = true;
540     }
541   }
542 
543   // In any cycle where we can't schedule any instructions, we must
544   // stall or emit a noop, depending on the target.
545   bool CycleHasInsts = false;
546 
547   // While Available queue is not empty, grab the node with the highest
548   // priority. If it is not ready put it back.  Schedule the node.
549   std::vector<SUnit*> NotReady;
550   Sequence.reserve(SUnits.size());
551   while (!AvailableQueue.empty() || !PendingQueue.empty()) {
552     // Check to see if any of the pending instructions are ready to issue.  If
553     // so, add them to the available queue.
554     unsigned MinDepth = ~0u;
555     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
556       if (PendingQueue[i]->getDepth() <= CurCycle) {
557         AvailableQueue.push(PendingQueue[i]);
558         PendingQueue[i]->isAvailable = true;
559         PendingQueue[i] = PendingQueue.back();
560         PendingQueue.pop_back();
561         --i; --e;
562       } else if (PendingQueue[i]->getDepth() < MinDepth)
563         MinDepth = PendingQueue[i]->getDepth();
564     }
565 
566     DEBUG(dbgs() << "\n*** Examining Available\n"; AvailableQueue.dump(this));
567 
568     SUnit *FoundSUnit = nullptr, *NotPreferredSUnit = nullptr;
569     bool HasNoopHazards = false;
570     while (!AvailableQueue.empty()) {
571       SUnit *CurSUnit = AvailableQueue.pop();
572 
573       ScheduleHazardRecognizer::HazardType HT =
574         HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
575       if (HT == ScheduleHazardRecognizer::NoHazard) {
576         if (HazardRec->ShouldPreferAnother(CurSUnit)) {
577           if (!NotPreferredSUnit) {
578             // If this is the first non-preferred node for this cycle, then
579             // record it and continue searching for a preferred node. If this
580             // is not the first non-preferred node, then treat it as though
581             // there had been a hazard.
582             NotPreferredSUnit = CurSUnit;
583             continue;
584           }
585         } else {
586           FoundSUnit = CurSUnit;
587           break;
588         }
589       }
590 
591       // Remember if this is a noop hazard.
592       HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
593 
594       NotReady.push_back(CurSUnit);
595     }
596 
597     // If we have a non-preferred node, push it back onto the available list.
598     // If we did not find a preferred node, then schedule this first
599     // non-preferred node.
600     if (NotPreferredSUnit) {
601       if (!FoundSUnit) {
602         DEBUG(dbgs() << "*** Will schedule a non-preferred instruction...\n");
603         FoundSUnit = NotPreferredSUnit;
604       } else {
605         AvailableQueue.push(NotPreferredSUnit);
606       }
607 
608       NotPreferredSUnit = nullptr;
609     }
610 
611     // Add the nodes that aren't ready back onto the available list.
612     if (!NotReady.empty()) {
613       AvailableQueue.push_all(NotReady);
614       NotReady.clear();
615     }
616 
617     // If we found a node to schedule...
618     if (FoundSUnit) {
619       // If we need to emit noops prior to this instruction, then do so.
620       unsigned NumPreNoops = HazardRec->PreEmitNoops(FoundSUnit);
621       for (unsigned i = 0; i != NumPreNoops; ++i)
622         emitNoop(CurCycle);
623 
624       // ... schedule the node...
625       ScheduleNodeTopDown(FoundSUnit, CurCycle);
626       HazardRec->EmitInstruction(FoundSUnit);
627       CycleHasInsts = true;
628       if (HazardRec->atIssueLimit()) {
629         DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle << '\n');
630         HazardRec->AdvanceCycle();
631         ++CurCycle;
632         CycleHasInsts = false;
633       }
634     } else {
635       if (CycleHasInsts) {
636         DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
637         HazardRec->AdvanceCycle();
638       } else if (!HasNoopHazards) {
639         // Otherwise, we have a pipeline stall, but no other problem,
640         // just advance the current cycle and try again.
641         DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
642         HazardRec->AdvanceCycle();
643         ++NumStalls;
644       } else {
645         // Otherwise, we have no instructions to issue and we have instructions
646         // that will fault if we don't do this right.  This is the case for
647         // processors without pipeline interlocks and other cases.
648         emitNoop(CurCycle);
649       }
650 
651       ++CurCycle;
652       CycleHasInsts = false;
653     }
654   }
655 
656 #ifndef NDEBUG
657   unsigned ScheduledNodes = VerifyScheduledDAG(/*isBottomUp=*/false);
658   unsigned Noops = 0;
659   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
660     if (!Sequence[i])
661       ++Noops;
662   assert(Sequence.size() - Noops == ScheduledNodes &&
663          "The number of nodes scheduled doesn't match the expected number!");
664 #endif // NDEBUG
665 }
666 
667 // EmitSchedule - Emit the machine code in scheduled order.
668 void SchedulePostRATDList::EmitSchedule() {
669   RegionBegin = RegionEnd;
670 
671   // If first instruction was a DBG_VALUE then put it back.
672   if (FirstDbgValue)
673     BB->splice(RegionEnd, BB, FirstDbgValue);
674 
675   // Then re-insert them according to the given schedule.
676   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
677     if (SUnit *SU = Sequence[i])
678       BB->splice(RegionEnd, BB, SU->getInstr());
679     else
680       // Null SUnit* is a noop.
681       TII->insertNoop(*BB, RegionEnd);
682 
683     // Update the Begin iterator, as the first instruction in the block
684     // may have been scheduled later.
685     if (i == 0)
686       RegionBegin = std::prev(RegionEnd);
687   }
688 
689   // Reinsert any remaining debug_values.
690   for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
691          DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
692     std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
693     MachineInstr *DbgValue = P.first;
694     MachineBasicBlock::iterator OrigPrivMI = P.second;
695     BB->splice(++OrigPrivMI, BB, DbgValue);
696   }
697   DbgValues.clear();
698   FirstDbgValue = nullptr;
699 }
700