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