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