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