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