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