xref: /llvm-project/llvm/lib/CodeGen/MachineScheduler.cpp (revision 49cb6e909d71bd52a0c78b0baa21e3f73d09f632)
1 //===- MachineScheduler.cpp - Machine Instruction 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 // MachineScheduler schedules machine instructions after phi elimination. It
11 // preserves LiveIntervals so it can be invoked before register allocation.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/MachineScheduler.h"
16 #include "llvm/ADT/PriorityQueue.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineLoopInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegisterClassInfo.h"
24 #include "llvm/CodeGen/ScheduleDFS.h"
25 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/GraphWriter.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 
34 using namespace llvm;
35 
36 #define DEBUG_TYPE "misched"
37 
38 namespace llvm {
39 cl::opt<bool> ForceTopDown("misched-topdown", cl::Hidden,
40                            cl::desc("Force top-down list scheduling"));
41 cl::opt<bool> ForceBottomUp("misched-bottomup", cl::Hidden,
42                             cl::desc("Force bottom-up list scheduling"));
43 cl::opt<bool>
44 DumpCriticalPathLength("misched-dcpl", cl::Hidden,
45                        cl::desc("Print critical path length to stdout"));
46 }
47 
48 #ifndef NDEBUG
49 static cl::opt<bool> ViewMISchedDAGs("view-misched-dags", cl::Hidden,
50   cl::desc("Pop up a window to show MISched dags after they are processed"));
51 
52 /// In some situations a few uninteresting nodes depend on nearly all other
53 /// nodes in the graph, provide a cutoff to hide them.
54 static cl::opt<unsigned> ViewMISchedCutoff("view-misched-cutoff", cl::Hidden,
55   cl::desc("Hide nodes with more predecessor/successor than cutoff"));
56 
57 static cl::opt<unsigned> MISchedCutoff("misched-cutoff", cl::Hidden,
58   cl::desc("Stop scheduling after N instructions"), cl::init(~0U));
59 
60 static cl::opt<std::string> SchedOnlyFunc("misched-only-func", cl::Hidden,
61   cl::desc("Only schedule this function"));
62 static cl::opt<unsigned> SchedOnlyBlock("misched-only-block", cl::Hidden,
63   cl::desc("Only schedule this MBB#"));
64 #else
65 static bool ViewMISchedDAGs = false;
66 #endif // NDEBUG
67 
68 /// Avoid quadratic complexity in unusually large basic blocks by limiting the
69 /// size of the ready lists.
70 static cl::opt<unsigned> ReadyListLimit("misched-limit", cl::Hidden,
71   cl::desc("Limit ready list to N instructions"), cl::init(256));
72 
73 static cl::opt<bool> EnableRegPressure("misched-regpressure", cl::Hidden,
74   cl::desc("Enable register pressure scheduling."), cl::init(true));
75 
76 static cl::opt<bool> EnableCyclicPath("misched-cyclicpath", cl::Hidden,
77   cl::desc("Enable cyclic critical path analysis."), cl::init(true));
78 
79 static cl::opt<bool> EnableMemOpCluster("misched-cluster", cl::Hidden,
80                                         cl::desc("Enable memop clustering."),
81                                         cl::init(true));
82 
83 // Experimental heuristics
84 static cl::opt<bool> EnableMacroFusion("misched-fusion", cl::Hidden,
85   cl::desc("Enable scheduling for macro fusion."), cl::init(true));
86 
87 static cl::opt<bool> VerifyScheduling("verify-misched", cl::Hidden,
88   cl::desc("Verify machine instrs before and after machine scheduling"));
89 
90 // DAG subtrees must have at least this many nodes.
91 static const unsigned MinSubtreeSize = 8;
92 
93 // Pin the vtables to this file.
94 void MachineSchedStrategy::anchor() {}
95 void ScheduleDAGMutation::anchor() {}
96 
97 //===----------------------------------------------------------------------===//
98 // Machine Instruction Scheduling Pass and Registry
99 //===----------------------------------------------------------------------===//
100 
101 MachineSchedContext::MachineSchedContext():
102     MF(nullptr), MLI(nullptr), MDT(nullptr), PassConfig(nullptr), AA(nullptr), LIS(nullptr) {
103   RegClassInfo = new RegisterClassInfo();
104 }
105 
106 MachineSchedContext::~MachineSchedContext() {
107   delete RegClassInfo;
108 }
109 
110 namespace {
111 /// Base class for a machine scheduler class that can run at any point.
112 class MachineSchedulerBase : public MachineSchedContext,
113                              public MachineFunctionPass {
114 public:
115   MachineSchedulerBase(char &ID): MachineFunctionPass(ID) {}
116 
117   void print(raw_ostream &O, const Module* = nullptr) const override;
118 
119 protected:
120   void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
121 };
122 
123 /// MachineScheduler runs after coalescing and before register allocation.
124 class MachineScheduler : public MachineSchedulerBase {
125 public:
126   MachineScheduler();
127 
128   void getAnalysisUsage(AnalysisUsage &AU) const override;
129 
130   bool runOnMachineFunction(MachineFunction&) override;
131 
132   static char ID; // Class identification, replacement for typeinfo
133 
134 protected:
135   ScheduleDAGInstrs *createMachineScheduler();
136 };
137 
138 /// PostMachineScheduler runs after shortly before code emission.
139 class PostMachineScheduler : public MachineSchedulerBase {
140 public:
141   PostMachineScheduler();
142 
143   void getAnalysisUsage(AnalysisUsage &AU) const override;
144 
145   bool runOnMachineFunction(MachineFunction&) override;
146 
147   static char ID; // Class identification, replacement for typeinfo
148 
149 protected:
150   ScheduleDAGInstrs *createPostMachineScheduler();
151 };
152 } // namespace
153 
154 char MachineScheduler::ID = 0;
155 
156 char &llvm::MachineSchedulerID = MachineScheduler::ID;
157 
158 INITIALIZE_PASS_BEGIN(MachineScheduler, "machine-scheduler",
159                       "Machine Instruction Scheduler", false, false)
160 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
161 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
162 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
163 INITIALIZE_PASS_END(MachineScheduler, "machine-scheduler",
164                     "Machine Instruction Scheduler", false, false)
165 
166 MachineScheduler::MachineScheduler()
167 : MachineSchedulerBase(ID) {
168   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
169 }
170 
171 void MachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
172   AU.setPreservesCFG();
173   AU.addRequiredID(MachineDominatorsID);
174   AU.addRequired<MachineLoopInfo>();
175   AU.addRequired<AAResultsWrapperPass>();
176   AU.addRequired<TargetPassConfig>();
177   AU.addRequired<SlotIndexes>();
178   AU.addPreserved<SlotIndexes>();
179   AU.addRequired<LiveIntervals>();
180   AU.addPreserved<LiveIntervals>();
181   MachineFunctionPass::getAnalysisUsage(AU);
182 }
183 
184 char PostMachineScheduler::ID = 0;
185 
186 char &llvm::PostMachineSchedulerID = PostMachineScheduler::ID;
187 
188 INITIALIZE_PASS(PostMachineScheduler, "postmisched",
189                 "PostRA Machine Instruction Scheduler", false, false)
190 
191 PostMachineScheduler::PostMachineScheduler()
192 : MachineSchedulerBase(ID) {
193   initializePostMachineSchedulerPass(*PassRegistry::getPassRegistry());
194 }
195 
196 void PostMachineScheduler::getAnalysisUsage(AnalysisUsage &AU) const {
197   AU.setPreservesCFG();
198   AU.addRequiredID(MachineDominatorsID);
199   AU.addRequired<MachineLoopInfo>();
200   AU.addRequired<TargetPassConfig>();
201   MachineFunctionPass::getAnalysisUsage(AU);
202 }
203 
204 MachinePassRegistry MachineSchedRegistry::Registry;
205 
206 /// A dummy default scheduler factory indicates whether the scheduler
207 /// is overridden on the command line.
208 static ScheduleDAGInstrs *useDefaultMachineSched(MachineSchedContext *C) {
209   return nullptr;
210 }
211 
212 /// MachineSchedOpt allows command line selection of the scheduler.
213 static cl::opt<MachineSchedRegistry::ScheduleDAGCtor, false,
214                RegisterPassParser<MachineSchedRegistry> >
215 MachineSchedOpt("misched",
216                 cl::init(&useDefaultMachineSched), cl::Hidden,
217                 cl::desc("Machine instruction scheduler to use"));
218 
219 static MachineSchedRegistry
220 DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
221                      useDefaultMachineSched);
222 
223 static cl::opt<bool> EnableMachineSched(
224     "enable-misched",
225     cl::desc("Enable the machine instruction scheduling pass."), cl::init(true),
226     cl::Hidden);
227 
228 static cl::opt<bool> EnablePostRAMachineSched(
229     "enable-post-misched",
230     cl::desc("Enable the post-ra machine instruction scheduling pass."),
231     cl::init(true), cl::Hidden);
232 
233 /// Forward declare the standard machine scheduler. This will be used as the
234 /// default scheduler if the target does not set a default.
235 static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C);
236 static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C);
237 
238 /// Decrement this iterator until reaching the top or a non-debug instr.
239 static MachineBasicBlock::const_iterator
240 priorNonDebug(MachineBasicBlock::const_iterator I,
241               MachineBasicBlock::const_iterator Beg) {
242   assert(I != Beg && "reached the top of the region, cannot decrement");
243   while (--I != Beg) {
244     if (!I->isDebugValue())
245       break;
246   }
247   return I;
248 }
249 
250 /// Non-const version.
251 static MachineBasicBlock::iterator
252 priorNonDebug(MachineBasicBlock::iterator I,
253               MachineBasicBlock::const_iterator Beg) {
254   return const_cast<MachineInstr*>(
255     &*priorNonDebug(MachineBasicBlock::const_iterator(I), Beg));
256 }
257 
258 /// If this iterator is a debug value, increment until reaching the End or a
259 /// non-debug instruction.
260 static MachineBasicBlock::const_iterator
261 nextIfDebug(MachineBasicBlock::const_iterator I,
262             MachineBasicBlock::const_iterator End) {
263   for(; I != End; ++I) {
264     if (!I->isDebugValue())
265       break;
266   }
267   return I;
268 }
269 
270 /// Non-const version.
271 static MachineBasicBlock::iterator
272 nextIfDebug(MachineBasicBlock::iterator I,
273             MachineBasicBlock::const_iterator End) {
274   // Cast the return value to nonconst MachineInstr, then cast to an
275   // instr_iterator, which does not check for null, finally return a
276   // bundle_iterator.
277   return MachineBasicBlock::instr_iterator(
278     const_cast<MachineInstr*>(
279       &*nextIfDebug(MachineBasicBlock::const_iterator(I), End)));
280 }
281 
282 /// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
283 ScheduleDAGInstrs *MachineScheduler::createMachineScheduler() {
284   // Select the scheduler, or set the default.
285   MachineSchedRegistry::ScheduleDAGCtor Ctor = MachineSchedOpt;
286   if (Ctor != useDefaultMachineSched)
287     return Ctor(this);
288 
289   // Get the default scheduler set by the target for this function.
290   ScheduleDAGInstrs *Scheduler = PassConfig->createMachineScheduler(this);
291   if (Scheduler)
292     return Scheduler;
293 
294   // Default to GenericScheduler.
295   return createGenericSchedLive(this);
296 }
297 
298 /// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
299 /// the caller. We don't have a command line option to override the postRA
300 /// scheduler. The Target must configure it.
301 ScheduleDAGInstrs *PostMachineScheduler::createPostMachineScheduler() {
302   // Get the postRA scheduler set by the target for this function.
303   ScheduleDAGInstrs *Scheduler = PassConfig->createPostMachineScheduler(this);
304   if (Scheduler)
305     return Scheduler;
306 
307   // Default to GenericScheduler.
308   return createGenericSchedPostRA(this);
309 }
310 
311 /// Top-level MachineScheduler pass driver.
312 ///
313 /// Visit blocks in function order. Divide each block into scheduling regions
314 /// and visit them bottom-up. Visiting regions bottom-up is not required, but is
315 /// consistent with the DAG builder, which traverses the interior of the
316 /// scheduling regions bottom-up.
317 ///
318 /// This design avoids exposing scheduling boundaries to the DAG builder,
319 /// simplifying the DAG builder's support for "special" target instructions.
320 /// At the same time the design allows target schedulers to operate across
321 /// scheduling boundaries, for example to bundle the boudary instructions
322 /// without reordering them. This creates complexity, because the target
323 /// scheduler must update the RegionBegin and RegionEnd positions cached by
324 /// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
325 /// design would be to split blocks at scheduling boundaries, but LLVM has a
326 /// general bias against block splitting purely for implementation simplicity.
327 bool MachineScheduler::runOnMachineFunction(MachineFunction &mf) {
328   if (skipFunction(*mf.getFunction()))
329     return false;
330 
331   if (EnableMachineSched.getNumOccurrences()) {
332     if (!EnableMachineSched)
333       return false;
334   } else if (!mf.getSubtarget().enableMachineScheduler())
335     return false;
336 
337   DEBUG(dbgs() << "Before MISched:\n"; mf.print(dbgs()));
338 
339   // Initialize the context of the pass.
340   MF = &mf;
341   MLI = &getAnalysis<MachineLoopInfo>();
342   MDT = &getAnalysis<MachineDominatorTree>();
343   PassConfig = &getAnalysis<TargetPassConfig>();
344   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
345 
346   LIS = &getAnalysis<LiveIntervals>();
347 
348   if (VerifyScheduling) {
349     DEBUG(LIS->dump());
350     MF->verify(this, "Before machine scheduling.");
351   }
352   RegClassInfo->runOnMachineFunction(*MF);
353 
354   // Instantiate the selected scheduler for this target, function, and
355   // optimization level.
356   std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
357   scheduleRegions(*Scheduler, false);
358 
359   DEBUG(LIS->dump());
360   if (VerifyScheduling)
361     MF->verify(this, "After machine scheduling.");
362   return true;
363 }
364 
365 bool PostMachineScheduler::runOnMachineFunction(MachineFunction &mf) {
366   if (skipFunction(*mf.getFunction()))
367     return false;
368 
369   if (EnablePostRAMachineSched.getNumOccurrences()) {
370     if (!EnablePostRAMachineSched)
371       return false;
372   } else if (!mf.getSubtarget().enablePostRAScheduler()) {
373     DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
374     return false;
375   }
376   DEBUG(dbgs() << "Before post-MI-sched:\n"; mf.print(dbgs()));
377 
378   // Initialize the context of the pass.
379   MF = &mf;
380   PassConfig = &getAnalysis<TargetPassConfig>();
381 
382   if (VerifyScheduling)
383     MF->verify(this, "Before post machine scheduling.");
384 
385   // Instantiate the selected scheduler for this target, function, and
386   // optimization level.
387   std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
388   scheduleRegions(*Scheduler, true);
389 
390   if (VerifyScheduling)
391     MF->verify(this, "After post machine scheduling.");
392   return true;
393 }
394 
395 /// Return true of the given instruction should not be included in a scheduling
396 /// region.
397 ///
398 /// MachineScheduler does not currently support scheduling across calls. To
399 /// handle calls, the DAG builder needs to be modified to create register
400 /// anti/output dependencies on the registers clobbered by the call's regmask
401 /// operand. In PreRA scheduling, the stack pointer adjustment already prevents
402 /// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
403 /// the boundary, but there would be no benefit to postRA scheduling across
404 /// calls this late anyway.
405 static bool isSchedBoundary(MachineBasicBlock::iterator MI,
406                             MachineBasicBlock *MBB,
407                             MachineFunction *MF,
408                             const TargetInstrInfo *TII) {
409   return MI->isCall() || TII->isSchedulingBoundary(MI, MBB, *MF);
410 }
411 
412 /// Main driver for both MachineScheduler and PostMachineScheduler.
413 void MachineSchedulerBase::scheduleRegions(ScheduleDAGInstrs &Scheduler,
414                                            bool FixKillFlags) {
415   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
416 
417   // Visit all machine basic blocks.
418   //
419   // TODO: Visit blocks in global postorder or postorder within the bottom-up
420   // loop tree. Then we can optionally compute global RegPressure.
421   for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
422        MBB != MBBEnd; ++MBB) {
423 
424     Scheduler.startBlock(&*MBB);
425 
426 #ifndef NDEBUG
427     if (SchedOnlyFunc.getNumOccurrences() && SchedOnlyFunc != MF->getName())
428       continue;
429     if (SchedOnlyBlock.getNumOccurrences()
430         && (int)SchedOnlyBlock != MBB->getNumber())
431       continue;
432 #endif
433 
434     // Break the block into scheduling regions [I, RegionEnd), and schedule each
435     // region as soon as it is discovered. RegionEnd points the scheduling
436     // boundary at the bottom of the region. The DAG does not include RegionEnd,
437     // but the region does (i.e. the next RegionEnd is above the previous
438     // RegionBegin). If the current block has no terminator then RegionEnd ==
439     // MBB->end() for the bottom region.
440     //
441     // The Scheduler may insert instructions during either schedule() or
442     // exitRegion(), even for empty regions. So the local iterators 'I' and
443     // 'RegionEnd' are invalid across these calls.
444     //
445     // MBB::size() uses instr_iterator to count. Here we need a bundle to count
446     // as a single instruction.
447     for(MachineBasicBlock::iterator RegionEnd = MBB->end();
448         RegionEnd != MBB->begin(); RegionEnd = Scheduler.begin()) {
449 
450       // Avoid decrementing RegionEnd for blocks with no terminator.
451       if (RegionEnd != MBB->end() ||
452           isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
453         --RegionEnd;
454       }
455 
456       // The next region starts above the previous region. Look backward in the
457       // instruction stream until we find the nearest boundary.
458       unsigned NumRegionInstrs = 0;
459       MachineBasicBlock::iterator I = RegionEnd;
460       for (;I != MBB->begin(); --I) {
461         if (isSchedBoundary(&*std::prev(I), &*MBB, MF, TII))
462           break;
463         if (!I->isDebugValue())
464           ++NumRegionInstrs;
465       }
466       // Notify the scheduler of the region, even if we may skip scheduling
467       // it. Perhaps it still needs to be bundled.
468       Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
469 
470       // Skip empty scheduling regions (0 or 1 schedulable instructions).
471       if (I == RegionEnd || I == std::prev(RegionEnd)) {
472         // Close the current region. Bundle the terminator if needed.
473         // This invalidates 'RegionEnd' and 'I'.
474         Scheduler.exitRegion();
475         continue;
476       }
477       DEBUG(dbgs() << "********** MI Scheduling **********\n");
478       DEBUG(dbgs() << MF->getName()
479             << ":BB#" << MBB->getNumber() << " " << MBB->getName()
480             << "\n  From: " << *I << "    To: ";
481             if (RegionEnd != MBB->end()) dbgs() << *RegionEnd;
482             else dbgs() << "End";
483             dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n');
484       if (DumpCriticalPathLength) {
485         errs() << MF->getName();
486         errs() << ":BB# " << MBB->getNumber();
487         errs() << " " << MBB->getName() << " \n";
488       }
489 
490       // Schedule a region: possibly reorder instructions.
491       // This invalidates 'RegionEnd' and 'I'.
492       Scheduler.schedule();
493 
494       // Close the current region.
495       Scheduler.exitRegion();
496 
497       // Scheduling has invalidated the current iterator 'I'. Ask the
498       // scheduler for the top of it's scheduled region.
499       RegionEnd = Scheduler.begin();
500     }
501     Scheduler.finishBlock();
502     // FIXME: Ideally, no further passes should rely on kill flags. However,
503     // thumb2 size reduction is currently an exception, so the PostMIScheduler
504     // needs to do this.
505     if (FixKillFlags)
506         Scheduler.fixupKills(&*MBB);
507   }
508   Scheduler.finalizeSchedule();
509 }
510 
511 void MachineSchedulerBase::print(raw_ostream &O, const Module* m) const {
512   // unimplemented
513 }
514 
515 LLVM_DUMP_METHOD
516 void ReadyQueue::dump() {
517   dbgs() << "Queue " << Name << ": ";
518   for (unsigned i = 0, e = Queue.size(); i < e; ++i)
519     dbgs() << Queue[i]->NodeNum << " ";
520   dbgs() << "\n";
521 }
522 
523 //===----------------------------------------------------------------------===//
524 // ScheduleDAGMI - Basic machine instruction scheduling. This is
525 // independent of PreRA/PostRA scheduling and involves no extra book-keeping for
526 // virtual registers.
527 // ===----------------------------------------------------------------------===/
528 
529 // Provide a vtable anchor.
530 ScheduleDAGMI::~ScheduleDAGMI() {
531 }
532 
533 bool ScheduleDAGMI::canAddEdge(SUnit *SuccSU, SUnit *PredSU) {
534   return SuccSU == &ExitSU || !Topo.IsReachable(PredSU, SuccSU);
535 }
536 
537 bool ScheduleDAGMI::addEdge(SUnit *SuccSU, const SDep &PredDep) {
538   if (SuccSU != &ExitSU) {
539     // Do not use WillCreateCycle, it assumes SD scheduling.
540     // If Pred is reachable from Succ, then the edge creates a cycle.
541     if (Topo.IsReachable(PredDep.getSUnit(), SuccSU))
542       return false;
543     Topo.AddPred(SuccSU, PredDep.getSUnit());
544   }
545   SuccSU->addPred(PredDep, /*Required=*/!PredDep.isArtificial());
546   // Return true regardless of whether a new edge needed to be inserted.
547   return true;
548 }
549 
550 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
551 /// NumPredsLeft reaches zero, release the successor node.
552 ///
553 /// FIXME: Adjust SuccSU height based on MinLatency.
554 void ScheduleDAGMI::releaseSucc(SUnit *SU, SDep *SuccEdge) {
555   SUnit *SuccSU = SuccEdge->getSUnit();
556 
557   if (SuccEdge->isWeak()) {
558     --SuccSU->WeakPredsLeft;
559     if (SuccEdge->isCluster())
560       NextClusterSucc = SuccSU;
561     return;
562   }
563 #ifndef NDEBUG
564   if (SuccSU->NumPredsLeft == 0) {
565     dbgs() << "*** Scheduling failed! ***\n";
566     SuccSU->dump(this);
567     dbgs() << " has been released too many times!\n";
568     llvm_unreachable(nullptr);
569   }
570 #endif
571   // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
572   // CurrCycle may have advanced since then.
573   if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
574     SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
575 
576   --SuccSU->NumPredsLeft;
577   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
578     SchedImpl->releaseTopNode(SuccSU);
579 }
580 
581 /// releaseSuccessors - Call releaseSucc on each of SU's successors.
582 void ScheduleDAGMI::releaseSuccessors(SUnit *SU) {
583   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
584        I != E; ++I) {
585     releaseSucc(SU, &*I);
586   }
587 }
588 
589 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
590 /// NumSuccsLeft reaches zero, release the predecessor node.
591 ///
592 /// FIXME: Adjust PredSU height based on MinLatency.
593 void ScheduleDAGMI::releasePred(SUnit *SU, SDep *PredEdge) {
594   SUnit *PredSU = PredEdge->getSUnit();
595 
596   if (PredEdge->isWeak()) {
597     --PredSU->WeakSuccsLeft;
598     if (PredEdge->isCluster())
599       NextClusterPred = PredSU;
600     return;
601   }
602 #ifndef NDEBUG
603   if (PredSU->NumSuccsLeft == 0) {
604     dbgs() << "*** Scheduling failed! ***\n";
605     PredSU->dump(this);
606     dbgs() << " has been released too many times!\n";
607     llvm_unreachable(nullptr);
608   }
609 #endif
610   // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
611   // CurrCycle may have advanced since then.
612   if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
613     PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
614 
615   --PredSU->NumSuccsLeft;
616   if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
617     SchedImpl->releaseBottomNode(PredSU);
618 }
619 
620 /// releasePredecessors - Call releasePred on each of SU's predecessors.
621 void ScheduleDAGMI::releasePredecessors(SUnit *SU) {
622   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
623        I != E; ++I) {
624     releasePred(SU, &*I);
625   }
626 }
627 
628 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
629 /// crossing a scheduling boundary. [begin, end) includes all instructions in
630 /// the region, including the boundary itself and single-instruction regions
631 /// that don't get scheduled.
632 void ScheduleDAGMI::enterRegion(MachineBasicBlock *bb,
633                                      MachineBasicBlock::iterator begin,
634                                      MachineBasicBlock::iterator end,
635                                      unsigned regioninstrs)
636 {
637   ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
638 
639   SchedImpl->initPolicy(begin, end, regioninstrs);
640 }
641 
642 /// This is normally called from the main scheduler loop but may also be invoked
643 /// by the scheduling strategy to perform additional code motion.
644 void ScheduleDAGMI::moveInstruction(
645   MachineInstr *MI, MachineBasicBlock::iterator InsertPos) {
646   // Advance RegionBegin if the first instruction moves down.
647   if (&*RegionBegin == MI)
648     ++RegionBegin;
649 
650   // Update the instruction stream.
651   BB->splice(InsertPos, BB, MI);
652 
653   // Update LiveIntervals
654   if (LIS)
655     LIS->handleMove(*MI, /*UpdateFlags=*/true);
656 
657   // Recede RegionBegin if an instruction moves above the first.
658   if (RegionBegin == InsertPos)
659     RegionBegin = MI;
660 }
661 
662 bool ScheduleDAGMI::checkSchedLimit() {
663 #ifndef NDEBUG
664   if (NumInstrsScheduled == MISchedCutoff && MISchedCutoff != ~0U) {
665     CurrentTop = CurrentBottom;
666     return false;
667   }
668   ++NumInstrsScheduled;
669 #endif
670   return true;
671 }
672 
673 /// Per-region scheduling driver, called back from
674 /// MachineScheduler::runOnMachineFunction. This is a simplified driver that
675 /// does not consider liveness or register pressure. It is useful for PostRA
676 /// scheduling and potentially other custom schedulers.
677 void ScheduleDAGMI::schedule() {
678   DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
679   DEBUG(SchedImpl->dumpPolicy());
680 
681   // Build the DAG.
682   buildSchedGraph(AA);
683 
684   Topo.InitDAGTopologicalSorting();
685 
686   postprocessDAG();
687 
688   SmallVector<SUnit*, 8> TopRoots, BotRoots;
689   findRootsAndBiasEdges(TopRoots, BotRoots);
690 
691   // Initialize the strategy before modifying the DAG.
692   // This may initialize a DFSResult to be used for queue priority.
693   SchedImpl->initialize(this);
694 
695   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
696           SUnits[su].dumpAll(this));
697   if (ViewMISchedDAGs) viewGraph();
698 
699   // Initialize ready queues now that the DAG and priority data are finalized.
700   initQueues(TopRoots, BotRoots);
701 
702   bool IsTopNode = false;
703   while (true) {
704     DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
705     SUnit *SU = SchedImpl->pickNode(IsTopNode);
706     if (!SU) break;
707 
708     assert(!SU->isScheduled && "Node already scheduled");
709     if (!checkSchedLimit())
710       break;
711 
712     MachineInstr *MI = SU->getInstr();
713     if (IsTopNode) {
714       assert(SU->isTopReady() && "node still has unscheduled dependencies");
715       if (&*CurrentTop == MI)
716         CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
717       else
718         moveInstruction(MI, CurrentTop);
719     } else {
720       assert(SU->isBottomReady() && "node still has unscheduled dependencies");
721       MachineBasicBlock::iterator priorII =
722         priorNonDebug(CurrentBottom, CurrentTop);
723       if (&*priorII == MI)
724         CurrentBottom = priorII;
725       else {
726         if (&*CurrentTop == MI)
727           CurrentTop = nextIfDebug(++CurrentTop, priorII);
728         moveInstruction(MI, CurrentBottom);
729         CurrentBottom = MI;
730       }
731     }
732     // Notify the scheduling strategy before updating the DAG.
733     // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
734     // runs, it can then use the accurate ReadyCycle time to determine whether
735     // newly released nodes can move to the readyQ.
736     SchedImpl->schedNode(SU, IsTopNode);
737 
738     updateQueues(SU, IsTopNode);
739   }
740   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
741 
742   placeDebugValues();
743 
744   DEBUG({
745       unsigned BBNum = begin()->getParent()->getNumber();
746       dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
747       dumpSchedule();
748       dbgs() << '\n';
749     });
750 }
751 
752 /// Apply each ScheduleDAGMutation step in order.
753 void ScheduleDAGMI::postprocessDAG() {
754   for (unsigned i = 0, e = Mutations.size(); i < e; ++i) {
755     Mutations[i]->apply(this);
756   }
757 }
758 
759 void ScheduleDAGMI::
760 findRootsAndBiasEdges(SmallVectorImpl<SUnit*> &TopRoots,
761                       SmallVectorImpl<SUnit*> &BotRoots) {
762   for (std::vector<SUnit>::iterator
763          I = SUnits.begin(), E = SUnits.end(); I != E; ++I) {
764     SUnit *SU = &(*I);
765     assert(!SU->isBoundaryNode() && "Boundary node should not be in SUnits");
766 
767     // Order predecessors so DFSResult follows the critical path.
768     SU->biasCriticalPath();
769 
770     // A SUnit is ready to top schedule if it has no predecessors.
771     if (!I->NumPredsLeft)
772       TopRoots.push_back(SU);
773     // A SUnit is ready to bottom schedule if it has no successors.
774     if (!I->NumSuccsLeft)
775       BotRoots.push_back(SU);
776   }
777   ExitSU.biasCriticalPath();
778 }
779 
780 /// Identify DAG roots and setup scheduler queues.
781 void ScheduleDAGMI::initQueues(ArrayRef<SUnit*> TopRoots,
782                                ArrayRef<SUnit*> BotRoots) {
783   NextClusterSucc = nullptr;
784   NextClusterPred = nullptr;
785 
786   // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
787   //
788   // Nodes with unreleased weak edges can still be roots.
789   // Release top roots in forward order.
790   for (SmallVectorImpl<SUnit*>::const_iterator
791          I = TopRoots.begin(), E = TopRoots.end(); I != E; ++I) {
792     SchedImpl->releaseTopNode(*I);
793   }
794   // Release bottom roots in reverse order so the higher priority nodes appear
795   // first. This is more natural and slightly more efficient.
796   for (SmallVectorImpl<SUnit*>::const_reverse_iterator
797          I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
798     SchedImpl->releaseBottomNode(*I);
799   }
800 
801   releaseSuccessors(&EntrySU);
802   releasePredecessors(&ExitSU);
803 
804   SchedImpl->registerRoots();
805 
806   // Advance past initial DebugValues.
807   CurrentTop = nextIfDebug(RegionBegin, RegionEnd);
808   CurrentBottom = RegionEnd;
809 }
810 
811 /// Update scheduler queues after scheduling an instruction.
812 void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
813   // Release dependent instructions for scheduling.
814   if (IsTopNode)
815     releaseSuccessors(SU);
816   else
817     releasePredecessors(SU);
818 
819   SU->isScheduled = true;
820 }
821 
822 /// Reinsert any remaining debug_values, just like the PostRA scheduler.
823 void ScheduleDAGMI::placeDebugValues() {
824   // If first instruction was a DBG_VALUE then put it back.
825   if (FirstDbgValue) {
826     BB->splice(RegionBegin, BB, FirstDbgValue);
827     RegionBegin = FirstDbgValue;
828   }
829 
830   for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
831          DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
832     std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
833     MachineInstr *DbgValue = P.first;
834     MachineBasicBlock::iterator OrigPrevMI = P.second;
835     if (&*RegionBegin == DbgValue)
836       ++RegionBegin;
837     BB->splice(++OrigPrevMI, BB, DbgValue);
838     if (OrigPrevMI == std::prev(RegionEnd))
839       RegionEnd = DbgValue;
840   }
841   DbgValues.clear();
842   FirstDbgValue = nullptr;
843 }
844 
845 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
846 void ScheduleDAGMI::dumpSchedule() const {
847   for (MachineBasicBlock::iterator MI = begin(), ME = end(); MI != ME; ++MI) {
848     if (SUnit *SU = getSUnit(&(*MI)))
849       SU->dump(this);
850     else
851       dbgs() << "Missing SUnit\n";
852   }
853 }
854 #endif
855 
856 //===----------------------------------------------------------------------===//
857 // ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
858 // preservation.
859 //===----------------------------------------------------------------------===//
860 
861 ScheduleDAGMILive::~ScheduleDAGMILive() {
862   delete DFSResult;
863 }
864 
865 /// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
866 /// crossing a scheduling boundary. [begin, end) includes all instructions in
867 /// the region, including the boundary itself and single-instruction regions
868 /// that don't get scheduled.
869 void ScheduleDAGMILive::enterRegion(MachineBasicBlock *bb,
870                                 MachineBasicBlock::iterator begin,
871                                 MachineBasicBlock::iterator end,
872                                 unsigned regioninstrs)
873 {
874   // ScheduleDAGMI initializes SchedImpl's per-region policy.
875   ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
876 
877   // For convenience remember the end of the liveness region.
878   LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
879 
880   SUPressureDiffs.clear();
881 
882   ShouldTrackPressure = SchedImpl->shouldTrackPressure();
883   ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
884 
885   if (ShouldTrackLaneMasks) {
886     if (!ShouldTrackPressure)
887       report_fatal_error("ShouldTrackLaneMasks requires ShouldTrackPressure");
888     // Dead subregister defs have no users and therefore no dependencies,
889     // moving them around may cause liveintervals to degrade into multiple
890     // components. Change independent components to have their own vreg to avoid
891     // this.
892     if (!DisconnectedComponentsRenamed)
893       LIS->renameDisconnectedComponents();
894   }
895 }
896 
897 // Setup the register pressure trackers for the top scheduled top and bottom
898 // scheduled regions.
899 void ScheduleDAGMILive::initRegPressure() {
900   TopRPTracker.init(&MF, RegClassInfo, LIS, BB, RegionBegin,
901                     ShouldTrackLaneMasks, false);
902   BotRPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
903                     ShouldTrackLaneMasks, false);
904 
905   // Close the RPTracker to finalize live ins.
906   RPTracker.closeRegion();
907 
908   DEBUG(RPTracker.dump());
909 
910   // Initialize the live ins and live outs.
911   TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
912   BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
913 
914   // Close one end of the tracker so we can call
915   // getMaxUpward/DownwardPressureDelta before advancing across any
916   // instructions. This converts currently live regs into live ins/outs.
917   TopRPTracker.closeTop();
918   BotRPTracker.closeBottom();
919 
920   BotRPTracker.initLiveThru(RPTracker);
921   if (!BotRPTracker.getLiveThru().empty()) {
922     TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
923     DEBUG(dbgs() << "Live Thru: ";
924           dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
925   };
926 
927   // For each live out vreg reduce the pressure change associated with other
928   // uses of the same vreg below the live-out reaching def.
929   updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
930 
931   // Account for liveness generated by the region boundary.
932   if (LiveRegionEnd != RegionEnd) {
933     SmallVector<RegisterMaskPair, 8> LiveUses;
934     BotRPTracker.recede(&LiveUses);
935     updatePressureDiffs(LiveUses);
936   }
937 
938   DEBUG(
939     dbgs() << "Top Pressure:\n";
940     dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
941     dbgs() << "Bottom Pressure:\n";
942     dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
943   );
944 
945   assert(BotRPTracker.getPos() == RegionEnd && "Can't find the region bottom");
946 
947   // Cache the list of excess pressure sets in this region. This will also track
948   // the max pressure in the scheduled code for these sets.
949   RegionCriticalPSets.clear();
950   const std::vector<unsigned> &RegionPressure =
951     RPTracker.getPressure().MaxSetPressure;
952   for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
953     unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
954     if (RegionPressure[i] > Limit) {
955       DEBUG(dbgs() << TRI->getRegPressureSetName(i)
956             << " Limit " << Limit
957             << " Actual " << RegionPressure[i] << "\n");
958       RegionCriticalPSets.push_back(PressureChange(i));
959     }
960   }
961   DEBUG(dbgs() << "Excess PSets: ";
962         for (unsigned i = 0, e = RegionCriticalPSets.size(); i != e; ++i)
963           dbgs() << TRI->getRegPressureSetName(
964             RegionCriticalPSets[i].getPSet()) << " ";
965         dbgs() << "\n");
966 }
967 
968 void ScheduleDAGMILive::
969 updateScheduledPressure(const SUnit *SU,
970                         const std::vector<unsigned> &NewMaxPressure) {
971   const PressureDiff &PDiff = getPressureDiff(SU);
972   unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
973   for (PressureDiff::const_iterator I = PDiff.begin(), E = PDiff.end();
974        I != E; ++I) {
975     if (!I->isValid())
976       break;
977     unsigned ID = I->getPSet();
978     while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
979       ++CritIdx;
980     if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
981       if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
982           && NewMaxPressure[ID] <= INT16_MAX)
983         RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
984     }
985     unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
986     if (NewMaxPressure[ID] >= Limit - 2) {
987       DEBUG(dbgs() << "  " << TRI->getRegPressureSetName(ID) << ": "
988             << NewMaxPressure[ID]
989             << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ") << Limit
990             << "(+ " << BotRPTracker.getLiveThru()[ID] << " livethru)\n");
991     }
992   }
993 }
994 
995 /// Update the PressureDiff array for liveness after scheduling this
996 /// instruction.
997 void ScheduleDAGMILive::updatePressureDiffs(
998     ArrayRef<RegisterMaskPair> LiveUses) {
999   for (const RegisterMaskPair &P : LiveUses) {
1000     unsigned Reg = P.RegUnit;
1001     /// FIXME: Currently assuming single-use physregs.
1002     if (!TRI->isVirtualRegister(Reg))
1003       continue;
1004 
1005     if (ShouldTrackLaneMasks) {
1006       // If the register has just become live then other uses won't change
1007       // this fact anymore => decrement pressure.
1008       // If the register has just become dead then other uses make it come
1009       // back to life => increment pressure.
1010       bool Decrement = P.LaneMask != 0;
1011 
1012       for (const VReg2SUnit &V2SU
1013            : make_range(VRegUses.find(Reg), VRegUses.end())) {
1014         SUnit &SU = *V2SU.SU;
1015         if (SU.isScheduled || &SU == &ExitSU)
1016           continue;
1017 
1018         PressureDiff &PDiff = getPressureDiff(&SU);
1019         PDiff.addPressureChange(Reg, Decrement, &MRI);
1020         DEBUG(
1021           dbgs() << "  UpdateRegP: SU(" << SU.NodeNum << ") "
1022                  << PrintReg(Reg, TRI) << ':' << PrintLaneMask(P.LaneMask)
1023                  << ' ' << *SU.getInstr();
1024           dbgs() << "              to ";
1025           PDiff.dump(*TRI);
1026         );
1027       }
1028     } else {
1029       assert(P.LaneMask != 0);
1030       DEBUG(dbgs() << "  LiveReg: " << PrintVRegOrUnit(Reg, TRI) << "\n");
1031       // This may be called before CurrentBottom has been initialized. However,
1032       // BotRPTracker must have a valid position. We want the value live into the
1033       // instruction or live out of the block, so ask for the previous
1034       // instruction's live-out.
1035       const LiveInterval &LI = LIS->getInterval(Reg);
1036       VNInfo *VNI;
1037       MachineBasicBlock::const_iterator I =
1038         nextIfDebug(BotRPTracker.getPos(), BB->end());
1039       if (I == BB->end())
1040         VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1041       else {
1042         LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
1043         VNI = LRQ.valueIn();
1044       }
1045       // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1046       assert(VNI && "No live value at use.");
1047       for (const VReg2SUnit &V2SU
1048            : make_range(VRegUses.find(Reg), VRegUses.end())) {
1049         SUnit *SU = V2SU.SU;
1050         // If this use comes before the reaching def, it cannot be a last use,
1051         // so decrease its pressure change.
1052         if (!SU->isScheduled && SU != &ExitSU) {
1053           LiveQueryResult LRQ =
1054               LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
1055           if (LRQ.valueIn() == VNI) {
1056             PressureDiff &PDiff = getPressureDiff(SU);
1057             PDiff.addPressureChange(Reg, true, &MRI);
1058             DEBUG(
1059               dbgs() << "  UpdateRegP: SU(" << SU->NodeNum << ") "
1060                      << *SU->getInstr();
1061               dbgs() << "              to ";
1062               PDiff.dump(*TRI);
1063             );
1064           }
1065         }
1066       }
1067     }
1068   }
1069 }
1070 
1071 /// schedule - Called back from MachineScheduler::runOnMachineFunction
1072 /// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1073 /// only includes instructions that have DAG nodes, not scheduling boundaries.
1074 ///
1075 /// This is a skeletal driver, with all the functionality pushed into helpers,
1076 /// so that it can be easily extended by experimental schedulers. Generally,
1077 /// implementing MachineSchedStrategy should be sufficient to implement a new
1078 /// scheduling algorithm. However, if a scheduler further subclasses
1079 /// ScheduleDAGMILive then it will want to override this virtual method in order
1080 /// to update any specialized state.
1081 void ScheduleDAGMILive::schedule() {
1082   DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1083   DEBUG(SchedImpl->dumpPolicy());
1084   buildDAGWithRegPressure();
1085 
1086   Topo.InitDAGTopologicalSorting();
1087 
1088   postprocessDAG();
1089 
1090   SmallVector<SUnit*, 8> TopRoots, BotRoots;
1091   findRootsAndBiasEdges(TopRoots, BotRoots);
1092 
1093   // Initialize the strategy before modifying the DAG.
1094   // This may initialize a DFSResult to be used for queue priority.
1095   SchedImpl->initialize(this);
1096 
1097   DEBUG(
1098     for (const SUnit &SU : SUnits) {
1099       SU.dumpAll(this);
1100       if (ShouldTrackPressure) {
1101         dbgs() << "  Pressure Diff      : ";
1102         getPressureDiff(&SU).dump(*TRI);
1103       }
1104       dbgs() << '\n';
1105     }
1106   );
1107   if (ViewMISchedDAGs) viewGraph();
1108 
1109   // Initialize ready queues now that the DAG and priority data are finalized.
1110   initQueues(TopRoots, BotRoots);
1111 
1112   bool IsTopNode = false;
1113   while (true) {
1114     DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
1115     SUnit *SU = SchedImpl->pickNode(IsTopNode);
1116     if (!SU) break;
1117 
1118     assert(!SU->isScheduled && "Node already scheduled");
1119     if (!checkSchedLimit())
1120       break;
1121 
1122     scheduleMI(SU, IsTopNode);
1123 
1124     if (DFSResult) {
1125       unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1126       if (!ScheduledTrees.test(SubtreeID)) {
1127         ScheduledTrees.set(SubtreeID);
1128         DFSResult->scheduleTree(SubtreeID);
1129         SchedImpl->scheduleTree(SubtreeID);
1130       }
1131     }
1132 
1133     // Notify the scheduling strategy after updating the DAG.
1134     SchedImpl->schedNode(SU, IsTopNode);
1135 
1136     updateQueues(SU, IsTopNode);
1137   }
1138   assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1139 
1140   placeDebugValues();
1141 
1142   DEBUG({
1143       unsigned BBNum = begin()->getParent()->getNumber();
1144       dbgs() << "*** Final schedule for BB#" << BBNum << " ***\n";
1145       dumpSchedule();
1146       dbgs() << '\n';
1147     });
1148 }
1149 
1150 /// Build the DAG and setup three register pressure trackers.
1151 void ScheduleDAGMILive::buildDAGWithRegPressure() {
1152   if (!ShouldTrackPressure) {
1153     RPTracker.reset();
1154     RegionCriticalPSets.clear();
1155     buildSchedGraph(AA);
1156     return;
1157   }
1158 
1159   // Initialize the register pressure tracker used by buildSchedGraph.
1160   RPTracker.init(&MF, RegClassInfo, LIS, BB, LiveRegionEnd,
1161                  ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
1162 
1163   // Account for liveness generate by the region boundary.
1164   if (LiveRegionEnd != RegionEnd)
1165     RPTracker.recede();
1166 
1167   // Build the DAG, and compute current register pressure.
1168   buildSchedGraph(AA, &RPTracker, &SUPressureDiffs, LIS, ShouldTrackLaneMasks);
1169 
1170   // Initialize top/bottom trackers after computing region pressure.
1171   initRegPressure();
1172 }
1173 
1174 void ScheduleDAGMILive::computeDFSResult() {
1175   if (!DFSResult)
1176     DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1177   DFSResult->clear();
1178   ScheduledTrees.clear();
1179   DFSResult->resize(SUnits.size());
1180   DFSResult->compute(SUnits);
1181   ScheduledTrees.resize(DFSResult->getNumSubtrees());
1182 }
1183 
1184 /// Compute the max cyclic critical path through the DAG. The scheduling DAG
1185 /// only provides the critical path for single block loops. To handle loops that
1186 /// span blocks, we could use the vreg path latencies provided by
1187 /// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1188 /// available for use in the scheduler.
1189 ///
1190 /// The cyclic path estimation identifies a def-use pair that crosses the back
1191 /// edge and considers the depth and height of the nodes. For example, consider
1192 /// the following instruction sequence where each instruction has unit latency
1193 /// and defines an epomymous virtual register:
1194 ///
1195 /// a->b(a,c)->c(b)->d(c)->exit
1196 ///
1197 /// The cyclic critical path is a two cycles: b->c->b
1198 /// The acyclic critical path is four cycles: a->b->c->d->exit
1199 /// LiveOutHeight = height(c) = len(c->d->exit) = 2
1200 /// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
1201 /// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
1202 /// LiveInDepth = depth(b) = len(a->b) = 1
1203 ///
1204 /// LiveOutDepth - LiveInDepth = 3 - 1 = 2
1205 /// LiveInHeight - LiveOutHeight = 4 - 2 = 2
1206 /// CyclicCriticalPath = min(2, 2) = 2
1207 ///
1208 /// This could be relevant to PostRA scheduling, but is currently implemented
1209 /// assuming LiveIntervals.
1210 unsigned ScheduleDAGMILive::computeCyclicCriticalPath() {
1211   // This only applies to single block loop.
1212   if (!BB->isSuccessor(BB))
1213     return 0;
1214 
1215   unsigned MaxCyclicLatency = 0;
1216   // Visit each live out vreg def to find def/use pairs that cross iterations.
1217   for (const RegisterMaskPair &P : RPTracker.getPressure().LiveOutRegs) {
1218     unsigned Reg = P.RegUnit;
1219     if (!TRI->isVirtualRegister(Reg))
1220         continue;
1221     const LiveInterval &LI = LIS->getInterval(Reg);
1222     const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1223     if (!DefVNI)
1224       continue;
1225 
1226     MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
1227     const SUnit *DefSU = getSUnit(DefMI);
1228     if (!DefSU)
1229       continue;
1230 
1231     unsigned LiveOutHeight = DefSU->getHeight();
1232     unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
1233     // Visit all local users of the vreg def.
1234     for (const VReg2SUnit &V2SU
1235          : make_range(VRegUses.find(Reg), VRegUses.end())) {
1236       SUnit *SU = V2SU.SU;
1237       if (SU == &ExitSU)
1238         continue;
1239 
1240       // Only consider uses of the phi.
1241       LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
1242       if (!LRQ.valueIn()->isPHIDef())
1243         continue;
1244 
1245       // Assume that a path spanning two iterations is a cycle, which could
1246       // overestimate in strange cases. This allows cyclic latency to be
1247       // estimated as the minimum slack of the vreg's depth or height.
1248       unsigned CyclicLatency = 0;
1249       if (LiveOutDepth > SU->getDepth())
1250         CyclicLatency = LiveOutDepth - SU->getDepth();
1251 
1252       unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
1253       if (LiveInHeight > LiveOutHeight) {
1254         if (LiveInHeight - LiveOutHeight < CyclicLatency)
1255           CyclicLatency = LiveInHeight - LiveOutHeight;
1256       } else
1257         CyclicLatency = 0;
1258 
1259       DEBUG(dbgs() << "Cyclic Path: SU(" << DefSU->NodeNum << ") -> SU("
1260             << SU->NodeNum << ") = " << CyclicLatency << "c\n");
1261       if (CyclicLatency > MaxCyclicLatency)
1262         MaxCyclicLatency = CyclicLatency;
1263     }
1264   }
1265   DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
1266   return MaxCyclicLatency;
1267 }
1268 
1269 /// Release ExitSU predecessors and setup scheduler queues. Re-position
1270 /// the Top RP tracker in case the region beginning has changed.
1271 void ScheduleDAGMILive::initQueues(ArrayRef<SUnit*> TopRoots,
1272                                    ArrayRef<SUnit*> BotRoots) {
1273   ScheduleDAGMI::initQueues(TopRoots, BotRoots);
1274   if (ShouldTrackPressure) {
1275     assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
1276     TopRPTracker.setPos(CurrentTop);
1277   }
1278 }
1279 
1280 /// Move an instruction and update register pressure.
1281 void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
1282   // Move the instruction to its new location in the instruction stream.
1283   MachineInstr *MI = SU->getInstr();
1284 
1285   if (IsTopNode) {
1286     assert(SU->isTopReady() && "node still has unscheduled dependencies");
1287     if (&*CurrentTop == MI)
1288       CurrentTop = nextIfDebug(++CurrentTop, CurrentBottom);
1289     else {
1290       moveInstruction(MI, CurrentTop);
1291       TopRPTracker.setPos(MI);
1292     }
1293 
1294     if (ShouldTrackPressure) {
1295       // Update top scheduled pressure.
1296       RegisterOperands RegOpers;
1297       RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1298       if (ShouldTrackLaneMasks) {
1299         // Adjust liveness and add missing dead+read-undef flags.
1300         SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
1301         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1302       } else {
1303         // Adjust for missing dead-def flags.
1304         RegOpers.detectDeadDefs(*MI, *LIS);
1305       }
1306 
1307       TopRPTracker.advance(RegOpers);
1308       assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
1309       DEBUG(
1310         dbgs() << "Top Pressure:\n";
1311         dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1312       );
1313 
1314       updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
1315     }
1316   } else {
1317     assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1318     MachineBasicBlock::iterator priorII =
1319       priorNonDebug(CurrentBottom, CurrentTop);
1320     if (&*priorII == MI)
1321       CurrentBottom = priorII;
1322     else {
1323       if (&*CurrentTop == MI) {
1324         CurrentTop = nextIfDebug(++CurrentTop, priorII);
1325         TopRPTracker.setPos(CurrentTop);
1326       }
1327       moveInstruction(MI, CurrentBottom);
1328       CurrentBottom = MI;
1329     }
1330     if (ShouldTrackPressure) {
1331       RegisterOperands RegOpers;
1332       RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks, false);
1333       if (ShouldTrackLaneMasks) {
1334         // Adjust liveness and add missing dead+read-undef flags.
1335         SlotIndex SlotIdx = LIS->getInstructionIndex(*MI).getRegSlot();
1336         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx, MI);
1337       } else {
1338         // Adjust for missing dead-def flags.
1339         RegOpers.detectDeadDefs(*MI, *LIS);
1340       }
1341 
1342       BotRPTracker.recedeSkipDebugValues();
1343       SmallVector<RegisterMaskPair, 8> LiveUses;
1344       BotRPTracker.recede(RegOpers, &LiveUses);
1345       assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
1346       DEBUG(
1347         dbgs() << "Bottom Pressure:\n";
1348         dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI);
1349       );
1350 
1351       updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
1352       updatePressureDiffs(LiveUses);
1353     }
1354   }
1355 }
1356 
1357 //===----------------------------------------------------------------------===//
1358 // BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
1359 //===----------------------------------------------------------------------===//
1360 
1361 namespace {
1362 /// \brief Post-process the DAG to create cluster edges between neighboring
1363 /// loads or between neighboring stores.
1364 class BaseMemOpClusterMutation : public ScheduleDAGMutation {
1365   struct MemOpInfo {
1366     SUnit *SU;
1367     unsigned BaseReg;
1368     int64_t Offset;
1369     MemOpInfo(SUnit *su, unsigned reg, int64_t ofs)
1370         : SU(su), BaseReg(reg), Offset(ofs) {}
1371 
1372     bool operator<(const MemOpInfo&RHS) const {
1373       return std::tie(BaseReg, Offset) < std::tie(RHS.BaseReg, RHS.Offset);
1374     }
1375   };
1376 
1377   const TargetInstrInfo *TII;
1378   const TargetRegisterInfo *TRI;
1379   bool IsLoad;
1380 
1381 public:
1382   BaseMemOpClusterMutation(const TargetInstrInfo *tii,
1383                            const TargetRegisterInfo *tri, bool IsLoad)
1384       : TII(tii), TRI(tri), IsLoad(IsLoad) {}
1385 
1386   void apply(ScheduleDAGInstrs *DAGInstrs) override;
1387 
1388 protected:
1389   void clusterNeighboringMemOps(ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG);
1390 };
1391 
1392 class StoreClusterMutation : public BaseMemOpClusterMutation {
1393 public:
1394   StoreClusterMutation(const TargetInstrInfo *tii,
1395                        const TargetRegisterInfo *tri)
1396       : BaseMemOpClusterMutation(tii, tri, false) {}
1397 };
1398 
1399 class LoadClusterMutation : public BaseMemOpClusterMutation {
1400 public:
1401   LoadClusterMutation(const TargetInstrInfo *tii, const TargetRegisterInfo *tri)
1402       : BaseMemOpClusterMutation(tii, tri, true) {}
1403 };
1404 } // anonymous
1405 
1406 void BaseMemOpClusterMutation::clusterNeighboringMemOps(
1407     ArrayRef<SUnit *> MemOps, ScheduleDAGMI *DAG) {
1408   SmallVector<MemOpInfo, 32> MemOpRecords;
1409   for (unsigned Idx = 0, End = MemOps.size(); Idx != End; ++Idx) {
1410     SUnit *SU = MemOps[Idx];
1411     unsigned BaseReg;
1412     int64_t Offset;
1413     if (TII->getMemOpBaseRegImmOfs(SU->getInstr(), BaseReg, Offset, TRI))
1414       MemOpRecords.push_back(MemOpInfo(SU, BaseReg, Offset));
1415   }
1416   if (MemOpRecords.size() < 2)
1417     return;
1418 
1419   std::sort(MemOpRecords.begin(), MemOpRecords.end());
1420   unsigned ClusterLength = 1;
1421   for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
1422     if (MemOpRecords[Idx].BaseReg != MemOpRecords[Idx+1].BaseReg) {
1423       ClusterLength = 1;
1424       continue;
1425     }
1426 
1427     SUnit *SUa = MemOpRecords[Idx].SU;
1428     SUnit *SUb = MemOpRecords[Idx+1].SU;
1429     if (TII->shouldClusterMemOps(SUa->getInstr(), SUb->getInstr(), ClusterLength)
1430         && DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
1431       DEBUG(dbgs() << "Cluster ld/st SU(" << SUa->NodeNum << ") - SU("
1432             << SUb->NodeNum << ")\n");
1433       // Copy successor edges from SUa to SUb. Interleaving computation
1434       // dependent on SUa can prevent load combining due to register reuse.
1435       // Predecessor edges do not need to be copied from SUb to SUa since nearby
1436       // loads should have effectively the same inputs.
1437       for (SUnit::const_succ_iterator
1438              SI = SUa->Succs.begin(), SE = SUa->Succs.end(); SI != SE; ++SI) {
1439         if (SI->getSUnit() == SUb)
1440           continue;
1441         DEBUG(dbgs() << "  Copy Succ SU(" << SI->getSUnit()->NodeNum << ")\n");
1442         DAG->addEdge(SI->getSUnit(), SDep(SUb, SDep::Artificial));
1443       }
1444       ++ClusterLength;
1445     } else
1446       ClusterLength = 1;
1447   }
1448 }
1449 
1450 /// \brief Callback from DAG postProcessing to create cluster edges for loads.
1451 void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAGInstrs) {
1452 
1453   ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1454 
1455   // Map DAG NodeNum to store chain ID.
1456   DenseMap<unsigned, unsigned> StoreChainIDs;
1457   // Map each store chain to a set of dependent MemOps.
1458   SmallVector<SmallVector<SUnit*,4>, 32> StoreChainDependents;
1459   for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1460     SUnit *SU = &DAG->SUnits[Idx];
1461     if ((IsLoad && !SU->getInstr()->mayLoad()) ||
1462         (!IsLoad && !SU->getInstr()->mayStore()))
1463       continue;
1464 
1465     unsigned ChainPredID = DAG->SUnits.size();
1466     for (SUnit::const_pred_iterator
1467            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1468       if (PI->isCtrl()) {
1469         ChainPredID = PI->getSUnit()->NodeNum;
1470         break;
1471       }
1472     }
1473     // Check if this chain-like pred has been seen
1474     // before. ChainPredID==MaxNodeID at the top of the schedule.
1475     unsigned NumChains = StoreChainDependents.size();
1476     std::pair<DenseMap<unsigned, unsigned>::iterator, bool> Result =
1477       StoreChainIDs.insert(std::make_pair(ChainPredID, NumChains));
1478     if (Result.second)
1479       StoreChainDependents.resize(NumChains + 1);
1480     StoreChainDependents[Result.first->second].push_back(SU);
1481   }
1482 
1483   // Iterate over the store chains.
1484   for (unsigned Idx = 0, End = StoreChainDependents.size(); Idx != End; ++Idx)
1485     clusterNeighboringMemOps(StoreChainDependents[Idx], DAG);
1486 }
1487 
1488 //===----------------------------------------------------------------------===//
1489 // MacroFusion - DAG post-processing to encourage fusion of macro ops.
1490 //===----------------------------------------------------------------------===//
1491 
1492 namespace {
1493 /// \brief Post-process the DAG to create cluster edges between instructions
1494 /// that may be fused by the processor into a single operation.
1495 class MacroFusion : public ScheduleDAGMutation {
1496   const TargetInstrInfo &TII;
1497   const TargetRegisterInfo &TRI;
1498 public:
1499   MacroFusion(const TargetInstrInfo &TII, const TargetRegisterInfo &TRI)
1500     : TII(TII), TRI(TRI) {}
1501 
1502   void apply(ScheduleDAGInstrs *DAGInstrs) override;
1503 };
1504 } // anonymous
1505 
1506 /// Returns true if \p MI reads a register written by \p Other.
1507 static bool HasDataDep(const TargetRegisterInfo &TRI, const MachineInstr &MI,
1508                        const MachineInstr &Other) {
1509   for (const MachineOperand &MO : MI.uses()) {
1510     if (!MO.isReg() || !MO.readsReg())
1511       continue;
1512 
1513     unsigned Reg = MO.getReg();
1514     if (Other.modifiesRegister(Reg, &TRI))
1515       return true;
1516   }
1517   return false;
1518 }
1519 
1520 /// \brief Callback from DAG postProcessing to create cluster edges to encourage
1521 /// fused operations.
1522 void MacroFusion::apply(ScheduleDAGInstrs *DAGInstrs) {
1523   ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1524 
1525   // For now, assume targets can only fuse with the branch.
1526   SUnit &ExitSU = DAG->ExitSU;
1527   MachineInstr *Branch = ExitSU.getInstr();
1528   if (!Branch)
1529     return;
1530 
1531   for (SUnit &SU : DAG->SUnits) {
1532     // SUnits with successors can't be schedule in front of the ExitSU.
1533     if (!SU.Succs.empty())
1534       continue;
1535     // We only care if the node writes to a register that the branch reads.
1536     MachineInstr *Pred = SU.getInstr();
1537     if (!HasDataDep(TRI, *Branch, *Pred))
1538       continue;
1539 
1540     if (!TII.shouldScheduleAdjacent(Pred, Branch))
1541       continue;
1542 
1543     // Create a single weak edge from SU to ExitSU. The only effect is to cause
1544     // bottom-up scheduling to heavily prioritize the clustered SU.  There is no
1545     // need to copy predecessor edges from ExitSU to SU, since top-down
1546     // scheduling cannot prioritize ExitSU anyway. To defer top-down scheduling
1547     // of SU, we could create an artificial edge from the deepest root, but it
1548     // hasn't been needed yet.
1549     bool Success = DAG->addEdge(&ExitSU, SDep(&SU, SDep::Cluster));
1550     (void)Success;
1551     assert(Success && "No DAG nodes should be reachable from ExitSU");
1552 
1553     DEBUG(dbgs() << "Macro Fuse SU(" << SU.NodeNum << ")\n");
1554     break;
1555   }
1556 }
1557 
1558 //===----------------------------------------------------------------------===//
1559 // CopyConstrain - DAG post-processing to encourage copy elimination.
1560 //===----------------------------------------------------------------------===//
1561 
1562 namespace {
1563 /// \brief Post-process the DAG to create weak edges from all uses of a copy to
1564 /// the one use that defines the copy's source vreg, most likely an induction
1565 /// variable increment.
1566 class CopyConstrain : public ScheduleDAGMutation {
1567   // Transient state.
1568   SlotIndex RegionBeginIdx;
1569   // RegionEndIdx is the slot index of the last non-debug instruction in the
1570   // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
1571   SlotIndex RegionEndIdx;
1572 public:
1573   CopyConstrain(const TargetInstrInfo *, const TargetRegisterInfo *) {}
1574 
1575   void apply(ScheduleDAGInstrs *DAGInstrs) override;
1576 
1577 protected:
1578   void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
1579 };
1580 } // anonymous
1581 
1582 /// constrainLocalCopy handles two possibilities:
1583 /// 1) Local src:
1584 /// I0:     = dst
1585 /// I1: src = ...
1586 /// I2:     = dst
1587 /// I3: dst = src (copy)
1588 /// (create pred->succ edges I0->I1, I2->I1)
1589 ///
1590 /// 2) Local copy:
1591 /// I0: dst = src (copy)
1592 /// I1:     = dst
1593 /// I2: src = ...
1594 /// I3:     = dst
1595 /// (create pred->succ edges I1->I2, I3->I2)
1596 ///
1597 /// Although the MachineScheduler is currently constrained to single blocks,
1598 /// this algorithm should handle extended blocks. An EBB is a set of
1599 /// contiguously numbered blocks such that the previous block in the EBB is
1600 /// always the single predecessor.
1601 void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
1602   LiveIntervals *LIS = DAG->getLIS();
1603   MachineInstr *Copy = CopySU->getInstr();
1604 
1605   // Check for pure vreg copies.
1606   const MachineOperand &SrcOp = Copy->getOperand(1);
1607   unsigned SrcReg = SrcOp.getReg();
1608   if (!TargetRegisterInfo::isVirtualRegister(SrcReg) || !SrcOp.readsReg())
1609     return;
1610 
1611   const MachineOperand &DstOp = Copy->getOperand(0);
1612   unsigned DstReg = DstOp.getReg();
1613   if (!TargetRegisterInfo::isVirtualRegister(DstReg) || DstOp.isDead())
1614     return;
1615 
1616   // Check if either the dest or source is local. If it's live across a back
1617   // edge, it's not local. Note that if both vregs are live across the back
1618   // edge, we cannot successfully contrain the copy without cyclic scheduling.
1619   // If both the copy's source and dest are local live intervals, then we
1620   // should treat the dest as the global for the purpose of adding
1621   // constraints. This adds edges from source's other uses to the copy.
1622   unsigned LocalReg = SrcReg;
1623   unsigned GlobalReg = DstReg;
1624   LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
1625   if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
1626     LocalReg = DstReg;
1627     GlobalReg = SrcReg;
1628     LocalLI = &LIS->getInterval(LocalReg);
1629     if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
1630       return;
1631   }
1632   LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
1633 
1634   // Find the global segment after the start of the local LI.
1635   LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
1636   // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
1637   // local live range. We could create edges from other global uses to the local
1638   // start, but the coalescer should have already eliminated these cases, so
1639   // don't bother dealing with it.
1640   if (GlobalSegment == GlobalLI->end())
1641     return;
1642 
1643   // If GlobalSegment is killed at the LocalLI->start, the call to find()
1644   // returned the next global segment. But if GlobalSegment overlaps with
1645   // LocalLI->start, then advance to the next segement. If a hole in GlobalLI
1646   // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
1647   if (GlobalSegment->contains(LocalLI->beginIndex()))
1648     ++GlobalSegment;
1649 
1650   if (GlobalSegment == GlobalLI->end())
1651     return;
1652 
1653   // Check if GlobalLI contains a hole in the vicinity of LocalLI.
1654   if (GlobalSegment != GlobalLI->begin()) {
1655     // Two address defs have no hole.
1656     if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
1657                                GlobalSegment->start)) {
1658       return;
1659     }
1660     // If the prior global segment may be defined by the same two-address
1661     // instruction that also defines LocalLI, then can't make a hole here.
1662     if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
1663                                LocalLI->beginIndex())) {
1664       return;
1665     }
1666     // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
1667     // it would be a disconnected component in the live range.
1668     assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
1669            "Disconnected LRG within the scheduling region.");
1670   }
1671   MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
1672   if (!GlobalDef)
1673     return;
1674 
1675   SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
1676   if (!GlobalSU)
1677     return;
1678 
1679   // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
1680   // constraining the uses of the last local def to precede GlobalDef.
1681   SmallVector<SUnit*,8> LocalUses;
1682   const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
1683   MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
1684   SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
1685   for (SUnit::const_succ_iterator
1686          I = LastLocalSU->Succs.begin(), E = LastLocalSU->Succs.end();
1687        I != E; ++I) {
1688     if (I->getKind() != SDep::Data || I->getReg() != LocalReg)
1689       continue;
1690     if (I->getSUnit() == GlobalSU)
1691       continue;
1692     if (!DAG->canAddEdge(GlobalSU, I->getSUnit()))
1693       return;
1694     LocalUses.push_back(I->getSUnit());
1695   }
1696   // Open the top of the GlobalLI hole by constraining any earlier global uses
1697   // to precede the start of LocalLI.
1698   SmallVector<SUnit*,8> GlobalUses;
1699   MachineInstr *FirstLocalDef =
1700     LIS->getInstructionFromIndex(LocalLI->beginIndex());
1701   SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
1702   for (SUnit::const_pred_iterator
1703          I = GlobalSU->Preds.begin(), E = GlobalSU->Preds.end(); I != E; ++I) {
1704     if (I->getKind() != SDep::Anti || I->getReg() != GlobalReg)
1705       continue;
1706     if (I->getSUnit() == FirstLocalSU)
1707       continue;
1708     if (!DAG->canAddEdge(FirstLocalSU, I->getSUnit()))
1709       return;
1710     GlobalUses.push_back(I->getSUnit());
1711   }
1712   DEBUG(dbgs() << "Constraining copy SU(" << CopySU->NodeNum << ")\n");
1713   // Add the weak edges.
1714   for (SmallVectorImpl<SUnit*>::const_iterator
1715          I = LocalUses.begin(), E = LocalUses.end(); I != E; ++I) {
1716     DEBUG(dbgs() << "  Local use SU(" << (*I)->NodeNum << ") -> SU("
1717           << GlobalSU->NodeNum << ")\n");
1718     DAG->addEdge(GlobalSU, SDep(*I, SDep::Weak));
1719   }
1720   for (SmallVectorImpl<SUnit*>::const_iterator
1721          I = GlobalUses.begin(), E = GlobalUses.end(); I != E; ++I) {
1722     DEBUG(dbgs() << "  Global use SU(" << (*I)->NodeNum << ") -> SU("
1723           << FirstLocalSU->NodeNum << ")\n");
1724     DAG->addEdge(FirstLocalSU, SDep(*I, SDep::Weak));
1725   }
1726 }
1727 
1728 /// \brief Callback from DAG postProcessing to create weak edges to encourage
1729 /// copy elimination.
1730 void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
1731   ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
1732   assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
1733 
1734   MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
1735   if (FirstPos == DAG->end())
1736     return;
1737   RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
1738   RegionEndIdx = DAG->getLIS()->getInstructionIndex(
1739       *priorNonDebug(DAG->end(), DAG->begin()));
1740 
1741   for (unsigned Idx = 0, End = DAG->SUnits.size(); Idx != End; ++Idx) {
1742     SUnit *SU = &DAG->SUnits[Idx];
1743     if (!SU->getInstr()->isCopy())
1744       continue;
1745 
1746     constrainLocalCopy(SU, static_cast<ScheduleDAGMILive*>(DAG));
1747   }
1748 }
1749 
1750 //===----------------------------------------------------------------------===//
1751 // MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
1752 // and possibly other custom schedulers.
1753 //===----------------------------------------------------------------------===//
1754 
1755 static const unsigned InvalidCycle = ~0U;
1756 
1757 SchedBoundary::~SchedBoundary() { delete HazardRec; }
1758 
1759 void SchedBoundary::reset() {
1760   // A new HazardRec is created for each DAG and owned by SchedBoundary.
1761   // Destroying and reconstructing it is very expensive though. So keep
1762   // invalid, placeholder HazardRecs.
1763   if (HazardRec && HazardRec->isEnabled()) {
1764     delete HazardRec;
1765     HazardRec = nullptr;
1766   }
1767   Available.clear();
1768   Pending.clear();
1769   CheckPending = false;
1770   NextSUs.clear();
1771   CurrCycle = 0;
1772   CurrMOps = 0;
1773   MinReadyCycle = UINT_MAX;
1774   ExpectedLatency = 0;
1775   DependentLatency = 0;
1776   RetiredMOps = 0;
1777   MaxExecutedResCount = 0;
1778   ZoneCritResIdx = 0;
1779   IsResourceLimited = false;
1780   ReservedCycles.clear();
1781 #ifndef NDEBUG
1782   // Track the maximum number of stall cycles that could arise either from the
1783   // latency of a DAG edge or the number of cycles that a processor resource is
1784   // reserved (SchedBoundary::ReservedCycles).
1785   MaxObservedStall = 0;
1786 #endif
1787   // Reserve a zero-count for invalid CritResIdx.
1788   ExecutedResCounts.resize(1);
1789   assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
1790 }
1791 
1792 void SchedRemainder::
1793 init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
1794   reset();
1795   if (!SchedModel->hasInstrSchedModel())
1796     return;
1797   RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
1798   for (std::vector<SUnit>::iterator
1799          I = DAG->SUnits.begin(), E = DAG->SUnits.end(); I != E; ++I) {
1800     const MCSchedClassDesc *SC = DAG->getSchedClass(&*I);
1801     RemIssueCount += SchedModel->getNumMicroOps(I->getInstr(), SC)
1802       * SchedModel->getMicroOpFactor();
1803     for (TargetSchedModel::ProcResIter
1804            PI = SchedModel->getWriteProcResBegin(SC),
1805            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1806       unsigned PIdx = PI->ProcResourceIdx;
1807       unsigned Factor = SchedModel->getResourceFactor(PIdx);
1808       RemainingCounts[PIdx] += (Factor * PI->Cycles);
1809     }
1810   }
1811 }
1812 
1813 void SchedBoundary::
1814 init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
1815   reset();
1816   DAG = dag;
1817   SchedModel = smodel;
1818   Rem = rem;
1819   if (SchedModel->hasInstrSchedModel()) {
1820     ExecutedResCounts.resize(SchedModel->getNumProcResourceKinds());
1821     ReservedCycles.resize(SchedModel->getNumProcResourceKinds(), InvalidCycle);
1822   }
1823 }
1824 
1825 /// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
1826 /// these "soft stalls" differently than the hard stall cycles based on CPU
1827 /// resources and computed by checkHazard(). A fully in-order model
1828 /// (MicroOpBufferSize==0) will not make use of this since instructions are not
1829 /// available for scheduling until they are ready. However, a weaker in-order
1830 /// model may use this for heuristics. For example, if a processor has in-order
1831 /// behavior when reading certain resources, this may come into play.
1832 unsigned SchedBoundary::getLatencyStallCycles(SUnit *SU) {
1833   if (!SU->isUnbuffered)
1834     return 0;
1835 
1836   unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
1837   if (ReadyCycle > CurrCycle)
1838     return ReadyCycle - CurrCycle;
1839   return 0;
1840 }
1841 
1842 /// Compute the next cycle at which the given processor resource can be
1843 /// scheduled.
1844 unsigned SchedBoundary::
1845 getNextResourceCycle(unsigned PIdx, unsigned Cycles) {
1846   unsigned NextUnreserved = ReservedCycles[PIdx];
1847   // If this resource has never been used, always return cycle zero.
1848   if (NextUnreserved == InvalidCycle)
1849     return 0;
1850   // For bottom-up scheduling add the cycles needed for the current operation.
1851   if (!isTop())
1852     NextUnreserved += Cycles;
1853   return NextUnreserved;
1854 }
1855 
1856 /// Does this SU have a hazard within the current instruction group.
1857 ///
1858 /// The scheduler supports two modes of hazard recognition. The first is the
1859 /// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
1860 /// supports highly complicated in-order reservation tables
1861 /// (ScoreboardHazardRecognizer) and arbitraty target-specific logic.
1862 ///
1863 /// The second is a streamlined mechanism that checks for hazards based on
1864 /// simple counters that the scheduler itself maintains. It explicitly checks
1865 /// for instruction dispatch limitations, including the number of micro-ops that
1866 /// can dispatch per cycle.
1867 ///
1868 /// TODO: Also check whether the SU must start a new group.
1869 bool SchedBoundary::checkHazard(SUnit *SU) {
1870   if (HazardRec->isEnabled()
1871       && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
1872     return true;
1873   }
1874   unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
1875   if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
1876     DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") uops="
1877           << SchedModel->getNumMicroOps(SU->getInstr()) << '\n');
1878     return true;
1879   }
1880   if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
1881     const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
1882     for (TargetSchedModel::ProcResIter
1883            PI = SchedModel->getWriteProcResBegin(SC),
1884            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
1885       unsigned NRCycle = getNextResourceCycle(PI->ProcResourceIdx, PI->Cycles);
1886       if (NRCycle > CurrCycle) {
1887 #ifndef NDEBUG
1888         MaxObservedStall = std::max(PI->Cycles, MaxObservedStall);
1889 #endif
1890         DEBUG(dbgs() << "  SU(" << SU->NodeNum << ") "
1891               << SchedModel->getResourceName(PI->ProcResourceIdx)
1892               << "=" << NRCycle << "c\n");
1893         return true;
1894       }
1895     }
1896   }
1897   return false;
1898 }
1899 
1900 // Find the unscheduled node in ReadySUs with the highest latency.
1901 unsigned SchedBoundary::
1902 findMaxLatency(ArrayRef<SUnit*> ReadySUs) {
1903   SUnit *LateSU = nullptr;
1904   unsigned RemLatency = 0;
1905   for (ArrayRef<SUnit*>::iterator I = ReadySUs.begin(), E = ReadySUs.end();
1906        I != E; ++I) {
1907     unsigned L = getUnscheduledLatency(*I);
1908     if (L > RemLatency) {
1909       RemLatency = L;
1910       LateSU = *I;
1911     }
1912   }
1913   if (LateSU) {
1914     DEBUG(dbgs() << Available.getName() << " RemLatency SU("
1915           << LateSU->NodeNum << ") " << RemLatency << "c\n");
1916   }
1917   return RemLatency;
1918 }
1919 
1920 // Count resources in this zone and the remaining unscheduled
1921 // instruction. Return the max count, scaled. Set OtherCritIdx to the critical
1922 // resource index, or zero if the zone is issue limited.
1923 unsigned SchedBoundary::
1924 getOtherResourceCount(unsigned &OtherCritIdx) {
1925   OtherCritIdx = 0;
1926   if (!SchedModel->hasInstrSchedModel())
1927     return 0;
1928 
1929   unsigned OtherCritCount = Rem->RemIssueCount
1930     + (RetiredMOps * SchedModel->getMicroOpFactor());
1931   DEBUG(dbgs() << "  " << Available.getName() << " + Remain MOps: "
1932         << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
1933   for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
1934        PIdx != PEnd; ++PIdx) {
1935     unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
1936     if (OtherCount > OtherCritCount) {
1937       OtherCritCount = OtherCount;
1938       OtherCritIdx = PIdx;
1939     }
1940   }
1941   if (OtherCritIdx) {
1942     DEBUG(dbgs() << "  " << Available.getName() << " + Remain CritRes: "
1943           << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
1944           << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
1945   }
1946   return OtherCritCount;
1947 }
1948 
1949 void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle) {
1950   assert(SU->getInstr() && "Scheduled SUnit must have instr");
1951 
1952 #ifndef NDEBUG
1953   // ReadyCycle was been bumped up to the CurrCycle when this node was
1954   // scheduled, but CurrCycle may have been eagerly advanced immediately after
1955   // scheduling, so may now be greater than ReadyCycle.
1956   if (ReadyCycle > CurrCycle)
1957     MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
1958 #endif
1959 
1960   if (ReadyCycle < MinReadyCycle)
1961     MinReadyCycle = ReadyCycle;
1962 
1963   // Check for interlocks first. For the purpose of other heuristics, an
1964   // instruction that cannot issue appears as if it's not in the ReadyQueue.
1965   bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
1966   if ((!IsBuffered && ReadyCycle > CurrCycle) || checkHazard(SU) ||
1967       Available.size() >= ReadyListLimit)
1968     Pending.push(SU);
1969   else
1970     Available.push(SU);
1971 
1972   // Record this node as an immediate dependent of the scheduled node.
1973   NextSUs.insert(SU);
1974 }
1975 
1976 void SchedBoundary::releaseTopNode(SUnit *SU) {
1977   if (SU->isScheduled)
1978     return;
1979 
1980   releaseNode(SU, SU->TopReadyCycle);
1981 }
1982 
1983 void SchedBoundary::releaseBottomNode(SUnit *SU) {
1984   if (SU->isScheduled)
1985     return;
1986 
1987   releaseNode(SU, SU->BotReadyCycle);
1988 }
1989 
1990 /// Move the boundary of scheduled code by one cycle.
1991 void SchedBoundary::bumpCycle(unsigned NextCycle) {
1992   if (SchedModel->getMicroOpBufferSize() == 0) {
1993     assert(MinReadyCycle < UINT_MAX && "MinReadyCycle uninitialized");
1994     if (MinReadyCycle > NextCycle)
1995       NextCycle = MinReadyCycle;
1996   }
1997   // Update the current micro-ops, which will issue in the next cycle.
1998   unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
1999   CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
2000 
2001   // Decrement DependentLatency based on the next cycle.
2002   if ((NextCycle - CurrCycle) > DependentLatency)
2003     DependentLatency = 0;
2004   else
2005     DependentLatency -= (NextCycle - CurrCycle);
2006 
2007   if (!HazardRec->isEnabled()) {
2008     // Bypass HazardRec virtual calls.
2009     CurrCycle = NextCycle;
2010   } else {
2011     // Bypass getHazardType calls in case of long latency.
2012     for (; CurrCycle != NextCycle; ++CurrCycle) {
2013       if (isTop())
2014         HazardRec->AdvanceCycle();
2015       else
2016         HazardRec->RecedeCycle();
2017     }
2018   }
2019   CheckPending = true;
2020   unsigned LFactor = SchedModel->getLatencyFactor();
2021   IsResourceLimited =
2022     (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2023     > (int)LFactor;
2024 
2025   DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName() << '\n');
2026 }
2027 
2028 void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
2029   ExecutedResCounts[PIdx] += Count;
2030   if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
2031     MaxExecutedResCount = ExecutedResCounts[PIdx];
2032 }
2033 
2034 /// Add the given processor resource to this scheduled zone.
2035 ///
2036 /// \param Cycles indicates the number of consecutive (non-pipelined) cycles
2037 /// during which this resource is consumed.
2038 ///
2039 /// \return the next cycle at which the instruction may execute without
2040 /// oversubscribing resources.
2041 unsigned SchedBoundary::
2042 countResource(unsigned PIdx, unsigned Cycles, unsigned NextCycle) {
2043   unsigned Factor = SchedModel->getResourceFactor(PIdx);
2044   unsigned Count = Factor * Cycles;
2045   DEBUG(dbgs() << "  " << SchedModel->getResourceName(PIdx)
2046         << " +" << Cycles << "x" << Factor << "u\n");
2047 
2048   // Update Executed resources counts.
2049   incExecutedResources(PIdx, Count);
2050   assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
2051   Rem->RemainingCounts[PIdx] -= Count;
2052 
2053   // Check if this resource exceeds the current critical resource. If so, it
2054   // becomes the critical resource.
2055   if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
2056     ZoneCritResIdx = PIdx;
2057     DEBUG(dbgs() << "  *** Critical resource "
2058           << SchedModel->getResourceName(PIdx) << ": "
2059           << getResourceCount(PIdx) / SchedModel->getLatencyFactor() << "c\n");
2060   }
2061   // For reserved resources, record the highest cycle using the resource.
2062   unsigned NextAvailable = getNextResourceCycle(PIdx, Cycles);
2063   if (NextAvailable > CurrCycle) {
2064     DEBUG(dbgs() << "  Resource conflict: "
2065           << SchedModel->getProcResource(PIdx)->Name << " reserved until @"
2066           << NextAvailable << "\n");
2067   }
2068   return NextAvailable;
2069 }
2070 
2071 /// Move the boundary of scheduled code by one SUnit.
2072 void SchedBoundary::bumpNode(SUnit *SU) {
2073   // Update the reservation table.
2074   if (HazardRec->isEnabled()) {
2075     if (!isTop() && SU->isCall) {
2076       // Calls are scheduled with their preceding instructions. For bottom-up
2077       // scheduling, clear the pipeline state before emitting.
2078       HazardRec->Reset();
2079     }
2080     HazardRec->EmitInstruction(SU);
2081   }
2082   // checkHazard should prevent scheduling multiple instructions per cycle that
2083   // exceed the issue width.
2084   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2085   unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
2086   assert(
2087       (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
2088       "Cannot schedule this instruction's MicroOps in the current cycle.");
2089 
2090   unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
2091   DEBUG(dbgs() << "  Ready @" << ReadyCycle << "c\n");
2092 
2093   unsigned NextCycle = CurrCycle;
2094   switch (SchedModel->getMicroOpBufferSize()) {
2095   case 0:
2096     assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
2097     break;
2098   case 1:
2099     if (ReadyCycle > NextCycle) {
2100       NextCycle = ReadyCycle;
2101       DEBUG(dbgs() << "  *** Stall until: " << ReadyCycle << "\n");
2102     }
2103     break;
2104   default:
2105     // We don't currently model the OOO reorder buffer, so consider all
2106     // scheduled MOps to be "retired". We do loosely model in-order resource
2107     // latency. If this instruction uses an in-order resource, account for any
2108     // likely stall cycles.
2109     if (SU->isUnbuffered && ReadyCycle > NextCycle)
2110       NextCycle = ReadyCycle;
2111     break;
2112   }
2113   RetiredMOps += IncMOps;
2114 
2115   // Update resource counts and critical resource.
2116   if (SchedModel->hasInstrSchedModel()) {
2117     unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
2118     assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
2119     Rem->RemIssueCount -= DecRemIssue;
2120     if (ZoneCritResIdx) {
2121       // Scale scheduled micro-ops for comparing with the critical resource.
2122       unsigned ScaledMOps =
2123         RetiredMOps * SchedModel->getMicroOpFactor();
2124 
2125       // If scaled micro-ops are now more than the previous critical resource by
2126       // a full cycle, then micro-ops issue becomes critical.
2127       if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
2128           >= (int)SchedModel->getLatencyFactor()) {
2129         ZoneCritResIdx = 0;
2130         DEBUG(dbgs() << "  *** Critical resource NumMicroOps: "
2131               << ScaledMOps / SchedModel->getLatencyFactor() << "c\n");
2132       }
2133     }
2134     for (TargetSchedModel::ProcResIter
2135            PI = SchedModel->getWriteProcResBegin(SC),
2136            PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2137       unsigned RCycle =
2138         countResource(PI->ProcResourceIdx, PI->Cycles, NextCycle);
2139       if (RCycle > NextCycle)
2140         NextCycle = RCycle;
2141     }
2142     if (SU->hasReservedResource) {
2143       // For reserved resources, record the highest cycle using the resource.
2144       // For top-down scheduling, this is the cycle in which we schedule this
2145       // instruction plus the number of cycles the operations reserves the
2146       // resource. For bottom-up is it simply the instruction's cycle.
2147       for (TargetSchedModel::ProcResIter
2148              PI = SchedModel->getWriteProcResBegin(SC),
2149              PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2150         unsigned PIdx = PI->ProcResourceIdx;
2151         if (SchedModel->getProcResource(PIdx)->BufferSize == 0) {
2152           if (isTop()) {
2153             ReservedCycles[PIdx] =
2154               std::max(getNextResourceCycle(PIdx, 0), NextCycle + PI->Cycles);
2155           }
2156           else
2157             ReservedCycles[PIdx] = NextCycle;
2158         }
2159       }
2160     }
2161   }
2162   // Update ExpectedLatency and DependentLatency.
2163   unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
2164   unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
2165   if (SU->getDepth() > TopLatency) {
2166     TopLatency = SU->getDepth();
2167     DEBUG(dbgs() << "  " << Available.getName()
2168           << " TopLatency SU(" << SU->NodeNum << ") " << TopLatency << "c\n");
2169   }
2170   if (SU->getHeight() > BotLatency) {
2171     BotLatency = SU->getHeight();
2172     DEBUG(dbgs() << "  " << Available.getName()
2173           << " BotLatency SU(" << SU->NodeNum << ") " << BotLatency << "c\n");
2174   }
2175   // If we stall for any reason, bump the cycle.
2176   if (NextCycle > CurrCycle) {
2177     bumpCycle(NextCycle);
2178   } else {
2179     // After updating ZoneCritResIdx and ExpectedLatency, check if we're
2180     // resource limited. If a stall occurred, bumpCycle does this.
2181     unsigned LFactor = SchedModel->getLatencyFactor();
2182     IsResourceLimited =
2183       (int)(getCriticalCount() - (getScheduledLatency() * LFactor))
2184       > (int)LFactor;
2185   }
2186   // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
2187   // resets CurrMOps. Loop to handle instructions with more MOps than issue in
2188   // one cycle.  Since we commonly reach the max MOps here, opportunistically
2189   // bump the cycle to avoid uselessly checking everything in the readyQ.
2190   CurrMOps += IncMOps;
2191   while (CurrMOps >= SchedModel->getIssueWidth()) {
2192     DEBUG(dbgs() << "  *** Max MOps " << CurrMOps
2193           << " at cycle " << CurrCycle << '\n');
2194     bumpCycle(++NextCycle);
2195   }
2196   DEBUG(dumpScheduledState());
2197 }
2198 
2199 /// Release pending ready nodes in to the available queue. This makes them
2200 /// visible to heuristics.
2201 void SchedBoundary::releasePending() {
2202   // If the available queue is empty, it is safe to reset MinReadyCycle.
2203   if (Available.empty())
2204     MinReadyCycle = UINT_MAX;
2205 
2206   // Check to see if any of the pending instructions are ready to issue.  If
2207   // so, add them to the available queue.
2208   bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
2209   for (unsigned i = 0, e = Pending.size(); i != e; ++i) {
2210     SUnit *SU = *(Pending.begin()+i);
2211     unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
2212 
2213     if (ReadyCycle < MinReadyCycle)
2214       MinReadyCycle = ReadyCycle;
2215 
2216     if (!IsBuffered && ReadyCycle > CurrCycle)
2217       continue;
2218 
2219     if (checkHazard(SU))
2220       continue;
2221 
2222     if (Available.size() >= ReadyListLimit)
2223       break;
2224 
2225     Available.push(SU);
2226     Pending.remove(Pending.begin()+i);
2227     --i; --e;
2228   }
2229   DEBUG(if (!Pending.empty()) Pending.dump());
2230   CheckPending = false;
2231 }
2232 
2233 /// Remove SU from the ready set for this boundary.
2234 void SchedBoundary::removeReady(SUnit *SU) {
2235   if (Available.isInQueue(SU))
2236     Available.remove(Available.find(SU));
2237   else {
2238     assert(Pending.isInQueue(SU) && "bad ready count");
2239     Pending.remove(Pending.find(SU));
2240   }
2241 }
2242 
2243 /// If this queue only has one ready candidate, return it. As a side effect,
2244 /// defer any nodes that now hit a hazard, and advance the cycle until at least
2245 /// one node is ready. If multiple instructions are ready, return NULL.
2246 SUnit *SchedBoundary::pickOnlyChoice() {
2247   if (CheckPending)
2248     releasePending();
2249 
2250   if (CurrMOps > 0) {
2251     // Defer any ready instrs that now have a hazard.
2252     for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
2253       if (checkHazard(*I)) {
2254         Pending.push(*I);
2255         I = Available.remove(I);
2256         continue;
2257       }
2258       ++I;
2259     }
2260   }
2261   for (unsigned i = 0; Available.empty(); ++i) {
2262 //  FIXME: Re-enable assert once PR20057 is resolved.
2263 //    assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
2264 //           "permanent hazard");
2265     (void)i;
2266     bumpCycle(CurrCycle + 1);
2267     releasePending();
2268   }
2269   if (Available.size() == 1)
2270     return *Available.begin();
2271   return nullptr;
2272 }
2273 
2274 #ifndef NDEBUG
2275 // This is useful information to dump after bumpNode.
2276 // Note that the Queue contents are more useful before pickNodeFromQueue.
2277 void SchedBoundary::dumpScheduledState() {
2278   unsigned ResFactor;
2279   unsigned ResCount;
2280   if (ZoneCritResIdx) {
2281     ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
2282     ResCount = getResourceCount(ZoneCritResIdx);
2283   } else {
2284     ResFactor = SchedModel->getMicroOpFactor();
2285     ResCount = RetiredMOps * SchedModel->getMicroOpFactor();
2286   }
2287   unsigned LFactor = SchedModel->getLatencyFactor();
2288   dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
2289          << "  Retired: " << RetiredMOps;
2290   dbgs() << "\n  Executed: " << getExecutedCount() / LFactor << "c";
2291   dbgs() << "\n  Critical: " << ResCount / LFactor << "c, "
2292          << ResCount / ResFactor << " "
2293          << SchedModel->getResourceName(ZoneCritResIdx)
2294          << "\n  ExpectedLatency: " << ExpectedLatency << "c\n"
2295          << (IsResourceLimited ? "  - Resource" : "  - Latency")
2296          << " limited.\n";
2297 }
2298 #endif
2299 
2300 //===----------------------------------------------------------------------===//
2301 // GenericScheduler - Generic implementation of MachineSchedStrategy.
2302 //===----------------------------------------------------------------------===//
2303 
2304 void GenericSchedulerBase::SchedCandidate::
2305 initResourceDelta(const ScheduleDAGMI *DAG,
2306                   const TargetSchedModel *SchedModel) {
2307   if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
2308     return;
2309 
2310   const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
2311   for (TargetSchedModel::ProcResIter
2312          PI = SchedModel->getWriteProcResBegin(SC),
2313          PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2314     if (PI->ProcResourceIdx == Policy.ReduceResIdx)
2315       ResDelta.CritResources += PI->Cycles;
2316     if (PI->ProcResourceIdx == Policy.DemandResIdx)
2317       ResDelta.DemandedResources += PI->Cycles;
2318   }
2319 }
2320 
2321 /// Set the CandPolicy given a scheduling zone given the current resources and
2322 /// latencies inside and outside the zone.
2323 void GenericSchedulerBase::setPolicy(CandPolicy &Policy, bool IsPostRA,
2324                                      SchedBoundary &CurrZone,
2325                                      SchedBoundary *OtherZone) {
2326   // Apply preemptive heuristics based on the total latency and resources
2327   // inside and outside this zone. Potential stalls should be considered before
2328   // following this policy.
2329 
2330   // Compute remaining latency. We need this both to determine whether the
2331   // overall schedule has become latency-limited and whether the instructions
2332   // outside this zone are resource or latency limited.
2333   //
2334   // The "dependent" latency is updated incrementally during scheduling as the
2335   // max height/depth of scheduled nodes minus the cycles since it was
2336   // scheduled:
2337   //   DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
2338   //
2339   // The "independent" latency is the max ready queue depth:
2340   //   ILat = max N.depth for N in Available|Pending
2341   //
2342   // RemainingLatency is the greater of independent and dependent latency.
2343   unsigned RemLatency = CurrZone.getDependentLatency();
2344   RemLatency = std::max(RemLatency,
2345                         CurrZone.findMaxLatency(CurrZone.Available.elements()));
2346   RemLatency = std::max(RemLatency,
2347                         CurrZone.findMaxLatency(CurrZone.Pending.elements()));
2348 
2349   // Compute the critical resource outside the zone.
2350   unsigned OtherCritIdx = 0;
2351   unsigned OtherCount =
2352     OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
2353 
2354   bool OtherResLimited = false;
2355   if (SchedModel->hasInstrSchedModel()) {
2356     unsigned LFactor = SchedModel->getLatencyFactor();
2357     OtherResLimited = (int)(OtherCount - (RemLatency * LFactor)) > (int)LFactor;
2358   }
2359   // Schedule aggressively for latency in PostRA mode. We don't check for
2360   // acyclic latency during PostRA, and highly out-of-order processors will
2361   // skip PostRA scheduling.
2362   if (!OtherResLimited) {
2363     if (IsPostRA || (RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath)) {
2364       Policy.ReduceLatency |= true;
2365       DEBUG(dbgs() << "  " << CurrZone.Available.getName()
2366             << " RemainingLatency " << RemLatency << " + "
2367             << CurrZone.getCurrCycle() << "c > CritPath "
2368             << Rem.CriticalPath << "\n");
2369     }
2370   }
2371   // If the same resource is limiting inside and outside the zone, do nothing.
2372   if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
2373     return;
2374 
2375   DEBUG(
2376     if (CurrZone.isResourceLimited()) {
2377       dbgs() << "  " << CurrZone.Available.getName() << " ResourceLimited: "
2378              << SchedModel->getResourceName(CurrZone.getZoneCritResIdx())
2379              << "\n";
2380     }
2381     if (OtherResLimited)
2382       dbgs() << "  RemainingLimit: "
2383              << SchedModel->getResourceName(OtherCritIdx) << "\n";
2384     if (!CurrZone.isResourceLimited() && !OtherResLimited)
2385       dbgs() << "  Latency limited both directions.\n");
2386 
2387   if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
2388     Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
2389 
2390   if (OtherResLimited)
2391     Policy.DemandResIdx = OtherCritIdx;
2392 }
2393 
2394 #ifndef NDEBUG
2395 const char *GenericSchedulerBase::getReasonStr(
2396   GenericSchedulerBase::CandReason Reason) {
2397   switch (Reason) {
2398   case NoCand:         return "NOCAND    ";
2399   case Only1:          return "ONLY1     ";
2400   case PhysRegCopy:    return "PREG-COPY ";
2401   case RegExcess:      return "REG-EXCESS";
2402   case RegCritical:    return "REG-CRIT  ";
2403   case Stall:          return "STALL     ";
2404   case Cluster:        return "CLUSTER   ";
2405   case Weak:           return "WEAK      ";
2406   case RegMax:         return "REG-MAX   ";
2407   case ResourceReduce: return "RES-REDUCE";
2408   case ResourceDemand: return "RES-DEMAND";
2409   case TopDepthReduce: return "TOP-DEPTH ";
2410   case TopPathReduce:  return "TOP-PATH  ";
2411   case BotHeightReduce:return "BOT-HEIGHT";
2412   case BotPathReduce:  return "BOT-PATH  ";
2413   case NextDefUse:     return "DEF-USE   ";
2414   case NodeOrder:      return "ORDER     ";
2415   };
2416   llvm_unreachable("Unknown reason!");
2417 }
2418 
2419 void GenericSchedulerBase::traceCandidate(const SchedCandidate &Cand) {
2420   PressureChange P;
2421   unsigned ResIdx = 0;
2422   unsigned Latency = 0;
2423   switch (Cand.Reason) {
2424   default:
2425     break;
2426   case RegExcess:
2427     P = Cand.RPDelta.Excess;
2428     break;
2429   case RegCritical:
2430     P = Cand.RPDelta.CriticalMax;
2431     break;
2432   case RegMax:
2433     P = Cand.RPDelta.CurrentMax;
2434     break;
2435   case ResourceReduce:
2436     ResIdx = Cand.Policy.ReduceResIdx;
2437     break;
2438   case ResourceDemand:
2439     ResIdx = Cand.Policy.DemandResIdx;
2440     break;
2441   case TopDepthReduce:
2442     Latency = Cand.SU->getDepth();
2443     break;
2444   case TopPathReduce:
2445     Latency = Cand.SU->getHeight();
2446     break;
2447   case BotHeightReduce:
2448     Latency = Cand.SU->getHeight();
2449     break;
2450   case BotPathReduce:
2451     Latency = Cand.SU->getDepth();
2452     break;
2453   }
2454   dbgs() << "  Cand SU(" << Cand.SU->NodeNum << ") " << getReasonStr(Cand.Reason);
2455   if (P.isValid())
2456     dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
2457            << ":" << P.getUnitInc() << " ";
2458   else
2459     dbgs() << "      ";
2460   if (ResIdx)
2461     dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
2462   else
2463     dbgs() << "         ";
2464   if (Latency)
2465     dbgs() << " " << Latency << " cycles ";
2466   else
2467     dbgs() << "          ";
2468   dbgs() << '\n';
2469 }
2470 #endif
2471 
2472 /// Return true if this heuristic determines order.
2473 static bool tryLess(int TryVal, int CandVal,
2474                     GenericSchedulerBase::SchedCandidate &TryCand,
2475                     GenericSchedulerBase::SchedCandidate &Cand,
2476                     GenericSchedulerBase::CandReason Reason) {
2477   if (TryVal < CandVal) {
2478     TryCand.Reason = Reason;
2479     return true;
2480   }
2481   if (TryVal > CandVal) {
2482     if (Cand.Reason > Reason)
2483       Cand.Reason = Reason;
2484     return true;
2485   }
2486   Cand.setRepeat(Reason);
2487   return false;
2488 }
2489 
2490 static bool tryGreater(int TryVal, int CandVal,
2491                        GenericSchedulerBase::SchedCandidate &TryCand,
2492                        GenericSchedulerBase::SchedCandidate &Cand,
2493                        GenericSchedulerBase::CandReason Reason) {
2494   if (TryVal > CandVal) {
2495     TryCand.Reason = Reason;
2496     return true;
2497   }
2498   if (TryVal < CandVal) {
2499     if (Cand.Reason > Reason)
2500       Cand.Reason = Reason;
2501     return true;
2502   }
2503   Cand.setRepeat(Reason);
2504   return false;
2505 }
2506 
2507 static bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand,
2508                        GenericSchedulerBase::SchedCandidate &Cand,
2509                        SchedBoundary &Zone) {
2510   if (Zone.isTop()) {
2511     if (Cand.SU->getDepth() > Zone.getScheduledLatency()) {
2512       if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2513                   TryCand, Cand, GenericSchedulerBase::TopDepthReduce))
2514         return true;
2515     }
2516     if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2517                    TryCand, Cand, GenericSchedulerBase::TopPathReduce))
2518       return true;
2519   } else {
2520     if (Cand.SU->getHeight() > Zone.getScheduledLatency()) {
2521       if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
2522                   TryCand, Cand, GenericSchedulerBase::BotHeightReduce))
2523         return true;
2524     }
2525     if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
2526                    TryCand, Cand, GenericSchedulerBase::BotPathReduce))
2527       return true;
2528   }
2529   return false;
2530 }
2531 
2532 static void tracePick(GenericSchedulerBase::CandReason Reason, bool IsTop) {
2533   DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ")
2534         << GenericSchedulerBase::getReasonStr(Reason) << '\n');
2535 }
2536 
2537 static void tracePick(const GenericSchedulerBase::SchedCandidate &Cand,
2538                       bool IsTop) {
2539   tracePick(Cand.Reason, IsTop);
2540 }
2541 
2542 void GenericScheduler::initialize(ScheduleDAGMI *dag) {
2543   assert(dag->hasVRegLiveness() &&
2544          "(PreRA)GenericScheduler needs vreg liveness");
2545   DAG = static_cast<ScheduleDAGMILive*>(dag);
2546   SchedModel = DAG->getSchedModel();
2547   TRI = DAG->TRI;
2548 
2549   Rem.init(DAG, SchedModel);
2550   Top.init(DAG, SchedModel, &Rem);
2551   Bot.init(DAG, SchedModel, &Rem);
2552 
2553   // Initialize resource counts.
2554 
2555   // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
2556   // are disabled, then these HazardRecs will be disabled.
2557   const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
2558   if (!Top.HazardRec) {
2559     Top.HazardRec =
2560         DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
2561             Itin, DAG);
2562   }
2563   if (!Bot.HazardRec) {
2564     Bot.HazardRec =
2565         DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
2566             Itin, DAG);
2567   }
2568 }
2569 
2570 /// Initialize the per-region scheduling policy.
2571 void GenericScheduler::initPolicy(MachineBasicBlock::iterator Begin,
2572                                   MachineBasicBlock::iterator End,
2573                                   unsigned NumRegionInstrs) {
2574   const MachineFunction &MF = *Begin->getParent()->getParent();
2575   const TargetLowering *TLI = MF.getSubtarget().getTargetLowering();
2576 
2577   // Avoid setting up the register pressure tracker for small regions to save
2578   // compile time. As a rough heuristic, only track pressure when the number of
2579   // schedulable instructions exceeds half the integer register file.
2580   RegionPolicy.ShouldTrackPressure = true;
2581   for (unsigned VT = MVT::i32; VT > (unsigned)MVT::i1; --VT) {
2582     MVT::SimpleValueType LegalIntVT = (MVT::SimpleValueType)VT;
2583     if (TLI->isTypeLegal(LegalIntVT)) {
2584       unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
2585         TLI->getRegClassFor(LegalIntVT));
2586       RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
2587     }
2588   }
2589 
2590   // For generic targets, we default to bottom-up, because it's simpler and more
2591   // compile-time optimizations have been implemented in that direction.
2592   RegionPolicy.OnlyBottomUp = true;
2593 
2594   // Allow the subtarget to override default policy.
2595   MF.getSubtarget().overrideSchedPolicy(RegionPolicy, Begin, End,
2596                                         NumRegionInstrs);
2597 
2598   // After subtarget overrides, apply command line options.
2599   if (!EnableRegPressure)
2600     RegionPolicy.ShouldTrackPressure = false;
2601 
2602   // Check -misched-topdown/bottomup can force or unforce scheduling direction.
2603   // e.g. -misched-bottomup=false allows scheduling in both directions.
2604   assert((!ForceTopDown || !ForceBottomUp) &&
2605          "-misched-topdown incompatible with -misched-bottomup");
2606   if (ForceBottomUp.getNumOccurrences() > 0) {
2607     RegionPolicy.OnlyBottomUp = ForceBottomUp;
2608     if (RegionPolicy.OnlyBottomUp)
2609       RegionPolicy.OnlyTopDown = false;
2610   }
2611   if (ForceTopDown.getNumOccurrences() > 0) {
2612     RegionPolicy.OnlyTopDown = ForceTopDown;
2613     if (RegionPolicy.OnlyTopDown)
2614       RegionPolicy.OnlyBottomUp = false;
2615   }
2616 }
2617 
2618 void GenericScheduler::dumpPolicy() {
2619   dbgs() << "GenericScheduler RegionPolicy: "
2620          << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
2621          << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
2622          << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
2623          << "\n";
2624 }
2625 
2626 /// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
2627 /// critical path by more cycles than it takes to drain the instruction buffer.
2628 /// We estimate an upper bounds on in-flight instructions as:
2629 ///
2630 /// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
2631 /// InFlightIterations = AcyclicPath / CyclesPerIteration
2632 /// InFlightResources = InFlightIterations * LoopResources
2633 ///
2634 /// TODO: Check execution resources in addition to IssueCount.
2635 void GenericScheduler::checkAcyclicLatency() {
2636   if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
2637     return;
2638 
2639   // Scaled number of cycles per loop iteration.
2640   unsigned IterCount =
2641     std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
2642              Rem.RemIssueCount);
2643   // Scaled acyclic critical path.
2644   unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
2645   // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
2646   unsigned InFlightCount =
2647     (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
2648   unsigned BufferLimit =
2649     SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
2650 
2651   Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
2652 
2653   DEBUG(dbgs() << "IssueCycles="
2654         << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
2655         << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
2656         << "c NumIters=" << (AcyclicCount + IterCount-1) / IterCount
2657         << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
2658         << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
2659         if (Rem.IsAcyclicLatencyLimited)
2660           dbgs() << "  ACYCLIC LATENCY LIMIT\n");
2661 }
2662 
2663 void GenericScheduler::registerRoots() {
2664   Rem.CriticalPath = DAG->ExitSU.getDepth();
2665 
2666   // Some roots may not feed into ExitSU. Check all of them in case.
2667   for (std::vector<SUnit*>::const_iterator
2668          I = Bot.Available.begin(), E = Bot.Available.end(); I != E; ++I) {
2669     if ((*I)->getDepth() > Rem.CriticalPath)
2670       Rem.CriticalPath = (*I)->getDepth();
2671   }
2672   DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
2673   if (DumpCriticalPathLength) {
2674     errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
2675   }
2676 
2677   if (EnableCyclicPath) {
2678     Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
2679     checkAcyclicLatency();
2680   }
2681 }
2682 
2683 static bool tryPressure(const PressureChange &TryP,
2684                         const PressureChange &CandP,
2685                         GenericSchedulerBase::SchedCandidate &TryCand,
2686                         GenericSchedulerBase::SchedCandidate &Cand,
2687                         GenericSchedulerBase::CandReason Reason,
2688                         const TargetRegisterInfo *TRI,
2689                         const MachineFunction &MF) {
2690   unsigned TryPSet = TryP.getPSetOrMax();
2691   unsigned CandPSet = CandP.getPSetOrMax();
2692   // If both candidates affect the same set, go with the smallest increase.
2693   if (TryPSet == CandPSet) {
2694     return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
2695                    Reason);
2696   }
2697   // If one candidate decreases and the other increases, go with it.
2698   // Invalid candidates have UnitInc==0.
2699   if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
2700                  Reason)) {
2701     return true;
2702   }
2703 
2704   int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
2705                                  std::numeric_limits<int>::max();
2706 
2707   int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
2708                                    std::numeric_limits<int>::max();
2709 
2710   // If the candidates are decreasing pressure, reverse priority.
2711   if (TryP.getUnitInc() < 0)
2712     std::swap(TryRank, CandRank);
2713   return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
2714 }
2715 
2716 static unsigned getWeakLeft(const SUnit *SU, bool isTop) {
2717   return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
2718 }
2719 
2720 /// Minimize physical register live ranges. Regalloc wants them adjacent to
2721 /// their physreg def/use.
2722 ///
2723 /// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
2724 /// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
2725 /// with the operation that produces or consumes the physreg. We'll do this when
2726 /// regalloc has support for parallel copies.
2727 static int biasPhysRegCopy(const SUnit *SU, bool isTop) {
2728   const MachineInstr *MI = SU->getInstr();
2729   if (!MI->isCopy())
2730     return 0;
2731 
2732   unsigned ScheduledOper = isTop ? 1 : 0;
2733   unsigned UnscheduledOper = isTop ? 0 : 1;
2734   // If we have already scheduled the physreg produce/consumer, immediately
2735   // schedule the copy.
2736   if (TargetRegisterInfo::isPhysicalRegister(
2737         MI->getOperand(ScheduledOper).getReg()))
2738     return 1;
2739   // If the physreg is at the boundary, defer it. Otherwise schedule it
2740   // immediately to free the dependent. We can hoist the copy later.
2741   bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
2742   if (TargetRegisterInfo::isPhysicalRegister(
2743         MI->getOperand(UnscheduledOper).getReg()))
2744     return AtBoundary ? -1 : 1;
2745   return 0;
2746 }
2747 
2748 void GenericScheduler::initCandidate(SchedCandidate &Cand, SUnit *SU,
2749                                      bool AtTop,
2750                                      const RegPressureTracker &RPTracker,
2751                                      RegPressureTracker &TempTracker) {
2752   Cand.SU = SU;
2753   if (DAG->isTrackingPressure()) {
2754     if (AtTop) {
2755       TempTracker.getMaxDownwardPressureDelta(
2756         Cand.SU->getInstr(),
2757         Cand.RPDelta,
2758         DAG->getRegionCriticalPSets(),
2759         DAG->getRegPressure().MaxSetPressure);
2760     } else {
2761       if (VerifyScheduling) {
2762         TempTracker.getMaxUpwardPressureDelta(
2763           Cand.SU->getInstr(),
2764           &DAG->getPressureDiff(Cand.SU),
2765           Cand.RPDelta,
2766           DAG->getRegionCriticalPSets(),
2767           DAG->getRegPressure().MaxSetPressure);
2768       } else {
2769         RPTracker.getUpwardPressureDelta(
2770           Cand.SU->getInstr(),
2771           DAG->getPressureDiff(Cand.SU),
2772           Cand.RPDelta,
2773           DAG->getRegionCriticalPSets(),
2774           DAG->getRegPressure().MaxSetPressure);
2775       }
2776     }
2777   }
2778   DEBUG(if (Cand.RPDelta.Excess.isValid())
2779           dbgs() << "  Try  SU(" << Cand.SU->NodeNum << ") "
2780                  << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet())
2781                  << ":" << Cand.RPDelta.Excess.getUnitInc() << "\n");
2782 }
2783 
2784 /// Apply a set of heursitics to a new candidate. Heuristics are currently
2785 /// hierarchical. This may be more efficient than a graduated cost model because
2786 /// we don't need to evaluate all aspects of the model for each node in the
2787 /// queue. But it's really done to make the heuristics easier to debug and
2788 /// statistically analyze.
2789 ///
2790 /// \param Cand provides the policy and current best candidate.
2791 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
2792 /// \param Zone describes the scheduled zone that we are extending.
2793 void GenericScheduler::tryCandidate(SchedCandidate &Cand,
2794                                     SchedCandidate &TryCand,
2795                                     SchedBoundary &Zone) {
2796   // Initialize the candidate if needed.
2797   if (!Cand.isValid()) {
2798     TryCand.Reason = NodeOrder;
2799     return;
2800   }
2801 
2802   if (tryGreater(biasPhysRegCopy(TryCand.SU, Zone.isTop()),
2803                  biasPhysRegCopy(Cand.SU, Zone.isTop()),
2804                  TryCand, Cand, PhysRegCopy))
2805     return;
2806 
2807   // Avoid exceeding the target's limit.
2808   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
2809                                                Cand.RPDelta.Excess,
2810                                                TryCand, Cand, RegExcess, TRI,
2811                                                DAG->MF))
2812     return;
2813 
2814   // Avoid increasing the max critical pressure in the scheduled region.
2815   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
2816                                                Cand.RPDelta.CriticalMax,
2817                                                TryCand, Cand, RegCritical, TRI,
2818                                                DAG->MF))
2819     return;
2820 
2821   // For loops that are acyclic path limited, aggressively schedule for latency.
2822   // This can result in very long dependence chains scheduled in sequence, so
2823   // once every cycle (when CurrMOps == 0), switch to normal heuristics.
2824   if (Rem.IsAcyclicLatencyLimited && !Zone.getCurrMOps()
2825       && tryLatency(TryCand, Cand, Zone))
2826     return;
2827 
2828   // Prioritize instructions that read unbuffered resources by stall cycles.
2829   if (tryLess(Zone.getLatencyStallCycles(TryCand.SU),
2830               Zone.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
2831     return;
2832 
2833   // Keep clustered nodes together to encourage downstream peephole
2834   // optimizations which may reduce resource requirements.
2835   //
2836   // This is a best effort to set things up for a post-RA pass. Optimizations
2837   // like generating loads of multiple registers should ideally be done within
2838   // the scheduler pass by combining the loads during DAG postprocessing.
2839   const SUnit *NextClusterSU =
2840     Zone.isTop() ? DAG->getNextClusterSucc() : DAG->getNextClusterPred();
2841   if (tryGreater(TryCand.SU == NextClusterSU, Cand.SU == NextClusterSU,
2842                  TryCand, Cand, Cluster))
2843     return;
2844 
2845   // Weak edges are for clustering and other constraints.
2846   if (tryLess(getWeakLeft(TryCand.SU, Zone.isTop()),
2847               getWeakLeft(Cand.SU, Zone.isTop()),
2848               TryCand, Cand, Weak)) {
2849     return;
2850   }
2851   // Avoid increasing the max pressure of the entire region.
2852   if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
2853                                                Cand.RPDelta.CurrentMax,
2854                                                TryCand, Cand, RegMax, TRI,
2855                                                DAG->MF))
2856     return;
2857 
2858   // Avoid critical resource consumption and balance the schedule.
2859   TryCand.initResourceDelta(DAG, SchedModel);
2860   if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
2861               TryCand, Cand, ResourceReduce))
2862     return;
2863   if (tryGreater(TryCand.ResDelta.DemandedResources,
2864                  Cand.ResDelta.DemandedResources,
2865                  TryCand, Cand, ResourceDemand))
2866     return;
2867 
2868   // Avoid serializing long latency dependence chains.
2869   // For acyclic path limited loops, latency was already checked above.
2870   if (!RegionPolicy.DisableLatencyHeuristic && Cand.Policy.ReduceLatency &&
2871       !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, Zone)) {
2872     return;
2873   }
2874 
2875   // Prefer immediate defs/users of the last scheduled instruction. This is a
2876   // local pressure avoidance strategy that also makes the machine code
2877   // readable.
2878   if (tryGreater(Zone.isNextSU(TryCand.SU), Zone.isNextSU(Cand.SU),
2879                  TryCand, Cand, NextDefUse))
2880     return;
2881 
2882   // Fall through to original instruction order.
2883   if ((Zone.isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
2884       || (!Zone.isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
2885     TryCand.Reason = NodeOrder;
2886   }
2887 }
2888 
2889 /// Pick the best candidate from the queue.
2890 ///
2891 /// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
2892 /// DAG building. To adjust for the current scheduling location we need to
2893 /// maintain the number of vreg uses remaining to be top-scheduled.
2894 void GenericScheduler::pickNodeFromQueue(SchedBoundary &Zone,
2895                                          const RegPressureTracker &RPTracker,
2896                                          SchedCandidate &Cand) {
2897   ReadyQueue &Q = Zone.Available;
2898 
2899   DEBUG(Q.dump());
2900 
2901   // getMaxPressureDelta temporarily modifies the tracker.
2902   RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
2903 
2904   for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
2905 
2906     SchedCandidate TryCand(Cand.Policy);
2907     initCandidate(TryCand, *I, Zone.isTop(), RPTracker, TempTracker);
2908     tryCandidate(Cand, TryCand, Zone);
2909     if (TryCand.Reason != NoCand) {
2910       // Initialize resource delta if needed in case future heuristics query it.
2911       if (TryCand.ResDelta == SchedResourceDelta())
2912         TryCand.initResourceDelta(DAG, SchedModel);
2913       Cand.setBest(TryCand);
2914       DEBUG(traceCandidate(Cand));
2915     }
2916   }
2917 }
2918 
2919 /// Pick the best candidate node from either the top or bottom queue.
2920 SUnit *GenericScheduler::pickNodeBidirectional(bool &IsTopNode) {
2921   // Schedule as far as possible in the direction of no choice. This is most
2922   // efficient, but also provides the best heuristics for CriticalPSets.
2923   if (SUnit *SU = Bot.pickOnlyChoice()) {
2924     IsTopNode = false;
2925     tracePick(Only1, false);
2926     return SU;
2927   }
2928   if (SUnit *SU = Top.pickOnlyChoice()) {
2929     IsTopNode = true;
2930     tracePick(Only1, true);
2931     return SU;
2932   }
2933   CandPolicy NoPolicy;
2934   SchedCandidate BotCand(NoPolicy);
2935   SchedCandidate TopCand(NoPolicy);
2936   // Set the bottom-up policy based on the state of the current bottom zone and
2937   // the instructions outside the zone, including the top zone.
2938   setPolicy(BotCand.Policy, /*IsPostRA=*/false, Bot, &Top);
2939   // Set the top-down policy based on the state of the current top zone and
2940   // the instructions outside the zone, including the bottom zone.
2941   setPolicy(TopCand.Policy, /*IsPostRA=*/false, Top, &Bot);
2942 
2943   // Prefer bottom scheduling when heuristics are silent.
2944   pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
2945   assert(BotCand.Reason != NoCand && "failed to find the first candidate");
2946 
2947   // If either Q has a single candidate that provides the least increase in
2948   // Excess pressure, we can immediately schedule from that Q.
2949   //
2950   // RegionCriticalPSets summarizes the pressure within the scheduled region and
2951   // affects picking from either Q. If scheduling in one direction must
2952   // increase pressure for one of the excess PSets, then schedule in that
2953   // direction first to provide more freedom in the other direction.
2954   if ((BotCand.Reason == RegExcess && !BotCand.isRepeat(RegExcess))
2955       || (BotCand.Reason == RegCritical && !BotCand.isRepeat(RegCritical)))
2956   {
2957     IsTopNode = false;
2958     tracePick(BotCand, IsTopNode);
2959     return BotCand.SU;
2960   }
2961   // Check if the top Q has a better candidate.
2962   pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2963   assert(TopCand.Reason != NoCand && "failed to find the first candidate");
2964 
2965   // Choose the queue with the most important (lowest enum) reason.
2966   if (TopCand.Reason < BotCand.Reason) {
2967     IsTopNode = true;
2968     tracePick(TopCand, IsTopNode);
2969     return TopCand.SU;
2970   }
2971   // Otherwise prefer the bottom candidate, in node order if all else failed.
2972   IsTopNode = false;
2973   tracePick(BotCand, IsTopNode);
2974   return BotCand.SU;
2975 }
2976 
2977 /// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
2978 SUnit *GenericScheduler::pickNode(bool &IsTopNode) {
2979   if (DAG->top() == DAG->bottom()) {
2980     assert(Top.Available.empty() && Top.Pending.empty() &&
2981            Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
2982     return nullptr;
2983   }
2984   SUnit *SU;
2985   do {
2986     if (RegionPolicy.OnlyTopDown) {
2987       SU = Top.pickOnlyChoice();
2988       if (!SU) {
2989         CandPolicy NoPolicy;
2990         SchedCandidate TopCand(NoPolicy);
2991         pickNodeFromQueue(Top, DAG->getTopRPTracker(), TopCand);
2992         assert(TopCand.Reason != NoCand && "failed to find a candidate");
2993         tracePick(TopCand, true);
2994         SU = TopCand.SU;
2995       }
2996       IsTopNode = true;
2997     } else if (RegionPolicy.OnlyBottomUp) {
2998       SU = Bot.pickOnlyChoice();
2999       if (!SU) {
3000         CandPolicy NoPolicy;
3001         SchedCandidate BotCand(NoPolicy);
3002         pickNodeFromQueue(Bot, DAG->getBotRPTracker(), BotCand);
3003         assert(BotCand.Reason != NoCand && "failed to find a candidate");
3004         tracePick(BotCand, false);
3005         SU = BotCand.SU;
3006       }
3007       IsTopNode = false;
3008     } else {
3009       SU = pickNodeBidirectional(IsTopNode);
3010     }
3011   } while (SU->isScheduled);
3012 
3013   if (SU->isTopReady())
3014     Top.removeReady(SU);
3015   if (SU->isBottomReady())
3016     Bot.removeReady(SU);
3017 
3018   DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3019   return SU;
3020 }
3021 
3022 void GenericScheduler::reschedulePhysRegCopies(SUnit *SU, bool isTop) {
3023 
3024   MachineBasicBlock::iterator InsertPos = SU->getInstr();
3025   if (!isTop)
3026     ++InsertPos;
3027   SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
3028 
3029   // Find already scheduled copies with a single physreg dependence and move
3030   // them just above the scheduled instruction.
3031   for (SmallVectorImpl<SDep>::iterator I = Deps.begin(), E = Deps.end();
3032        I != E; ++I) {
3033     if (I->getKind() != SDep::Data || !TRI->isPhysicalRegister(I->getReg()))
3034       continue;
3035     SUnit *DepSU = I->getSUnit();
3036     if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
3037       continue;
3038     MachineInstr *Copy = DepSU->getInstr();
3039     if (!Copy->isCopy())
3040       continue;
3041     DEBUG(dbgs() << "  Rescheduling physreg copy ";
3042           I->getSUnit()->dump(DAG));
3043     DAG->moveInstruction(Copy, InsertPos);
3044   }
3045 }
3046 
3047 /// Update the scheduler's state after scheduling a node. This is the same node
3048 /// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
3049 /// update it's state based on the current cycle before MachineSchedStrategy
3050 /// does.
3051 ///
3052 /// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
3053 /// them here. See comments in biasPhysRegCopy.
3054 void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3055   if (IsTopNode) {
3056     SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3057     Top.bumpNode(SU);
3058     if (SU->hasPhysRegUses)
3059       reschedulePhysRegCopies(SU, true);
3060   } else {
3061     SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
3062     Bot.bumpNode(SU);
3063     if (SU->hasPhysRegDefs)
3064       reschedulePhysRegCopies(SU, false);
3065   }
3066 }
3067 
3068 /// Create the standard converging machine scheduler. This will be used as the
3069 /// default scheduler if the target does not set a default.
3070 static ScheduleDAGInstrs *createGenericSchedLive(MachineSchedContext *C) {
3071   ScheduleDAGMILive *DAG = new ScheduleDAGMILive(C, make_unique<GenericScheduler>(C));
3072   // Register DAG post-processors.
3073   //
3074   // FIXME: extend the mutation API to allow earlier mutations to instantiate
3075   // data and pass it to later mutations. Have a single mutation that gathers
3076   // the interesting nodes in one pass.
3077   DAG->addMutation(make_unique<CopyConstrain>(DAG->TII, DAG->TRI));
3078   if (EnableMemOpCluster) {
3079     if (DAG->TII->enableClusterLoads())
3080       DAG->addMutation(make_unique<LoadClusterMutation>(DAG->TII, DAG->TRI));
3081     if (DAG->TII->enableClusterStores())
3082       DAG->addMutation(make_unique<StoreClusterMutation>(DAG->TII, DAG->TRI));
3083   }
3084   if (EnableMacroFusion)
3085     DAG->addMutation(make_unique<MacroFusion>(*DAG->TII, *DAG->TRI));
3086   return DAG;
3087 }
3088 
3089 static MachineSchedRegistry
3090 GenericSchedRegistry("converge", "Standard converging scheduler.",
3091                      createGenericSchedLive);
3092 
3093 //===----------------------------------------------------------------------===//
3094 // PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
3095 //===----------------------------------------------------------------------===//
3096 
3097 void PostGenericScheduler::initialize(ScheduleDAGMI *Dag) {
3098   DAG = Dag;
3099   SchedModel = DAG->getSchedModel();
3100   TRI = DAG->TRI;
3101 
3102   Rem.init(DAG, SchedModel);
3103   Top.init(DAG, SchedModel, &Rem);
3104   BotRoots.clear();
3105 
3106   // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
3107   // or are disabled, then these HazardRecs will be disabled.
3108   const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
3109   if (!Top.HazardRec) {
3110     Top.HazardRec =
3111         DAG->MF.getSubtarget().getInstrInfo()->CreateTargetMIHazardRecognizer(
3112             Itin, DAG);
3113   }
3114 }
3115 
3116 
3117 void PostGenericScheduler::registerRoots() {
3118   Rem.CriticalPath = DAG->ExitSU.getDepth();
3119 
3120   // Some roots may not feed into ExitSU. Check all of them in case.
3121   for (SmallVectorImpl<SUnit*>::const_iterator
3122          I = BotRoots.begin(), E = BotRoots.end(); I != E; ++I) {
3123     if ((*I)->getDepth() > Rem.CriticalPath)
3124       Rem.CriticalPath = (*I)->getDepth();
3125   }
3126   DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
3127   if (DumpCriticalPathLength) {
3128     errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
3129   }
3130 }
3131 
3132 /// Apply a set of heursitics to a new candidate for PostRA scheduling.
3133 ///
3134 /// \param Cand provides the policy and current best candidate.
3135 /// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
3136 void PostGenericScheduler::tryCandidate(SchedCandidate &Cand,
3137                                         SchedCandidate &TryCand) {
3138 
3139   // Initialize the candidate if needed.
3140   if (!Cand.isValid()) {
3141     TryCand.Reason = NodeOrder;
3142     return;
3143   }
3144 
3145   // Prioritize instructions that read unbuffered resources by stall cycles.
3146   if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
3147               Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
3148     return;
3149 
3150   // Avoid critical resource consumption and balance the schedule.
3151   if (tryLess(TryCand.ResDelta.CritResources, Cand.ResDelta.CritResources,
3152               TryCand, Cand, ResourceReduce))
3153     return;
3154   if (tryGreater(TryCand.ResDelta.DemandedResources,
3155                  Cand.ResDelta.DemandedResources,
3156                  TryCand, Cand, ResourceDemand))
3157     return;
3158 
3159   // Avoid serializing long latency dependence chains.
3160   if (Cand.Policy.ReduceLatency && tryLatency(TryCand, Cand, Top)) {
3161     return;
3162   }
3163 
3164   // Fall through to original instruction order.
3165   if (TryCand.SU->NodeNum < Cand.SU->NodeNum)
3166     TryCand.Reason = NodeOrder;
3167 }
3168 
3169 void PostGenericScheduler::pickNodeFromQueue(SchedCandidate &Cand) {
3170   ReadyQueue &Q = Top.Available;
3171 
3172   DEBUG(Q.dump());
3173 
3174   for (ReadyQueue::iterator I = Q.begin(), E = Q.end(); I != E; ++I) {
3175     SchedCandidate TryCand(Cand.Policy);
3176     TryCand.SU = *I;
3177     TryCand.initResourceDelta(DAG, SchedModel);
3178     tryCandidate(Cand, TryCand);
3179     if (TryCand.Reason != NoCand) {
3180       Cand.setBest(TryCand);
3181       DEBUG(traceCandidate(Cand));
3182     }
3183   }
3184 }
3185 
3186 /// Pick the next node to schedule.
3187 SUnit *PostGenericScheduler::pickNode(bool &IsTopNode) {
3188   if (DAG->top() == DAG->bottom()) {
3189     assert(Top.Available.empty() && Top.Pending.empty() && "ReadyQ garbage");
3190     return nullptr;
3191   }
3192   SUnit *SU;
3193   do {
3194     SU = Top.pickOnlyChoice();
3195     if (SU) {
3196       tracePick(Only1, true);
3197     } else {
3198       CandPolicy NoPolicy;
3199       SchedCandidate TopCand(NoPolicy);
3200       // Set the top-down policy based on the state of the current top zone and
3201       // the instructions outside the zone, including the bottom zone.
3202       setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
3203       pickNodeFromQueue(TopCand);
3204       assert(TopCand.Reason != NoCand && "failed to find a candidate");
3205       tracePick(TopCand, true);
3206       SU = TopCand.SU;
3207     }
3208   } while (SU->isScheduled);
3209 
3210   IsTopNode = true;
3211   Top.removeReady(SU);
3212 
3213   DEBUG(dbgs() << "Scheduling SU(" << SU->NodeNum << ") " << *SU->getInstr());
3214   return SU;
3215 }
3216 
3217 /// Called after ScheduleDAGMI has scheduled an instruction and updated
3218 /// scheduled/remaining flags in the DAG nodes.
3219 void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
3220   SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
3221   Top.bumpNode(SU);
3222 }
3223 
3224 /// Create a generic scheduler with no vreg liveness or DAG mutation passes.
3225 static ScheduleDAGInstrs *createGenericSchedPostRA(MachineSchedContext *C) {
3226   return new ScheduleDAGMI(C, make_unique<PostGenericScheduler>(C), /*IsPostRA=*/true);
3227 }
3228 
3229 //===----------------------------------------------------------------------===//
3230 // ILP Scheduler. Currently for experimental analysis of heuristics.
3231 //===----------------------------------------------------------------------===//
3232 
3233 namespace {
3234 /// \brief Order nodes by the ILP metric.
3235 struct ILPOrder {
3236   const SchedDFSResult *DFSResult;
3237   const BitVector *ScheduledTrees;
3238   bool MaximizeILP;
3239 
3240   ILPOrder(bool MaxILP)
3241     : DFSResult(nullptr), ScheduledTrees(nullptr), MaximizeILP(MaxILP) {}
3242 
3243   /// \brief Apply a less-than relation on node priority.
3244   ///
3245   /// (Return true if A comes after B in the Q.)
3246   bool operator()(const SUnit *A, const SUnit *B) const {
3247     unsigned SchedTreeA = DFSResult->getSubtreeID(A);
3248     unsigned SchedTreeB = DFSResult->getSubtreeID(B);
3249     if (SchedTreeA != SchedTreeB) {
3250       // Unscheduled trees have lower priority.
3251       if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
3252         return ScheduledTrees->test(SchedTreeB);
3253 
3254       // Trees with shallower connections have have lower priority.
3255       if (DFSResult->getSubtreeLevel(SchedTreeA)
3256           != DFSResult->getSubtreeLevel(SchedTreeB)) {
3257         return DFSResult->getSubtreeLevel(SchedTreeA)
3258           < DFSResult->getSubtreeLevel(SchedTreeB);
3259       }
3260     }
3261     if (MaximizeILP)
3262       return DFSResult->getILP(A) < DFSResult->getILP(B);
3263     else
3264       return DFSResult->getILP(A) > DFSResult->getILP(B);
3265   }
3266 };
3267 
3268 /// \brief Schedule based on the ILP metric.
3269 class ILPScheduler : public MachineSchedStrategy {
3270   ScheduleDAGMILive *DAG;
3271   ILPOrder Cmp;
3272 
3273   std::vector<SUnit*> ReadyQ;
3274 public:
3275   ILPScheduler(bool MaximizeILP): DAG(nullptr), Cmp(MaximizeILP) {}
3276 
3277   void initialize(ScheduleDAGMI *dag) override {
3278     assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
3279     DAG = static_cast<ScheduleDAGMILive*>(dag);
3280     DAG->computeDFSResult();
3281     Cmp.DFSResult = DAG->getDFSResult();
3282     Cmp.ScheduledTrees = &DAG->getScheduledTrees();
3283     ReadyQ.clear();
3284   }
3285 
3286   void registerRoots() override {
3287     // Restore the heap in ReadyQ with the updated DFS results.
3288     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3289   }
3290 
3291   /// Implement MachineSchedStrategy interface.
3292   /// -----------------------------------------
3293 
3294   /// Callback to select the highest priority node from the ready Q.
3295   SUnit *pickNode(bool &IsTopNode) override {
3296     if (ReadyQ.empty()) return nullptr;
3297     std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3298     SUnit *SU = ReadyQ.back();
3299     ReadyQ.pop_back();
3300     IsTopNode = false;
3301     DEBUG(dbgs() << "Pick node " << "SU(" << SU->NodeNum << ") "
3302           << " ILP: " << DAG->getDFSResult()->getILP(SU)
3303           << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU) << " @"
3304           << DAG->getDFSResult()->getSubtreeLevel(
3305             DAG->getDFSResult()->getSubtreeID(SU)) << '\n'
3306           << "Scheduling " << *SU->getInstr());
3307     return SU;
3308   }
3309 
3310   /// \brief Scheduler callback to notify that a new subtree is scheduled.
3311   void scheduleTree(unsigned SubtreeID) override {
3312     std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3313   }
3314 
3315   /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
3316   /// DFSResults, and resort the priority Q.
3317   void schedNode(SUnit *SU, bool IsTopNode) override {
3318     assert(!IsTopNode && "SchedDFSResult needs bottom-up");
3319   }
3320 
3321   void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
3322 
3323   void releaseBottomNode(SUnit *SU) override {
3324     ReadyQ.push_back(SU);
3325     std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
3326   }
3327 };
3328 } // namespace
3329 
3330 static ScheduleDAGInstrs *createILPMaxScheduler(MachineSchedContext *C) {
3331   return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(true));
3332 }
3333 static ScheduleDAGInstrs *createILPMinScheduler(MachineSchedContext *C) {
3334   return new ScheduleDAGMILive(C, make_unique<ILPScheduler>(false));
3335 }
3336 static MachineSchedRegistry ILPMaxRegistry(
3337   "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
3338 static MachineSchedRegistry ILPMinRegistry(
3339   "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
3340 
3341 //===----------------------------------------------------------------------===//
3342 // Machine Instruction Shuffler for Correctness Testing
3343 //===----------------------------------------------------------------------===//
3344 
3345 #ifndef NDEBUG
3346 namespace {
3347 /// Apply a less-than relation on the node order, which corresponds to the
3348 /// instruction order prior to scheduling. IsReverse implements greater-than.
3349 template<bool IsReverse>
3350 struct SUnitOrder {
3351   bool operator()(SUnit *A, SUnit *B) const {
3352     if (IsReverse)
3353       return A->NodeNum > B->NodeNum;
3354     else
3355       return A->NodeNum < B->NodeNum;
3356   }
3357 };
3358 
3359 /// Reorder instructions as much as possible.
3360 class InstructionShuffler : public MachineSchedStrategy {
3361   bool IsAlternating;
3362   bool IsTopDown;
3363 
3364   // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
3365   // gives nodes with a higher number higher priority causing the latest
3366   // instructions to be scheduled first.
3367   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false> >
3368     TopQ;
3369   // When scheduling bottom-up, use greater-than as the queue priority.
3370   PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true> >
3371     BottomQ;
3372 public:
3373   InstructionShuffler(bool alternate, bool topdown)
3374     : IsAlternating(alternate), IsTopDown(topdown) {}
3375 
3376   void initialize(ScheduleDAGMI*) override {
3377     TopQ.clear();
3378     BottomQ.clear();
3379   }
3380 
3381   /// Implement MachineSchedStrategy interface.
3382   /// -----------------------------------------
3383 
3384   SUnit *pickNode(bool &IsTopNode) override {
3385     SUnit *SU;
3386     if (IsTopDown) {
3387       do {
3388         if (TopQ.empty()) return nullptr;
3389         SU = TopQ.top();
3390         TopQ.pop();
3391       } while (SU->isScheduled);
3392       IsTopNode = true;
3393     } else {
3394       do {
3395         if (BottomQ.empty()) return nullptr;
3396         SU = BottomQ.top();
3397         BottomQ.pop();
3398       } while (SU->isScheduled);
3399       IsTopNode = false;
3400     }
3401     if (IsAlternating)
3402       IsTopDown = !IsTopDown;
3403     return SU;
3404   }
3405 
3406   void schedNode(SUnit *SU, bool IsTopNode) override {}
3407 
3408   void releaseTopNode(SUnit *SU) override {
3409     TopQ.push(SU);
3410   }
3411   void releaseBottomNode(SUnit *SU) override {
3412     BottomQ.push(SU);
3413   }
3414 };
3415 } // namespace
3416 
3417 static ScheduleDAGInstrs *createInstructionShuffler(MachineSchedContext *C) {
3418   bool Alternate = !ForceTopDown && !ForceBottomUp;
3419   bool TopDown = !ForceBottomUp;
3420   assert((TopDown || !ForceTopDown) &&
3421          "-misched-topdown incompatible with -misched-bottomup");
3422   return new ScheduleDAGMILive(C, make_unique<InstructionShuffler>(Alternate, TopDown));
3423 }
3424 static MachineSchedRegistry ShufflerRegistry(
3425   "shuffle", "Shuffle machine instructions alternating directions",
3426   createInstructionShuffler);
3427 #endif // !NDEBUG
3428 
3429 //===----------------------------------------------------------------------===//
3430 // GraphWriter support for ScheduleDAGMILive.
3431 //===----------------------------------------------------------------------===//
3432 
3433 #ifndef NDEBUG
3434 namespace llvm {
3435 
3436 template<> struct GraphTraits<
3437   ScheduleDAGMI*> : public GraphTraits<ScheduleDAG*> {};
3438 
3439 template<>
3440 struct DOTGraphTraits<ScheduleDAGMI*> : public DefaultDOTGraphTraits {
3441 
3442   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
3443 
3444   static std::string getGraphName(const ScheduleDAG *G) {
3445     return G->MF.getName();
3446   }
3447 
3448   static bool renderGraphFromBottomUp() {
3449     return true;
3450   }
3451 
3452   static bool isNodeHidden(const SUnit *Node) {
3453     if (ViewMISchedCutoff == 0)
3454       return false;
3455     return (Node->Preds.size() > ViewMISchedCutoff
3456          || Node->Succs.size() > ViewMISchedCutoff);
3457   }
3458 
3459   /// If you want to override the dot attributes printed for a particular
3460   /// edge, override this method.
3461   static std::string getEdgeAttributes(const SUnit *Node,
3462                                        SUnitIterator EI,
3463                                        const ScheduleDAG *Graph) {
3464     if (EI.isArtificialDep())
3465       return "color=cyan,style=dashed";
3466     if (EI.isCtrlDep())
3467       return "color=blue,style=dashed";
3468     return "";
3469   }
3470 
3471   static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
3472     std::string Str;
3473     raw_string_ostream SS(Str);
3474     const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3475     const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3476       static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
3477     SS << "SU:" << SU->NodeNum;
3478     if (DFS)
3479       SS << " I:" << DFS->getNumInstrs(SU);
3480     return SS.str();
3481   }
3482   static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
3483     return G->getGraphNodeLabel(SU);
3484   }
3485 
3486   static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
3487     std::string Str("shape=Mrecord");
3488     const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
3489     const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
3490       static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
3491     if (DFS) {
3492       Str += ",style=filled,fillcolor=\"#";
3493       Str += DOT::getColorString(DFS->getSubtreeID(N));
3494       Str += '"';
3495     }
3496     return Str;
3497   }
3498 };
3499 } // namespace llvm
3500 #endif // NDEBUG
3501 
3502 /// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
3503 /// rendered using 'dot'.
3504 ///
3505 void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
3506 #ifndef NDEBUG
3507   ViewGraph(this, Name, false, Title);
3508 #else
3509   errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
3510          << "systems with Graphviz or gv!\n";
3511 #endif  // NDEBUG
3512 }
3513 
3514 /// Out-of-line implementation with no arguments is handy for gdb.
3515 void ScheduleDAGMI::viewGraph() {
3516   viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
3517 }
3518