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