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