LLVM 24.0.0git
MachineScheduler.cpp
Go to the documentation of this file.
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
15#include "CodeGenOptions.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/Statistic.h"
53#include "llvm/Config/llvm-config.h"
55#include "llvm/MC/LaneBitmask.h"
56#include "llvm/Pass.h"
59#include "llvm/Support/Debug.h"
64#include <algorithm>
65#include <cassert>
66#include <cstdint>
67#include <iterator>
68#include <limits>
69#include <memory>
70#include <string>
71#include <tuple>
72#include <utility>
73#include <vector>
74
75using namespace llvm;
76
77#define DEBUG_TYPE "machine-scheduler"
78
79STATISTIC(NumInstrsInSourceOrderPreRA,
80 "Number of instructions in source order after pre-RA scheduling");
81STATISTIC(NumInstrsInSourceOrderPostRA,
82 "Number of instructions in source order after post-RA scheduling");
83STATISTIC(NumInstrsScheduledPreRA,
84 "Number of instructions scheduled by pre-RA scheduler");
85STATISTIC(NumInstrsScheduledPostRA,
86 "Number of instructions scheduled by post-RA scheduler");
87STATISTIC(NumClustered, "Number of load/store pairs clustered");
88
89STATISTIC(NumTopPreRA,
90 "Number of scheduling units chosen from top queue pre-RA");
91STATISTIC(NumBotPreRA,
92 "Number of scheduling units chosen from bottom queue pre-RA");
93STATISTIC(NumNoCandPreRA,
94 "Number of scheduling units chosen for NoCand heuristic pre-RA");
95STATISTIC(NumOnly1PreRA,
96 "Number of scheduling units chosen for Only1 heuristic pre-RA");
97STATISTIC(NumPhysRegPreRA,
98 "Number of scheduling units chosen for PhysReg heuristic pre-RA");
99STATISTIC(NumRegExcessPreRA,
100 "Number of scheduling units chosen for RegExcess heuristic pre-RA");
101STATISTIC(NumRegCriticalPreRA,
102 "Number of scheduling units chosen for RegCritical heuristic pre-RA");
103STATISTIC(NumStallPreRA,
104 "Number of scheduling units chosen for Stall heuristic pre-RA");
105STATISTIC(NumClusterPreRA,
106 "Number of scheduling units chosen for Cluster heuristic pre-RA");
107STATISTIC(NumWeakPreRA,
108 "Number of scheduling units chosen for Weak heuristic pre-RA");
109STATISTIC(NumRegMaxPreRA,
110 "Number of scheduling units chosen for RegMax heuristic pre-RA");
112 NumResourceReducePreRA,
113 "Number of scheduling units chosen for ResourceReduce heuristic pre-RA");
115 NumResourceDemandPreRA,
116 "Number of scheduling units chosen for ResourceDemand heuristic pre-RA");
118 NumTopDepthReducePreRA,
119 "Number of scheduling units chosen for TopDepthReduce heuristic pre-RA");
121 NumTopPathReducePreRA,
122 "Number of scheduling units chosen for TopPathReduce heuristic pre-RA");
124 NumBotHeightReducePreRA,
125 "Number of scheduling units chosen for BotHeightReduce heuristic pre-RA");
127 NumBotPathReducePreRA,
128 "Number of scheduling units chosen for BotPathReduce heuristic pre-RA");
129STATISTIC(NumNodeOrderPreRA,
130 "Number of scheduling units chosen for NodeOrder heuristic pre-RA");
131STATISTIC(NumFirstValidPreRA,
132 "Number of scheduling units chosen for FirstValid heuristic pre-RA");
133
134STATISTIC(NumTopPostRA,
135 "Number of scheduling units chosen from top queue post-RA");
136STATISTIC(NumBotPostRA,
137 "Number of scheduling units chosen from bottom queue post-RA");
138STATISTIC(NumNoCandPostRA,
139 "Number of scheduling units chosen for NoCand heuristic post-RA");
140STATISTIC(NumOnly1PostRA,
141 "Number of scheduling units chosen for Only1 heuristic post-RA");
142STATISTIC(NumPhysRegPostRA,
143 "Number of scheduling units chosen for PhysReg heuristic post-RA");
144STATISTIC(NumRegExcessPostRA,
145 "Number of scheduling units chosen for RegExcess heuristic post-RA");
147 NumRegCriticalPostRA,
148 "Number of scheduling units chosen for RegCritical heuristic post-RA");
149STATISTIC(NumStallPostRA,
150 "Number of scheduling units chosen for Stall heuristic post-RA");
151STATISTIC(NumClusterPostRA,
152 "Number of scheduling units chosen for Cluster heuristic post-RA");
153STATISTIC(NumWeakPostRA,
154 "Number of scheduling units chosen for Weak heuristic post-RA");
155STATISTIC(NumRegMaxPostRA,
156 "Number of scheduling units chosen for RegMax heuristic post-RA");
158 NumResourceReducePostRA,
159 "Number of scheduling units chosen for ResourceReduce heuristic post-RA");
161 NumResourceDemandPostRA,
162 "Number of scheduling units chosen for ResourceDemand heuristic post-RA");
164 NumTopDepthReducePostRA,
165 "Number of scheduling units chosen for TopDepthReduce heuristic post-RA");
167 NumTopPathReducePostRA,
168 "Number of scheduling units chosen for TopPathReduce heuristic post-RA");
170 NumBotHeightReducePostRA,
171 "Number of scheduling units chosen for BotHeightReduce heuristic post-RA");
173 NumBotPathReducePostRA,
174 "Number of scheduling units chosen for BotPathReduce heuristic post-RA");
175STATISTIC(NumNodeOrderPostRA,
176 "Number of scheduling units chosen for NodeOrder heuristic post-RA");
177STATISTIC(NumFirstValidPostRA,
178 "Number of scheduling units chosen for FirstValid heuristic post-RA");
179
181 "misched-postra-break-antideps", cl::Hidden,
182 cl::desc("Set the post-RA MISched anti-dependency break mode"),
183 cl::init(TargetSubtargetInfo::ANTIDEP_NONE),
184 cl::values(clEnumValN(TargetSubtargetInfo::ANTIDEP_NONE, "none",
185 "No anti-dependency breaking"),
186 clEnumValN(TargetSubtargetInfo::ANTIDEP_CRITICAL, "critical",
187 "Break critical-path anti-dependencies"),
188 clEnumValN(TargetSubtargetInfo::ANTIDEP_ALL, "all",
189 "Break all anti-dependencies")));
190
192 return getCodeGenOptions(MF).misched_prera_direction;
193}
198 return getCodeGenOptions(MF).verify_misched;
199}
201#ifndef NDEBUG
202 return getCodeGenOptions(MF).misched_print_dags;
203#else
204 return false;
205#endif
206}
208#ifndef NDEBUG
209 return getCodeGenOptions(MF).misched_view_dags;
210#else
211 return false;
212#endif
213}
214
215// DAG subtrees must have at least this many nodes.
216static const unsigned MinSubtreeSize = 8;
217
218// Pin the vtables to this file.
219void MachineSchedStrategy::anchor() {}
220
221void ScheduleDAGMutation::anchor() {}
222
223//===----------------------------------------------------------------------===//
224// Machine Instruction Scheduling Pass and Registry
225//===----------------------------------------------------------------------===//
226
229
230namespace llvm {
231namespace impl_detail {
232
233/// Base class for the machine scheduler classes.
235protected:
236 void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags);
237};
238
239/// Impl class for MachineScheduler.
241 // These are only for using MF.verify()
242 // remove when verify supports passing in all analyses
243 MachineFunctionPass *P = nullptr;
244 MachineFunctionAnalysisManager *MFAM = nullptr;
245
246public:
254
256 // Migration only
257 void setLegacyPass(MachineFunctionPass *P) { this->P = P; }
258 void setMFAM(MachineFunctionAnalysisManager *MFAM) { this->MFAM = MFAM; }
259
260 bool run(MachineFunction &MF, const TargetMachine &TM,
261 const RequiredAnalyses &Analyses);
262
263protected:
265};
266
267/// Impl class for SSAMachineScheduler.
269 // These are only for using MF.verify()
270 // remove when verify supports passing in all analyses
271 MachineFunctionPass *P = nullptr;
272 MachineFunctionAnalysisManager *MFAM = nullptr;
273
274public:
282
284 // Migration only
285 void setLegacyPass(MachineFunctionPass *P) { this->P = P; }
286 void setMFAM(MachineFunctionAnalysisManager *MFAM) { this->MFAM = MFAM; }
287
288 bool run(MachineFunction &MF, const TargetMachine &TM,
289 const RequiredAnalyses &Analyses);
290
291protected:
293};
294
295/// Impl class for PostMachineScheduler.
297 // These are only for using MF.verify()
298 // remove when verify supports passing in all analyses
299 MachineFunctionPass *P = nullptr;
300 MachineFunctionAnalysisManager *MFAM = nullptr;
301
302public:
309 // Migration only
310 void setLegacyPass(MachineFunctionPass *P) { this->P = P; }
311 void setMFAM(MachineFunctionAnalysisManager *MFAM) { this->MFAM = MFAM; }
312
313 bool run(MachineFunction &Func, const TargetMachine &TM,
314 const RequiredAnalyses &Analyses);
315
316protected:
318};
319
320} // namespace impl_detail
321} // namespace llvm
322
327
328namespace {
329/// MachineScheduler runs after coalescing and before register allocation.
330class MachineSchedulerLegacy : public MachineFunctionPass {
331 MachineSchedulerImpl Impl;
332
333public:
334 MachineSchedulerLegacy();
335 void getAnalysisUsage(AnalysisUsage &AU) const override;
336 bool runOnMachineFunction(MachineFunction&) override;
337
338 static char ID; // Class identification, replacement for typeinfo
339};
340
341/// SSAMachineScheduler runs before PHI elimination.
342class SSAMachineSchedulerLegacy : public MachineFunctionPass {
343 SSAMachineSchedulerImpl Impl;
344
345public:
346 SSAMachineSchedulerLegacy();
347 void getAnalysisUsage(AnalysisUsage &AU) const override;
348 bool runOnMachineFunction(MachineFunction &) override;
349
350 static char ID; // Class identification, replacement for typeinfo
351};
352
353/// PostMachineScheduler runs after shortly before code emission.
354class PostMachineSchedulerLegacy : public MachineFunctionPass {
355 PostMachineSchedulerImpl Impl;
356
357public:
358 PostMachineSchedulerLegacy();
359 void getAnalysisUsage(AnalysisUsage &AU) const override;
360 bool runOnMachineFunction(MachineFunction &) override;
361
362 static char ID; // Class identification, replacement for typeinfo
363};
364
365} // end anonymous namespace
366
367char MachineSchedulerLegacy::ID = 0;
368
369char &llvm::MachineSchedulerID = MachineSchedulerLegacy::ID;
370
371INITIALIZE_PASS_BEGIN(MachineSchedulerLegacy, DEBUG_TYPE,
372 "Machine Instruction Scheduler", false, false)
378INITIALIZE_PASS_END(MachineSchedulerLegacy, DEBUG_TYPE,
379 "Machine Instruction Scheduler", false, false)
380
381MachineSchedulerLegacy::MachineSchedulerLegacy() : MachineFunctionPass(ID) {}
382
383void MachineSchedulerLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
384 AU.setPreservesCFG();
394}
395
396char SSAMachineSchedulerLegacy::ID = 0;
397
398char &llvm::SSAMachineSchedulerID = SSAMachineSchedulerLegacy::ID;
399
400INITIALIZE_PASS_BEGIN(SSAMachineSchedulerLegacy, "ssa-machine-scheduler",
401 "SSA Machine Instruction Scheduler", false, false)
407INITIALIZE_PASS_END(SSAMachineSchedulerLegacy, "ssa-machine-scheduler",
408 "SSA Machine Instruction Scheduler", false, false)
409
410SSAMachineSchedulerLegacy::SSAMachineSchedulerLegacy()
411 : MachineFunctionPass(ID) {
413}
414
415void SSAMachineSchedulerLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
416 AU.setPreservesCFG();
426}
427
428char PostMachineSchedulerLegacy::ID = 0;
429
430char &llvm::PostMachineSchedulerID = PostMachineSchedulerLegacy::ID;
431
432INITIALIZE_PASS_BEGIN(PostMachineSchedulerLegacy, "postmisched",
433 "PostRA Machine Instruction Scheduler", false, false)
437INITIALIZE_PASS_END(PostMachineSchedulerLegacy, "postmisched",
438 "PostRA Machine Instruction Scheduler", false, false)
439
440PostMachineSchedulerLegacy::PostMachineSchedulerLegacy()
441 : MachineFunctionPass(ID) {}
442
443void PostMachineSchedulerLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
444 AU.setPreservesCFG();
450}
451
454
455/// A dummy default scheduler factory indicates whether the scheduler
456/// is overridden on the command line.
460
461/// MachineSchedOpt allows command line selection of the scheduler.
466 cl::desc("Machine instruction scheduler to use"));
467
469DefaultSchedRegistry("default", "Use the target's default scheduler choice.",
471
472/// Decrement this iterator until reaching the top or a non-debug instr.
476 assert(I != Beg && "reached the top of the region, cannot decrement");
477 while (--I != Beg) {
478 if (!I->isDebugOrPseudoInstr())
479 break;
480 }
481 return I;
482}
483
484/// Non-const version.
491
492/// If this iterator is a debug value, increment until reaching the End or a
493/// non-debug instruction.
497 for(; I != End; ++I) {
498 if (!I->isDebugOrPseudoInstr())
499 break;
500 }
501 return I;
502}
503
504/// Non-const version.
511
512/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
514 // Select the scheduler, or set the default.
516 if (Ctor != useDefaultMachineSched)
517 return Ctor(this);
518
519 // Get the default scheduler set by the target for this function.
520 ScheduleDAGInstrs *Scheduler = TM->createMachineScheduler(this);
521 if (Scheduler)
522 return Scheduler;
523
524 // Default to GenericScheduler.
525 return createSchedLive(this);
526}
527
529 const RequiredAnalyses &Analyses) {
530 MF = &Func;
531 MLI = &Analyses.MLI;
532 this->TM = &TM;
533 AA = &Analyses.AA;
534 LIS = &Analyses.LIS;
535 RegClassInfo = &Analyses.RegClassInfo;
536 MBFI = &Analyses.MBFI;
537
538 const CodeGenOptions &Opts = getCodeGenOptions(Func);
539 if (Opts.verify_misched) {
540 LLVM_DEBUG(LIS->dump());
541 const char *MSchedBanner = "Before machine scheduling.";
542 if (P)
543 MF->verify(P, MSchedBanner, &errs());
544 else
545 MF->verify(*MFAM, MSchedBanner, &errs());
546 }
547
548 // Instantiate the selected scheduler for this target, function, and
549 // optimization level.
550 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
551 scheduleRegions(*Scheduler, false);
552
553 LLVM_DEBUG(LIS->dump());
554 if (Opts.verify_misched) {
555 const char *MSchedBanner = "After machine scheduling.";
556 if (P)
557 MF->verify(P, MSchedBanner, &errs());
558 else
559 MF->verify(*MFAM, MSchedBanner, &errs());
560 }
561 return true;
562}
563
564/// Instantiate a ScheduleDAGInstrs that will be owned by the caller.
566 // Get the default scheduler set by the target for this function.
567 ScheduleDAGInstrs *Scheduler = TM->createMachineScheduler(this);
568 if (Scheduler)
569 return Scheduler;
570
571 // Default to GenericScheduler.
572 return createSchedLive(this);
573}
574
576 const TargetMachine &TM,
577 const RequiredAnalyses &Analyses) {
578 MF = &Func;
579 MLI = &Analyses.MLI;
580 this->TM = &TM;
581 AA = &Analyses.AA;
582 LIS = &Analyses.LIS;
583 RegClassInfo = &Analyses.RegClassInfo;
584 MBFI = &Analyses.MBFI;
585
586 const CodeGenOptions &Opts = getCodeGenOptions(Func);
587 if (Opts.verify_misched) {
588 LLVM_DEBUG(LIS->dump());
589 const char *MSchedBanner = "Before machine scheduling.";
590 if (P)
591 MF->verify(P, MSchedBanner, &errs());
592 else
593 MF->verify(*MFAM, MSchedBanner, &errs());
594 }
595 RegClassInfo->runOnMachineFunction(*MF);
596
597 // Instantiate the selected scheduler for this target, function, and
598 // optimization level.
599 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createMachineScheduler());
600 scheduleRegions(*Scheduler, false);
601
602 LLVM_DEBUG(LIS->dump());
603 if (Opts.verify_misched) {
604 const char *MSchedBanner = "After machine scheduling.";
605 if (P)
606 MF->verify(P, MSchedBanner, &errs());
607 else
608 MF->verify(*MFAM, MSchedBanner, &errs());
609 }
610 return true;
611}
612
613/// Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by
614/// the caller. We don't have a command line option to override the postRA
615/// scheduler. The Target must configure it.
617 // Get the postRA scheduler set by the target for this function.
618 ScheduleDAGInstrs *Scheduler = TM->createPostMachineScheduler(this);
619 if (Scheduler)
620 return Scheduler;
621
622 // Default to GenericScheduler.
623 return createSchedPostRA(this);
624}
625
627 const TargetMachine &TM,
628 const RequiredAnalyses &Analyses) {
629 MF = &Func;
630 MLI = &Analyses.MLI;
631 this->TM = &TM;
632 AA = &Analyses.AA;
633 RegClassInfo = &Analyses.RCI;
634
635 const CodeGenOptions &Opts = getCodeGenOptions(Func);
636 if (Opts.verify_misched) {
637 const char *PostMSchedBanner = "Before post machine scheduling.";
638 if (P)
639 MF->verify(P, PostMSchedBanner, &errs());
640 else
641 MF->verify(*MFAM, PostMSchedBanner, &errs());
642 }
643
644 // Instantiate the selected scheduler for this target, function, and
645 // optimization level.
646 std::unique_ptr<ScheduleDAGInstrs> Scheduler(createPostMachineScheduler());
648
649 if (Opts.verify_misched) {
650 const char *PostMSchedBanner = "After post machine scheduling.";
651 if (P)
652 MF->verify(P, PostMSchedBanner, &errs());
653 else
654 MF->verify(*MFAM, PostMSchedBanner, &errs());
655 }
656 return true;
657}
658
659/// Top-level MachineScheduler pass driver.
660///
661/// Visit blocks in function order. Divide each block into scheduling regions
662/// and visit them bottom-up. Visiting regions bottom-up is not required, but is
663/// consistent with the DAG builder, which traverses the interior of the
664/// scheduling regions bottom-up.
665///
666/// This design avoids exposing scheduling boundaries to the DAG builder,
667/// simplifying the DAG builder's support for "special" target instructions.
668/// At the same time the design allows target schedulers to operate across
669/// scheduling boundaries, for example to bundle the boundary instructions
670/// without reordering them. This creates complexity, because the target
671/// scheduler must update the RegionBegin and RegionEnd positions cached by
672/// ScheduleDAGInstrs whenever adding or removing instructions. A much simpler
673/// design would be to split blocks at scheduling boundaries, but LLVM has a
674/// general bias against block splitting purely for implementation simplicity.
675bool MachineSchedulerLegacy::runOnMachineFunction(MachineFunction &MF) {
676 if (skipFunction(MF.getFunction()))
677 return false;
678
679 if (!valueOr(getCodeGenOptions(MF).enable_misched,
681 return false;
682
683 LLVM_DEBUG(dbgs() << "Before MISched:\n"; MF.print(dbgs()));
684
685 auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
686 auto &TM = getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
687 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
688 auto &LIS = getAnalysis<LiveIntervalsWrapperPass>().getLIS();
689 auto &RegClassInfo =
690 getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
691 auto &MBFI = getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
692
693 Impl.setLegacyPass(this);
694 return Impl.run(MF, TM, {MLI, AA, LIS, RegClassInfo, MBFI});
695}
696
697bool SSAMachineSchedulerLegacy::runOnMachineFunction(MachineFunction &MF) {
698 if (skipFunction(MF.getFunction()))
699 return false;
700
701 if (!valueOr(getCodeGenOptions(MF).enable_ssa_misched,
703 return false;
704
705 auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
706 auto &TM = getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
707 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
708 auto &LIS = getAnalysis<LiveIntervalsWrapperPass>().getLIS();
709 auto &RegClassInfo =
710 getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
711 auto &MBFI = getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI();
712
713 Impl.setLegacyPass(this);
714 return Impl.run(MF, TM, {MLI, AA, LIS, RegClassInfo, MBFI});
715}
716
718 : Impl(std::make_unique<MachineSchedulerImpl>()), TM(TM) {}
721 default;
722
724 : Impl(std::make_unique<SSAMachineSchedulerImpl>()), TM(TM) {}
726 SSAMachineSchedulerPass &&Other) = default;
728
730 : Impl(std::make_unique<PostMachineSchedulerImpl>()), TM(TM) {}
732 PostMachineSchedulerPass &&Other) = default;
734
738 if (!valueOr(getCodeGenOptions(MF).enable_misched,
740 return PreservedAnalyses::all();
741
742 LLVM_DEBUG(dbgs() << "Before MISched:\n"; MF.print(dbgs()));
743 auto &MLI = MFAM.getResult<MachineLoopAnalysis>(MF);
745 .getManager();
746 auto &AA = FAM.getResult<AAManager>(MF.getFunction());
747 auto &LIS = MFAM.getResult<LiveIntervalsAnalysis>(MF);
748 auto &RegClassInfo = MFAM.getResult<MachineRegisterClassAnalysis>(MF);
749 auto &MBFI = MFAM.getResult<MachineBlockFrequencyAnalysis>(MF);
750
751 Impl->setMFAM(&MFAM);
752 bool Changed = Impl->run(MF, *TM, {MLI, AA, LIS, RegClassInfo, MBFI});
753 if (!Changed)
754 return PreservedAnalyses::all();
755
758 .preserve<SlotIndexesAnalysis>()
759 .preserve<LiveIntervalsAnalysis>();
760}
761
765 if (auto Enable = toOptional(getCodeGenOptions(MF).enable_ssa_misched)) {
766 if (!*Enable)
767 return PreservedAnalyses::all();
768 } else if (!MF.getSubtarget().enableSSAMachineScheduler()) {
769 LLVM_DEBUG(dbgs() << "Subtarget disables ssa-MI-sched.\n");
770 return PreservedAnalyses::all();
771 }
772
773 auto &MLI = MFAM.getResult<MachineLoopAnalysis>(MF);
775 .getManager();
776 auto &AA = FAM.getResult<AAManager>(MF.getFunction());
777 auto &LIS = MFAM.getResult<LiveIntervalsAnalysis>(MF);
778 auto &RegClassInfo = MFAM.getResult<MachineRegisterClassAnalysis>(MF);
779 auto &MBFI = MFAM.getResult<MachineBlockFrequencyAnalysis>(MF);
780
781 Impl->setMFAM(&MFAM);
782 bool Changed = Impl->run(MF, *TM, {MLI, AA, LIS, RegClassInfo, MBFI});
783 if (!Changed)
784 return PreservedAnalyses::all();
785
788 return PA;
789}
790
791bool PostMachineSchedulerLegacy::runOnMachineFunction(MachineFunction &MF) {
792 if (skipFunction(MF.getFunction()))
793 return false;
794
795 if (auto Enable = toOptional(getCodeGenOptions(MF).enable_post_misched)) {
796 if (!*Enable)
797 return false;
798 } else if (!MF.getSubtarget().enablePostRAMachineScheduler()) {
799 LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
800 return false;
801 }
802 LLVM_DEBUG(dbgs() << "Before post-MI-sched:\n"; MF.print(dbgs()));
803 auto &MLI = getAnalysis<MachineLoopInfoWrapperPass>().getLI();
804 auto &TM = getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
805 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
806 auto &RCI = getAnalysis<MachineRegisterClassInfoWrapperPass>().getRCI();
807 Impl.setLegacyPass(this);
808 return Impl.run(MF, TM, {MLI, AA, RCI});
809}
810
814 if (auto Enable = toOptional(getCodeGenOptions(MF).enable_post_misched)) {
815 if (!*Enable)
816 return PreservedAnalyses::all();
817 } else if (!MF.getSubtarget().enablePostRAMachineScheduler()) {
818 LLVM_DEBUG(dbgs() << "Subtarget disables post-MI-sched.\n");
819 return PreservedAnalyses::all();
820 }
821 LLVM_DEBUG(dbgs() << "Before post-MI-sched:\n"; MF.print(dbgs()));
822 auto &MLI = MFAM.getResult<MachineLoopAnalysis>(MF);
824 .getManager();
825 auto &AA = FAM.getResult<AAManager>(MF.getFunction());
826 auto &RCI = MFAM.getResult<MachineRegisterClassAnalysis>(MF);
827
828 Impl->setMFAM(&MFAM);
829 bool Changed = Impl->run(MF, *TM, {MLI, AA, RCI});
830 if (!Changed)
831 return PreservedAnalyses::all();
832
835 return PA;
836}
837
838/// Return true of the given instruction should not be included in a scheduling
839/// region.
840///
841/// MachineScheduler does not currently support scheduling across calls. To
842/// handle calls, the DAG builder needs to be modified to create register
843/// anti/output dependencies on the registers clobbered by the call's regmask
844/// operand. In PreRA scheduling, the stack pointer adjustment already prevents
845/// scheduling across calls. In PostRA scheduling, we need the isCall to enforce
846/// the boundary, but there would be no benefit to postRA scheduling across
847/// calls this late anyway.
850 const TargetInstrInfo *TII) {
851 return MI->isCall() || TII->isSchedulingBoundary(*MI, MBB, *MF) ||
852 MI->isFakeUse() || MI->isPHI();
853}
854
856
857static void
859 MBBRegionsVector &Regions,
860 bool RegionsTopDown) {
861 MachineFunction *MF = MBB->getParent();
863
865 for(MachineBasicBlock::iterator RegionEnd = MBB->end();
866 RegionEnd != MBB->begin(); RegionEnd = I) {
867
868 // Avoid decrementing RegionEnd for blocks with no terminator.
869 if (RegionEnd != MBB->end() ||
870 isSchedBoundary(&*std::prev(RegionEnd), &*MBB, MF, TII)) {
871 --RegionEnd;
872 }
873
874 // The next region starts above the previous region. Look backward in the
875 // instruction stream until we find the nearest boundary.
876 unsigned NumRegionInstrs = 0;
877 I = RegionEnd;
878 for (;I != MBB->begin(); --I) {
879 MachineInstr &MI = *std::prev(I);
880 if (isSchedBoundary(&MI, &*MBB, MF, TII))
881 break;
882 if (!MI.isDebugOrPseudoInstr()) {
883 // MBB::size() uses instr_iterator to count. Here we need a bundle to
884 // count as a single instruction.
885 ++NumRegionInstrs;
886 }
887 }
888
889 // It's possible we found a scheduling region that only has debug
890 // instructions. Don't bother scheduling these.
891 if (NumRegionInstrs != 0)
892 Regions.push_back(SchedRegion(I, RegionEnd, NumRegionInstrs));
893 }
894
895 if (RegionsTopDown)
896 std::reverse(Regions.begin(), Regions.end());
897}
898
899/// Main driver for both MachineScheduler and PostMachineScheduler.
901 bool FixKillFlags) {
902 const CodeGenOptions &Opts = Scheduler.Opts;
903
904 // Visit all machine basic blocks.
905 //
906 // TODO: Visit blocks in global postorder or postorder within the bottom-up
907 // loop tree. Then we can optionally compute global RegPressure.
908 for (MachineFunction::iterator MBB = MF->begin(), MBBEnd = MF->end();
909 MBB != MBBEnd; ++MBB) {
910#ifndef NDEBUG
911 if (Opts.misched_only_func && *Opts.misched_only_func != MF->getName())
912 continue;
913 if (Opts.misched_only_block &&
914 (int)*Opts.misched_only_block != MBB->getNumber())
915 continue;
916#endif
917
918 Scheduler.startBlock(&*MBB);
919
920 // Break the block into scheduling regions [I, RegionEnd). RegionEnd
921 // points to the scheduling boundary at the bottom of the region. The DAG
922 // does not include RegionEnd, but the region does (i.e. the next
923 // RegionEnd is above the previous RegionBegin). If the current block has
924 // no terminator then RegionEnd == MBB->end() for the bottom region.
925 //
926 // All the regions of MBB are first found and stored in MBBRegions, which
927 // will be processed (MBB) top-down if initialized with true.
928 //
929 // The Scheduler may insert instructions during either schedule() or
930 // exitRegion(), even for empty regions. So the local iterators 'I' and
931 // 'RegionEnd' are invalid across these calls. Instructions must not be
932 // added to other regions than the current one without updating MBBRegions.
933
934 MBBRegionsVector MBBRegions;
935 getSchedRegions(&*MBB, MBBRegions, Scheduler.doMBBSchedRegionsTopDown());
936 bool ScheduleSingleMI = Scheduler.shouldScheduleSingleMIRegions();
937 for (const SchedRegion &R : MBBRegions) {
938 MachineBasicBlock::iterator I = R.RegionBegin;
939 MachineBasicBlock::iterator RegionEnd = R.RegionEnd;
940 unsigned NumRegionInstrs = R.NumRegionInstrs;
941
942 // Notify the scheduler of the region, even if we may skip scheduling
943 // it. Perhaps it still needs to be bundled.
944 Scheduler.enterRegion(&*MBB, I, RegionEnd, NumRegionInstrs);
945
946 // Skip empty scheduling regions and, conditionally, regions with a single
947 // MI.
948 if (I == RegionEnd || (!ScheduleSingleMI && I == std::prev(RegionEnd))) {
949 // Close the current region. Bundle the terminator if needed.
950 // This invalidates 'RegionEnd' and 'I'.
951 Scheduler.exitRegion();
952 continue;
953 }
954 auto DumpRegionHeader = [&] {
955 dbgs() << "Current Schedule Region\n";
956 dbgs() << MF->getName() << ":" << printMBBReference(*MBB) << " "
957 << MBB->getName() << "\n From: " << *I << " To: ";
958 if (RegionEnd != MBB->end())
959 dbgs() << *RegionEnd;
960 else
961 dbgs() << "End\n";
962 dbgs() << " RegionInstrs: " << NumRegionInstrs << '\n';
963 };
965 DumpRegionHeader();
966 else
967 LLVM_DEBUG(DumpRegionHeader());
968 if (Opts.misched_dcpl) {
969 errs() << MF->getName();
970 errs() << ":%bb. " << MBB->getNumber();
971 errs() << " " << MBB->getName() << " \n";
972 }
973
974 // Schedule a region: possibly reorder instructions.
975 // This invalidates the original region iterators.
976 Scheduler.schedule();
977
978 // Close the current region.
979 Scheduler.exitRegion();
980 }
981 Scheduler.finishBlock();
982 // FIXME: Ideally, no further passes should rely on kill flags. However,
983 // thumb2 size reduction is currently an exception, so the PostMIScheduler
984 // needs to do this.
985 if (FixKillFlags)
986 Scheduler.fixupKills(*MBB);
987 }
988 Scheduler.finalizeSchedule();
989}
990
991#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
993 dbgs() << "Queue " << Name << ": ";
994 for (const SUnit *SU : Queue)
995 dbgs() << *SU << " ";
996 dbgs() << "\n";
997}
998#endif
999
1000//===----------------------------------------------------------------------===//
1001// ScheduleDAGMI - Basic machine instruction scheduling. This is
1002// independent of PreRA/PostRA scheduling and involves no extra book-keeping for
1003// virtual registers.
1004// ===----------------------------------------------------------------------===/
1005
1008 if (AntiDepMode == TargetSubtargetInfo::ANTIDEP_NONE)
1009 return;
1010
1011 assert(C->MF->getRegInfo().tracksLiveness() &&
1012 "Live-ins must be accurate for anti-dependency breaking");
1013 assert(C->RegClassInfo &&
1014 "Register class info is required for anti-dependency breaking");
1015 if (AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL) {
1017 C->MF->getSubtarget().getCriticalPathRCs(CriticalPathRCs);
1018 Breaker.reset(createAggressiveAntiDepBreaker(*C->MF, *C->RegClassInfo,
1019 CriticalPathRCs));
1020 } else {
1021 assert(AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL &&
1022 "Unexpected anti-dependency break mode");
1023 Breaker.reset(createCriticalAntiDepBreaker(*C->MF, *C->RegClassInfo));
1024 }
1025}
1026
1027void AntiDepState::scanRangeBackwards(MachineBasicBlock::iterator From,
1029 for (auto I = From; I != To;) {
1030 MachineInstr &MI = *--I;
1031 --BoundaryScanIndex;
1032 if (!MI.isDebugOrPseudoInstr())
1033 Breaker->Observe(MI, BoundaryScanIndex, RegionEndIndex);
1034 if (MI.isBundle())
1035 BoundaryScanIndex -= MI.getBundleSize();
1036 }
1037}
1038
1040 if (!Breaker)
1041 return;
1042 Breaker->StartBlock(MBB);
1043 BoundaryScanPos = MBB->end();
1044 BoundaryScanIndex = MBB->size();
1045 RegionEndIndex = BoundaryScanIndex;
1046}
1047
1049 if (!Breaker)
1050 return;
1051 Breaker->FinishBlock();
1052}
1053
1055 if (!Breaker)
1056 return;
1057
1058 // Scheduling regions exclude boundary instructions and may have gaps between
1059 // them. Scan those gaps so the breaker's liveness remains synchronized.
1060 scanRangeBackwards(BoundaryScanPos, End);
1061 RegionEndIndex = BoundaryScanIndex;
1062 RegionProcessed = false;
1063}
1064
1067 if (!Breaker)
1068 return;
1069
1070 BoundaryScanPos = Begin;
1071 if (RegionProcessed) {
1072 BoundaryScanIndex -= std::distance(Begin, End);
1073 } else {
1074 // schedule() skips empty and single-instruction regions. Scan a skipped
1075 // region here so its instructions still contribute to liveness.
1076 scanRangeBackwards(End, Begin);
1077 }
1078}
1079
1081 const std::vector<SUnit> &SUnits, MachineBasicBlock::iterator Begin,
1083 AntiDepBreaker::DbgValueVector &DbgValues) {
1084 if (!Breaker)
1085 return false;
1086 RegionProcessed = true;
1087 return Breaker->BreakAntiDependencies(SUnits, Begin, End, RegionEndIndex,
1088 DbgValues) != 0;
1089}
1090
1091// Provide a vtable anchor.
1093
1094/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. When
1095/// NumPredsLeft reaches zero, release the successor node.
1096///
1097/// FIXME: Adjust SuccSU height based on MinLatency.
1099 SUnit *SuccSU = SuccEdge->getSUnit();
1100
1101 if (SuccEdge->isWeak()) {
1102 --SuccSU->WeakPredsLeft;
1103 return;
1104 }
1105#ifndef NDEBUG
1106 if (SuccSU->NumPredsLeft == 0) {
1107 dbgs() << "*** Scheduling failed! ***\n";
1108 dumpNode(*SuccSU);
1109 dbgs() << " has been released too many times!\n";
1110 llvm_unreachable(nullptr);
1111 }
1112#endif
1113 // SU->TopReadyCycle was set to CurrCycle when it was scheduled. However,
1114 // CurrCycle may have advanced since then.
1115 if (SuccSU->TopReadyCycle < SU->TopReadyCycle + SuccEdge->getLatency())
1116 SuccSU->TopReadyCycle = SU->TopReadyCycle + SuccEdge->getLatency();
1117
1118 --SuccSU->NumPredsLeft;
1119 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
1120 SchedImpl->releaseTopNode(SuccSU);
1121}
1122
1123/// releaseSuccessors - Call releaseSucc on each of SU's successors.
1125 for (SDep &Succ : SU->Succs)
1126 releaseSucc(SU, &Succ);
1127}
1128
1129/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. When
1130/// NumSuccsLeft reaches zero, release the predecessor node.
1131///
1132/// FIXME: Adjust PredSU height based on MinLatency.
1134 SUnit *PredSU = PredEdge->getSUnit();
1135
1136 if (PredEdge->isWeak()) {
1137 --PredSU->WeakSuccsLeft;
1138 return;
1139 }
1140#ifndef NDEBUG
1141 if (PredSU->NumSuccsLeft == 0) {
1142 dbgs() << "*** Scheduling failed! ***\n";
1143 dumpNode(*PredSU);
1144 dbgs() << " has been released too many times!\n";
1145 llvm_unreachable(nullptr);
1146 }
1147#endif
1148 // SU->BotReadyCycle was set to CurrCycle when it was scheduled. However,
1149 // CurrCycle may have advanced since then.
1150 if (PredSU->BotReadyCycle < SU->BotReadyCycle + PredEdge->getLatency())
1151 PredSU->BotReadyCycle = SU->BotReadyCycle + PredEdge->getLatency();
1152
1153 --PredSU->NumSuccsLeft;
1154 if (PredSU->NumSuccsLeft == 0 && PredSU != &EntrySU)
1155 SchedImpl->releaseBottomNode(PredSU);
1156}
1157
1158/// releasePredecessors - Call releasePred on each of SU's predecessors.
1160 for (SDep &Pred : SU->Preds)
1161 releasePred(SU, &Pred);
1162}
1163
1166 SchedImpl->enterMBB(bb);
1167 AntiDep.startBlock(bb);
1168}
1169
1171 AntiDep.finishBlock();
1172 SchedImpl->leaveMBB();
1174}
1175
1176/// enterRegion - Called back from PostMachineScheduler::runOnMachineFunction
1177/// after crossing a scheduling boundary. [begin, end) includes all instructions
1178/// in the region, including the boundary itself and single-instruction regions
1179/// that don't get scheduled.
1183 unsigned regioninstrs) {
1184 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
1185 AntiDep.enterRegion(end);
1186
1187 SchedImpl->initPolicy(begin, end, regioninstrs);
1188
1189 // Set dump direction after initializing sched policy.
1191 if (SchedImpl->getPolicy().OnlyTopDown)
1193 else if (SchedImpl->getPolicy().OnlyBottomUp)
1195 else
1198}
1199
1204
1205/// This is normally called from the main scheduler loop but may also be invoked
1206/// by the scheduling strategy to perform additional code motion.
1209 // Advance RegionBegin if the first instruction moves down.
1210 if (&*RegionBegin == MI)
1211 ++RegionBegin;
1212
1213 // Update the instruction stream.
1214 BB->splice(InsertPos, BB, MI);
1215
1216 // Update LiveIntervals
1217 if (LIS)
1218 LIS->handleMove(*MI, /*UpdateFlags=*/true);
1219
1220 // Recede RegionBegin if an instruction moves above the first.
1221 if (RegionBegin == InsertPos)
1222 RegionBegin = MI;
1223}
1224
1226#if LLVM_ENABLE_ABI_BREAKING_CHECKS && !defined(NDEBUG)
1227 if (NumInstrsScheduled == Opts.misched_cutoff && Opts.misched_cutoff != ~0U) {
1229 return false;
1230 }
1231 ++NumInstrsScheduled;
1232#endif
1233 return true;
1234}
1235
1236/// Per-region scheduling driver, called back from
1237/// PostMachineScheduler::runOnMachineFunction. This is a simplified driver
1238/// that does not consider liveness or register pressure. It is useful for
1239/// PostRA scheduling and potentially other custom schedulers.
1241 LLVM_DEBUG(dbgs() << "ScheduleDAGMI::schedule starting\n");
1242 LLVM_DEBUG(SchedImpl->dumpPolicy());
1243
1244 // Build the DAG.
1246
1247 if (AntiDep.breakAntiDependencies(SUnits, RegionBegin, RegionEnd,
1248 DbgValues)) {
1249 // Renaming invalidates register dependencies. Rebuild the base DAG before
1250 // applying mutations below, as SchedulePostRATDList does. Updating the DAG
1251 // in place would also need to account for edges removed by mutations.
1253 }
1254
1256
1257 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1258 findRootsAndBiasEdges(TopRoots, BotRoots);
1259
1260 LLVM_DEBUG(dump());
1262 dump();
1264 viewGraph();
1265
1266 // Initialize the strategy before modifying the DAG.
1267 // This may initialize a DFSResult to be used for queue priority.
1268 SchedImpl->initialize(this);
1269
1270 // Initialize ready queues now that the DAG and priority data are finalized.
1271 initQueues(TopRoots, BotRoots);
1272
1273 bool IsTopNode = false;
1274 while (true) {
1275 if (!checkSchedLimit())
1276 break;
1277
1278 LLVM_DEBUG(dbgs() << "** ScheduleDAGMI::schedule picking next node\n");
1279 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1280 if (!SU) break;
1281
1282 assert(!SU->isScheduled && "Node already scheduled");
1283
1284 MachineInstr *MI = SU->getInstr();
1285 if (IsTopNode) {
1286 assert(SU->isTopReady() && "node still has unscheduled dependencies");
1287 if (&*CurrentTop == MI)
1289 else
1291 } else {
1292 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
1295 if (&*priorII == MI)
1296 CurrentBottom = priorII;
1297 else {
1298 if (&*CurrentTop == MI)
1299 CurrentTop = nextIfDebug(++CurrentTop, priorII);
1301 CurrentBottom = MI;
1302 }
1303 }
1304 // Notify the scheduling strategy before updating the DAG.
1305 // This sets the scheduled node's ReadyCycle to CurrCycle. When updateQueues
1306 // runs, it can then use the accurate ReadyCycle time to determine whether
1307 // newly released nodes can move to the readyQ.
1308 SchedImpl->schedNode(SU, IsTopNode);
1309
1310 updateQueues(SU, IsTopNode);
1311 }
1312 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1313
1315
1316 LLVM_DEBUG({
1317 dbgs() << "*** Final schedule for "
1318 << printMBBReference(*begin()->getParent()) << " ***\n";
1319 dumpSchedule();
1320 dbgs() << '\n';
1321 });
1322}
1323
1324/// Apply each ScheduleDAGMutation step in order.
1326 for (auto &m : Mutations)
1327 m->apply(this);
1328}
1329
1332 SmallVectorImpl<SUnit*> &BotRoots) {
1333 for (SUnit &SU : SUnits) {
1334 assert(!SU.isBoundaryNode() && "Boundary node should not be in SUnits");
1335
1336 // Order predecessors so DFSResult follows the critical path.
1337 SU.biasCriticalPath();
1338
1339 // A SUnit is ready to top schedule if it has no predecessors.
1340 if (!SU.NumPredsLeft)
1341 TopRoots.push_back(&SU);
1342 // A SUnit is ready to bottom schedule if it has no successors.
1343 if (!SU.NumSuccsLeft)
1344 BotRoots.push_back(&SU);
1345 }
1346 ExitSU.biasCriticalPath();
1347}
1348
1349/// Identify DAG roots and setup scheduler queues.
1351 ArrayRef<SUnit *> BotRoots) {
1352 // Release all DAG roots for scheduling, not including EntrySU/ExitSU.
1353 //
1354 // Nodes with unreleased weak edges can still be roots.
1355 // Release top roots in forward order.
1356 for (SUnit *SU : TopRoots)
1357 SchedImpl->releaseTopNode(SU);
1358
1359 // Release bottom roots in reverse order so the higher priority nodes appear
1360 // first. This is more natural and slightly more efficient.
1362 I = BotRoots.rbegin(), E = BotRoots.rend(); I != E; ++I) {
1363 SchedImpl->releaseBottomNode(*I);
1364 }
1365
1368
1369 SchedImpl->registerRoots();
1370
1371 // Advance past initial DebugValues.
1374}
1375
1376/// Update scheduler queues after scheduling an instruction.
1377void ScheduleDAGMI::updateQueues(SUnit *SU, bool IsTopNode) {
1378 // Release dependent instructions for scheduling.
1379 if (IsTopNode)
1381 else
1383
1384 SU->isScheduled = true;
1385}
1386
1387/// Reinsert any remaining debug_values, just like the PostRA scheduler.
1389 // If first instruction was a DBG_VALUE then put it back.
1390 if (FirstDbgValue) {
1391 BB->splice(RegionBegin, BB, FirstDbgValue);
1393 }
1394
1395 for (std::vector<std::pair<MachineInstr *, MachineInstr *>>::iterator
1396 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
1397 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
1398 MachineInstr *DbgValue = P.first;
1399 MachineBasicBlock::iterator OrigPrevMI = P.second;
1400 if (&*RegionBegin == DbgValue)
1401 ++RegionBegin;
1402 BB->splice(std::next(OrigPrevMI), BB, DbgValue);
1403 if (RegionEnd != BB->end() && OrigPrevMI == &*RegionEnd)
1405 }
1406}
1407
1408#ifndef NDEBUG
1409static const char *scheduleTableLegend = " i: issue\n x: resource booked";
1410
1412 unsigned HeaderColWidth = Opts.misched_dump_schedule_trace_col_header_width;
1413 unsigned ColWidth = Opts.misched_dump_schedule_trace_col_width;
1414 // Bail off when there is no schedule model to query.
1415 if (!SchedModel.hasInstrSchedModel())
1416 return;
1417
1418 // Nothing to show if there is no or just one instruction.
1419 if (BB->size() < 2)
1420 return;
1421
1422 dbgs() << " * Schedule table (TopDown):\n";
1423 dbgs() << scheduleTableLegend << "\n";
1424 const unsigned FirstCycle = getSUnit(&*(std::begin(*this)))->TopReadyCycle;
1425 unsigned LastCycle = getSUnit(&*(std::prev(std::end(*this))))->TopReadyCycle;
1426 for (MachineInstr &MI : *this) {
1427 SUnit *SU = getSUnit(&MI);
1428 if (!SU)
1429 continue;
1430 const MCSchedClassDesc *SC = getSchedClass(SU);
1431 for (TargetSchedModel::ProcResIter PI = SchedModel.getWriteProcResBegin(SC),
1432 PE = SchedModel.getWriteProcResEnd(SC);
1433 PI != PE; ++PI) {
1434 if (SU->TopReadyCycle + PI->ReleaseAtCycle - 1 > LastCycle)
1435 LastCycle = SU->TopReadyCycle + PI->ReleaseAtCycle - 1;
1436 }
1437 }
1438 // Print the header with the cycles
1439 dbgs() << llvm::left_justify("Cycle", HeaderColWidth);
1440 for (unsigned C = FirstCycle; C <= LastCycle; ++C)
1441 dbgs() << llvm::left_justify("| " + std::to_string(C), ColWidth);
1442 dbgs() << "|\n";
1443
1444 for (MachineInstr &MI : *this) {
1445 SUnit *SU = getSUnit(&MI);
1446 if (!SU) {
1447 dbgs() << "Missing SUnit\n";
1448 continue;
1449 }
1450 std::string NodeName;
1451 raw_string_ostream(NodeName) << *SU;
1452 dbgs() << llvm::left_justify(NodeName, HeaderColWidth);
1453 unsigned C = FirstCycle;
1454 for (; C <= LastCycle; ++C) {
1455 if (C == SU->TopReadyCycle)
1456 dbgs() << llvm::left_justify("| i", ColWidth);
1457 else
1458 dbgs() << llvm::left_justify("|", ColWidth);
1459 }
1460 dbgs() << "|\n";
1461 const MCSchedClassDesc *SC = getSchedClass(SU);
1462
1464 make_range(SchedModel.getWriteProcResBegin(SC),
1465 SchedModel.getWriteProcResEnd(SC)));
1466
1467 if (Opts.misched_sort_resources_in_trace)
1469 ResourcesIt,
1470 [](const MCWriteProcResEntry &LHS,
1471 const MCWriteProcResEntry &RHS) -> bool {
1472 return std::tie(LHS.AcquireAtCycle, LHS.ReleaseAtCycle) <
1473 std::tie(RHS.AcquireAtCycle, RHS.ReleaseAtCycle);
1474 });
1475 for (const MCWriteProcResEntry &PI : ResourcesIt) {
1476 C = FirstCycle;
1477 const std::string ResName =
1478 SchedModel.getResourceName(PI.ProcResourceIdx);
1479 dbgs() << llvm::right_justify(ResName + " ", HeaderColWidth);
1480 for (; C < SU->TopReadyCycle + PI.AcquireAtCycle; ++C) {
1481 dbgs() << llvm::left_justify("|", ColWidth);
1482 }
1483 for (unsigned I = 0, E = PI.ReleaseAtCycle - PI.AcquireAtCycle; I != E;
1484 ++I, ++C)
1485 dbgs() << llvm::left_justify("| x", ColWidth);
1486 while (C++ <= LastCycle)
1487 dbgs() << llvm::left_justify("|", ColWidth);
1488 // Place end char
1489 dbgs() << "| \n";
1490 }
1491 }
1492}
1493
1495 unsigned HeaderColWidth = Opts.misched_dump_schedule_trace_col_header_width;
1496 unsigned ColWidth = Opts.misched_dump_schedule_trace_col_width;
1497 // Bail off when there is no schedule model to query.
1498 if (!SchedModel.hasInstrSchedModel())
1499 return;
1500
1501 // Nothing to show if there is no or just one instruction.
1502 if (BB->size() < 2)
1503 return;
1504
1505 dbgs() << " * Schedule table (BottomUp):\n";
1506 dbgs() << scheduleTableLegend << "\n";
1507
1508 const int FirstCycle = getSUnit(&*(std::begin(*this)))->BotReadyCycle;
1509 int LastCycle = getSUnit(&*(std::prev(std::end(*this))))->BotReadyCycle;
1510 for (MachineInstr &MI : *this) {
1511 SUnit *SU = getSUnit(&MI);
1512 if (!SU)
1513 continue;
1514 const MCSchedClassDesc *SC = getSchedClass(SU);
1515 for (TargetSchedModel::ProcResIter PI = SchedModel.getWriteProcResBegin(SC),
1516 PE = SchedModel.getWriteProcResEnd(SC);
1517 PI != PE; ++PI) {
1518 if ((int)SU->BotReadyCycle - PI->ReleaseAtCycle + 1 < LastCycle)
1519 LastCycle = (int)SU->BotReadyCycle - PI->ReleaseAtCycle + 1;
1520 }
1521 }
1522 // Print the header with the cycles
1523 dbgs() << llvm::left_justify("Cycle", HeaderColWidth);
1524 for (int C = FirstCycle; C >= LastCycle; --C)
1525 dbgs() << llvm::left_justify("| " + std::to_string(C), ColWidth);
1526 dbgs() << "|\n";
1527
1528 for (MachineInstr &MI : *this) {
1529 SUnit *SU = getSUnit(&MI);
1530 if (!SU) {
1531 dbgs() << "Missing SUnit\n";
1532 continue;
1533 }
1534 std::string NodeName;
1535 raw_string_ostream(NodeName) << *SU;
1536 dbgs() << llvm::left_justify(NodeName, HeaderColWidth);
1537 int C = FirstCycle;
1538 for (; C >= LastCycle; --C) {
1539 if (C == (int)SU->BotReadyCycle)
1540 dbgs() << llvm::left_justify("| i", ColWidth);
1541 else
1542 dbgs() << llvm::left_justify("|", ColWidth);
1543 }
1544 dbgs() << "|\n";
1545 const MCSchedClassDesc *SC = getSchedClass(SU);
1547 make_range(SchedModel.getWriteProcResBegin(SC),
1548 SchedModel.getWriteProcResEnd(SC)));
1549
1550 if (Opts.misched_sort_resources_in_trace)
1552 ResourcesIt,
1553 [](const MCWriteProcResEntry &LHS,
1554 const MCWriteProcResEntry &RHS) -> bool {
1555 return std::tie(LHS.AcquireAtCycle, LHS.ReleaseAtCycle) <
1556 std::tie(RHS.AcquireAtCycle, RHS.ReleaseAtCycle);
1557 });
1558 for (const MCWriteProcResEntry &PI : ResourcesIt) {
1559 C = FirstCycle;
1560 const std::string ResName =
1561 SchedModel.getResourceName(PI.ProcResourceIdx);
1562 dbgs() << llvm::right_justify(ResName + " ", HeaderColWidth);
1563 for (; C > ((int)SU->BotReadyCycle - (int)PI.AcquireAtCycle); --C) {
1564 dbgs() << llvm::left_justify("|", ColWidth);
1565 }
1566 for (unsigned I = 0, E = PI.ReleaseAtCycle - PI.AcquireAtCycle; I != E;
1567 ++I, --C)
1568 dbgs() << llvm::left_justify("| x", ColWidth);
1569 while (C-- >= LastCycle)
1570 dbgs() << llvm::left_justify("|", ColWidth);
1571 // Place end char
1572 dbgs() << "| \n";
1573 }
1574 }
1575}
1576#endif
1577
1578#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1580#ifndef NDEBUG
1581 if (Opts.misched_dump_schedule_trace) {
1584 else if (DumpDir == DumpDirection::BottomUp)
1587 dbgs() << "* Schedule table (Bidirectional): not implemented\n";
1588 } else {
1589 dbgs() << "* Schedule table: DumpDirection not set.\n";
1590 }
1591 }
1592#endif
1593
1594 for (MachineInstr &MI : *this) {
1595 if (SUnit *SU = getSUnit(&MI))
1596 dumpNode(*SU);
1597 else
1598 dbgs() << "Missing SUnit\n";
1599 }
1600}
1601#endif
1602
1603//===----------------------------------------------------------------------===//
1604// ScheduleDAGMILive - Base class for MachineInstr scheduling with LiveIntervals
1605// preservation.
1606//===----------------------------------------------------------------------===//
1607
1611
1613 const MachineInstr &MI = *SU.getInstr();
1614 for (const MachineOperand &MO : MI.operands()) {
1615 if (!MO.isReg())
1616 continue;
1617 if (!MO.readsReg())
1618 continue;
1619 if (TrackLaneMasks && !MO.isUse())
1620 continue;
1621
1622 Register Reg = MO.getReg();
1623 if (!Reg.isVirtual())
1624 continue;
1625
1626 // Ignore re-defs.
1627 if (TrackLaneMasks) {
1628 bool FoundDef = false;
1629 for (const MachineOperand &MO2 : MI.all_defs()) {
1630 if (MO2.getReg() == Reg && !MO2.isDead()) {
1631 FoundDef = true;
1632 break;
1633 }
1634 }
1635 if (FoundDef)
1636 continue;
1637 }
1638
1639 // Record this local VReg use.
1641 for (; UI != VRegUses.end(); ++UI) {
1642 if (UI->SU == &SU)
1643 break;
1644 }
1645 if (UI == VRegUses.end())
1646 VRegUses.insert(VReg2SUnit(Reg, LaneBitmask::getNone(), &SU));
1647 }
1648}
1649
1650/// enterRegion - Called back from MachineScheduler::runOnMachineFunction after
1651/// crossing a scheduling boundary. [begin, end) includes all instructions in
1652/// the region, including the boundary itself and single-instruction regions
1653/// that don't get scheduled.
1657 unsigned regioninstrs)
1658{
1659 // ScheduleDAGMI initializes SchedImpl's per-region policy.
1660 ScheduleDAGMI::enterRegion(bb, begin, end, regioninstrs);
1661
1662 // For convenience remember the end of the liveness region.
1663 LiveRegionEnd = (RegionEnd == bb->end()) ? RegionEnd : std::next(RegionEnd);
1664
1665 SUPressureDiffs.clear();
1666
1667 ShouldTrackPressure = SchedImpl->shouldTrackPressure();
1668 ShouldTrackLaneMasks = SchedImpl->shouldTrackLaneMasks();
1669
1671 "ShouldTrackLaneMasks requires ShouldTrackPressure");
1672}
1673
1674// Setup the register pressure trackers for the top scheduled and bottom
1675// scheduled regions.
1677 VRegUses.clear();
1678 VRegUses.setUniverse(MRI.getNumVirtRegs());
1679 for (SUnit &SU : SUnits)
1680 collectVRegUses(SU);
1681
1683 ShouldTrackLaneMasks, false);
1685 ShouldTrackLaneMasks, false);
1686
1687 // Close the RPTracker to finalize live ins.
1688 RPTracker.closeRegion();
1689
1690 LLVM_DEBUG(RPTracker.dump());
1691
1692 // Initialize the live ins and live outs.
1693 TopRPTracker.addLiveRegs(RPTracker.getPressure().LiveInRegs);
1694 BotRPTracker.addLiveRegs(RPTracker.getPressure().LiveOutRegs);
1695
1696 // Close one end of the tracker so we can call
1697 // getMaxUpward/DownwardPressureDelta before advancing across any
1698 // instructions. This converts currently live regs into live ins/outs.
1699 TopRPTracker.closeTop();
1700 BotRPTracker.closeBottom();
1701
1702 BotRPTracker.initLiveThru(RPTracker);
1703 if (!BotRPTracker.getLiveThru().empty()) {
1704 TopRPTracker.initLiveThru(BotRPTracker.getLiveThru());
1705 LLVM_DEBUG(dbgs() << "Live Thru: ";
1706 dumpRegSetPressure(BotRPTracker.getLiveThru(), TRI));
1707 };
1708
1709 // For each live out vreg reduce the pressure change associated with other
1710 // uses of the same vreg below the live-out reaching def.
1711 updatePressureDiffs(RPTracker.getPressure().LiveOutRegs);
1712
1713 // Account for liveness generated by the region boundary.
1714 if (LiveRegionEnd != RegionEnd) {
1716 BotRPTracker.recede(&LiveUses);
1717 updatePressureDiffs(LiveUses);
1718 }
1719
1720 LLVM_DEBUG(dbgs() << "Top Pressure: ";
1721 dumpRegSetPressure(TopRPTracker.getRegSetPressureAtPos(), TRI);
1722 dbgs() << "Bottom Pressure: ";
1723 dumpRegSetPressure(BotRPTracker.getRegSetPressureAtPos(), TRI););
1724
1725 assert((BotRPTracker.getPos() == RegionEnd ||
1726 (RegionEnd->isDebugInstr() &&
1728 "Can't find the region bottom");
1729
1730 // Cache the list of excess pressure sets in this region. This will also track
1731 // the max pressure in the scheduled code for these sets.
1732 RegionCriticalPSets.clear();
1733 const std::vector<unsigned> &RegionPressure =
1734 RPTracker.getPressure().MaxSetPressure;
1735 for (unsigned i = 0, e = RegionPressure.size(); i < e; ++i) {
1736 unsigned Limit = RegClassInfo->getRegPressureSetLimit(i);
1737 if (RegionPressure[i] > Limit) {
1738 LLVM_DEBUG(dbgs() << TRI->getRegPressureSetName(i) << " Limit " << Limit
1739 << " Actual " << RegionPressure[i] << "\n");
1740 RegionCriticalPSets.push_back(PressureChange(i));
1741 }
1742 }
1743 LLVM_DEBUG({
1744 if (RegionCriticalPSets.size() > 0) {
1745 dbgs() << "Excess PSets: ";
1746 for (const PressureChange &RCPS : RegionCriticalPSets)
1747 dbgs() << TRI->getRegPressureSetName(RCPS.getPSet()) << " ";
1748 dbgs() << "\n";
1749 }
1750 });
1751}
1752
1755 const std::vector<unsigned> &NewMaxPressure) {
1756 const PressureDiff &PDiff = getPressureDiff(SU);
1757 unsigned CritIdx = 0, CritEnd = RegionCriticalPSets.size();
1758 for (const PressureChange &PC : PDiff) {
1759 if (!PC.isValid())
1760 break;
1761 unsigned ID = PC.getPSet();
1762 while (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() < ID)
1763 ++CritIdx;
1764 if (CritIdx != CritEnd && RegionCriticalPSets[CritIdx].getPSet() == ID) {
1765 if ((int)NewMaxPressure[ID] > RegionCriticalPSets[CritIdx].getUnitInc()
1766 && NewMaxPressure[ID] <= (unsigned)std::numeric_limits<int16_t>::max())
1767 RegionCriticalPSets[CritIdx].setUnitInc(NewMaxPressure[ID]);
1768 }
1769 unsigned Limit = RegClassInfo->getRegPressureSetLimit(ID);
1770 if (NewMaxPressure[ID] >= Limit - 2) {
1771 LLVM_DEBUG(dbgs() << " " << TRI->getRegPressureSetName(ID) << ": "
1772 << NewMaxPressure[ID]
1773 << ((NewMaxPressure[ID] > Limit) ? " > " : " <= ")
1774 << Limit << "(+ " << BotRPTracker.getLiveThru()[ID]
1775 << " livethru)\n");
1776 }
1777 }
1778}
1779
1780/// Update the PressureDiff array for liveness after scheduling this
1781/// instruction.
1783 for (const VRegMaskOrUnit &P : LiveUses) {
1784 /// FIXME: Currently assuming single-use physregs.
1785 if (!P.VRegOrUnit.isVirtualReg())
1786 continue;
1787 Register Reg = P.VRegOrUnit.asVirtualReg();
1788
1790 // If the register has just become live then other uses won't change
1791 // this fact anymore => decrement pressure.
1792 // If the register has just become dead then other uses make it come
1793 // back to life => increment pressure.
1794 bool Decrement = P.LaneMask.any();
1795
1796 for (const VReg2SUnit &V2SU
1797 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1798 SUnit &SU = *V2SU.SU;
1799 if (SU.isScheduled || &SU == &ExitSU)
1800 continue;
1801
1802 PressureDiff &PDiff = getPressureDiff(&SU);
1803 PDiff.addPressureChange(VirtRegOrUnit(Reg), Decrement, &MRI);
1804 if (llvm::any_of(PDiff, [](const PressureChange &Change) {
1805 return Change.isValid();
1806 }))
1808 << " UpdateRegPressure: " << SU << " "
1809 << printReg(Reg, TRI) << ':'
1810 << PrintLaneMask(P.LaneMask) << ' ' << *SU.getInstr();
1811 dbgs() << " to "; PDiff.dump(*TRI););
1812 }
1813 } else {
1814 assert(P.LaneMask.any());
1815 LLVM_DEBUG(dbgs() << " LiveReg: " << printReg(Reg, TRI) << "\n");
1816 // This may be called before CurrentBottom has been initialized. However,
1817 // BotRPTracker must have a valid position. We want the value live into the
1818 // instruction or live out of the block, so ask for the previous
1819 // instruction's live-out.
1820 const LiveInterval &LI = LIS->getInterval(Reg);
1821 VNInfo *VNI;
1823 nextIfDebug(BotRPTracker.getPos(), BB->end());
1824 if (I == BB->end())
1825 VNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
1826 else {
1827 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*I));
1828 VNI = LRQ.valueIn();
1829 }
1830 // RegisterPressureTracker guarantees that readsReg is true for LiveUses.
1831 assert(VNI && "No live value at use.");
1832 for (const VReg2SUnit &V2SU
1833 : make_range(VRegUses.find(Reg), VRegUses.end())) {
1834 SUnit *SU = V2SU.SU;
1835 // If this use comes before the reaching def, it cannot be a last use,
1836 // so decrease its pressure change.
1837 if (!SU->isScheduled && SU != &ExitSU) {
1838 LiveQueryResult LRQ =
1839 LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
1840 if (LRQ.valueIn() == VNI) {
1841 PressureDiff &PDiff = getPressureDiff(SU);
1842 PDiff.addPressureChange(VirtRegOrUnit(Reg), true, &MRI);
1843 if (llvm::any_of(PDiff, [](const PressureChange &Change) {
1844 return Change.isValid();
1845 }))
1846 LLVM_DEBUG(dbgs() << " UpdateRegPressure: " << *SU << " "
1847 << *SU->getInstr();
1848 dbgs() << " to ";
1849 PDiff.dump(*TRI););
1850 }
1851 }
1852 }
1853 }
1854 }
1855}
1856
1858#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1859 if (EntrySU.getInstr() != nullptr)
1861 for (const SUnit &SU : SUnits) {
1862 dumpNodeAll(SU);
1863 if (ShouldTrackPressure) {
1864 dbgs() << " Pressure Diff : ";
1865 getPressureDiff(&SU).dump(*TRI);
1866 }
1867 dbgs() << " Single Issue : ";
1868 if (SchedModel.mustBeginGroup(SU.getInstr()) &&
1869 SchedModel.mustEndGroup(SU.getInstr()))
1870 dbgs() << "true;";
1871 else
1872 dbgs() << "false;";
1873 dbgs() << '\n';
1874 }
1875 if (ExitSU.getInstr() != nullptr)
1877#endif
1878}
1879
1880/// schedule - Called back from MachineScheduler::runOnMachineFunction
1881/// after setting up the current scheduling region. [RegionBegin, RegionEnd)
1882/// only includes instructions that have DAG nodes, not scheduling boundaries.
1883///
1884/// This is a skeletal driver, with all the functionality pushed into helpers,
1885/// so that it can be easily extended by experimental schedulers. Generally,
1886/// implementing MachineSchedStrategy should be sufficient to implement a new
1887/// scheduling algorithm. However, if a scheduler further subclasses
1888/// ScheduleDAGMILive then it will want to override this virtual method in order
1889/// to update any specialized state.
1891 LLVM_DEBUG(dbgs() << "ScheduleDAGMILive::schedule starting\n");
1892 LLVM_DEBUG(SchedImpl->dumpPolicy());
1894
1896
1897 SmallVector<SUnit*, 8> TopRoots, BotRoots;
1898 findRootsAndBiasEdges(TopRoots, BotRoots);
1899
1900 // Initialize the strategy before modifying the DAG.
1901 // This may initialize a DFSResult to be used for queue priority.
1902 SchedImpl->initialize(this);
1903
1904 LLVM_DEBUG(dump());
1906 dump();
1908 viewGraph();
1909
1910 // Initialize ready queues now that the DAG and priority data are finalized.
1911 initQueues(TopRoots, BotRoots);
1912
1913 bool IsTopNode = false;
1914 while (true) {
1915 if (!checkSchedLimit())
1916 break;
1917
1918 LLVM_DEBUG(dbgs() << "** ScheduleDAGMILive::schedule picking next node\n");
1919 SUnit *SU = SchedImpl->pickNode(IsTopNode);
1920 if (!SU) break;
1921
1922 assert(!SU->isScheduled && "Node already scheduled");
1923
1924 scheduleMI(SU, IsTopNode);
1925
1926 if (DFSResult) {
1927 unsigned SubtreeID = DFSResult->getSubtreeID(SU);
1928 if (!ScheduledTrees.test(SubtreeID)) {
1929 ScheduledTrees.set(SubtreeID);
1930 DFSResult->scheduleTree(SubtreeID);
1931 SchedImpl->scheduleTree(SubtreeID);
1932 }
1933 }
1934
1935 // Notify the scheduling strategy after updating the DAG.
1936 SchedImpl->schedNode(SU, IsTopNode);
1937
1938 updateQueues(SU, IsTopNode);
1939 }
1940 assert(CurrentTop == CurrentBottom && "Nonempty unscheduled zone.");
1941
1943
1944 LLVM_DEBUG({
1945 dbgs() << "*** Final schedule for "
1946 << printMBBReference(*begin()->getParent()) << " ***\n";
1947 dumpSchedule();
1948 dbgs() << '\n';
1949 });
1950}
1951
1952/// Build the DAG and setup three register pressure trackers.
1954 if (!ShouldTrackPressure) {
1955 RPTracker.reset();
1956 RegionCriticalPSets.clear();
1958 return;
1959 }
1960
1961 // Initialize the register pressure tracker used by buildSchedGraph.
1963 ShouldTrackLaneMasks, /*TrackUntiedDefs=*/true);
1964
1965 // Account for liveness generate by the region boundary.
1966 if (LiveRegionEnd != RegionEnd)
1967 RPTracker.recede();
1968
1969 // Build the DAG, and compute current register pressure.
1971
1972 // Initialize top/bottom trackers after computing region pressure.
1974}
1975
1977 if (!DFSResult)
1978 DFSResult = new SchedDFSResult(/*BottomU*/true, MinSubtreeSize);
1979 DFSResult->clear();
1980 ScheduledTrees.clear();
1981 DFSResult->resize(SUnits.size());
1982 DFSResult->compute(SUnits);
1983 ScheduledTrees.resize(DFSResult->getNumSubtrees());
1984}
1985
1986/// Compute the max cyclic critical path through the DAG. The scheduling DAG
1987/// only provides the critical path for single block loops. To handle loops that
1988/// span blocks, we could use the vreg path latencies provided by
1989/// MachineTraceMetrics instead. However, MachineTraceMetrics is not currently
1990/// available for use in the scheduler.
1991///
1992/// The cyclic path estimation identifies a def-use pair that crosses the back
1993/// edge and considers the depth and height of the nodes. For example, consider
1994/// the following instruction sequence where each instruction has unit latency
1995/// and defines an eponymous virtual register:
1996///
1997/// a->b(a,c)->c(b)->d(c)->exit
1998///
1999/// The cyclic critical path is a two cycles: b->c->b
2000/// The acyclic critical path is four cycles: a->b->c->d->exit
2001/// LiveOutHeight = height(c) = len(c->d->exit) = 2
2002/// LiveOutDepth = depth(c) + 1 = len(a->b->c) + 1 = 3
2003/// LiveInHeight = height(b) + 1 = len(b->c->d->exit) + 1 = 4
2004/// LiveInDepth = depth(b) = len(a->b) = 1
2005///
2006/// LiveOutDepth - LiveInDepth = 3 - 1 = 2
2007/// LiveInHeight - LiveOutHeight = 4 - 2 = 2
2008/// CyclicCriticalPath = min(2, 2) = 2
2009///
2010/// This could be relevant to PostRA scheduling, but is currently implemented
2011/// assuming LiveIntervals.
2013 // This only applies to single block loop.
2014 if (!BB->isSuccessor(BB))
2015 return 0;
2016
2017 unsigned MaxCyclicLatency = 0;
2018 // Visit each live out vreg def to find def/use pairs that cross iterations.
2019 for (const VRegMaskOrUnit &P : RPTracker.getPressure().LiveOutRegs) {
2020 if (!P.VRegOrUnit.isVirtualReg())
2021 continue;
2022 Register Reg = P.VRegOrUnit.asVirtualReg();
2023 const LiveInterval &LI = LIS->getInterval(Reg);
2024 const VNInfo *DefVNI = LI.getVNInfoBefore(LIS->getMBBEndIdx(BB));
2025 if (!DefVNI)
2026 continue;
2027
2028 MachineInstr *DefMI = LIS->getInstructionFromIndex(DefVNI->def);
2029 const SUnit *DefSU = getSUnit(DefMI);
2030 if (!DefSU)
2031 continue;
2032
2033 unsigned LiveOutHeight = DefSU->getHeight();
2034 unsigned LiveOutDepth = DefSU->getDepth() + DefSU->Latency;
2035 // Visit all local users of the vreg def.
2036 for (const VReg2SUnit &V2SU
2037 : make_range(VRegUses.find(Reg), VRegUses.end())) {
2038 SUnit *SU = V2SU.SU;
2039 if (SU == &ExitSU)
2040 continue;
2041
2042 // Only consider uses of the phi.
2043 LiveQueryResult LRQ = LI.Query(LIS->getInstructionIndex(*SU->getInstr()));
2044 if (!LRQ.valueIn()->isPHIDef())
2045 continue;
2046
2047 // Assume that a path spanning two iterations is a cycle, which could
2048 // overestimate in strange cases. This allows cyclic latency to be
2049 // estimated as the minimum slack of the vreg's depth or height.
2050 unsigned CyclicLatency = 0;
2051 if (LiveOutDepth > SU->getDepth())
2052 CyclicLatency = LiveOutDepth - SU->getDepth();
2053
2054 unsigned LiveInHeight = SU->getHeight() + DefSU->Latency;
2055 if (LiveInHeight > LiveOutHeight) {
2056 if (LiveInHeight - LiveOutHeight < CyclicLatency)
2057 CyclicLatency = LiveInHeight - LiveOutHeight;
2058 } else
2059 CyclicLatency = 0;
2060
2061 LLVM_DEBUG(dbgs() << "Cyclic Path: " << *DefSU << " -> " << *SU << " = "
2062 << CyclicLatency << "c\n");
2063 if (CyclicLatency > MaxCyclicLatency)
2064 MaxCyclicLatency = CyclicLatency;
2065 }
2066 }
2067 LLVM_DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "c\n");
2068 return MaxCyclicLatency;
2069}
2070
2071/// Release ExitSU predecessors and setup scheduler queues. Re-position
2072/// the Top RP tracker in case the region beginning has changed.
2074 ArrayRef<SUnit*> BotRoots) {
2075 ScheduleDAGMI::initQueues(TopRoots, BotRoots);
2076 if (ShouldTrackPressure) {
2077 assert(TopRPTracker.getPos() == RegionBegin && "bad initial Top tracker");
2078 TopRPTracker.setPos(CurrentTop);
2079 }
2080}
2081
2082/// Move an instruction and update register pressure.
2083void ScheduleDAGMILive::scheduleMI(SUnit *SU, bool IsTopNode) {
2084 // Move the instruction to its new location in the instruction stream.
2085 MachineInstr *MI = SU->getInstr();
2086
2087 if (IsTopNode) {
2088 assert(SU->isTopReady() && "node still has unscheduled dependencies");
2089 if (&*CurrentTop == MI)
2091 else {
2093 TopRPTracker.setPos(MI);
2094 }
2095
2096 if (ShouldTrackPressure) {
2097 // Update top scheduled pressure.
2098 RegisterOperands RegOpers;
2099 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks,
2100 /*IgnoreDead=*/false);
2102 // Adjust liveness and add missing dead+read-undef flags.
2103 RegOpers.adjustLaneLiveness(*LIS, MRI, *MI);
2104 } else {
2105 // Adjust for missing dead-def flags.
2106 RegOpers.detectDeadDefs(*MI, *LIS, MRI);
2107 }
2108
2109 TopRPTracker.advance(RegOpers);
2110 assert(TopRPTracker.getPos() == CurrentTop && "out of sync");
2111 LLVM_DEBUG(dbgs() << "Top Pressure: "; dumpRegSetPressure(
2112 TopRPTracker.getRegSetPressureAtPos(), TRI););
2113
2114 updateScheduledPressure(SU, TopRPTracker.getPressure().MaxSetPressure);
2115 }
2116 } else {
2117 assert(SU->isBottomReady() && "node still has unscheduled dependencies");
2120 if (&*priorII == MI)
2121 CurrentBottom = priorII;
2122 else {
2123 if (&*CurrentTop == MI) {
2124 CurrentTop = nextIfDebug(++CurrentTop, priorII);
2125 TopRPTracker.setPos(CurrentTop);
2126 }
2128 CurrentBottom = MI;
2130 }
2131 if (ShouldTrackPressure) {
2132 RegisterOperands RegOpers;
2133 RegOpers.collect(*MI, *TRI, MRI, ShouldTrackLaneMasks,
2134 /*IgnoreDead=*/false);
2136 // Adjust liveness and add missing dead+read-undef flags.
2137 RegOpers.adjustLaneLiveness(*LIS, MRI, *MI);
2138 } else {
2139 // Adjust for missing dead-def flags.
2140 RegOpers.detectDeadDefs(*MI, *LIS, MRI);
2141 }
2142
2143 if (BotRPTracker.getPos() != CurrentBottom)
2144 BotRPTracker.recedeSkipDebugValues();
2146 BotRPTracker.recede(RegOpers, &LiveUses);
2147 assert(BotRPTracker.getPos() == CurrentBottom && "out of sync");
2148 LLVM_DEBUG(dbgs() << "Bottom Pressure: "; dumpRegSetPressure(
2149 BotRPTracker.getRegSetPressureAtPos(), TRI););
2150
2151 updateScheduledPressure(SU, BotRPTracker.getPressure().MaxSetPressure);
2152 updatePressureDiffs(LiveUses);
2153 }
2154 }
2155}
2156
2157//===----------------------------------------------------------------------===//
2158// BaseMemOpClusterMutation - DAG post-processing to cluster loads or stores.
2159//===----------------------------------------------------------------------===//
2160
2161namespace {
2162
2163/// Post-process the DAG to create cluster edges between neighboring
2164/// loads or between neighboring stores.
2165class BaseMemOpClusterMutation : public ScheduleDAGMutation {
2166 struct MemOpInfo {
2167 SUnit *SU;
2169 int64_t Offset;
2170 LocationSize Width;
2171 bool OffsetIsScalable;
2172
2173 MemOpInfo(SUnit *SU, ArrayRef<const MachineOperand *> BaseOps,
2174 int64_t Offset, bool OffsetIsScalable, LocationSize Width)
2175 : SU(SU), BaseOps(BaseOps), Offset(Offset), Width(Width),
2176 OffsetIsScalable(OffsetIsScalable) {}
2177
2178 static bool Compare(const MachineOperand *const &A,
2179 const MachineOperand *const &B) {
2180 if (A->getType() != B->getType())
2181 return A->getType() < B->getType();
2182 if (A->isReg())
2183 return A->getReg() < B->getReg();
2184 if (A->isFI()) {
2185 const MachineFunction &MF = *A->getParent()->getParent()->getParent();
2186 const MachineFrameInfo &MFI = MF.getFrameInfo();
2188 bool StackGrowsDown = TFI.getStackGrowthDirection() ==
2190 bool AIsFixed = MFI.isFixedObjectIndex(A->getIndex());
2191 bool BIsFixed = MFI.isFixedObjectIndex(B->getIndex());
2192 // Sort fixed and non-fixed bases as separate groups, preserving the
2193 // existing frame-index ordering between the groups. Do not rely on
2194 // non-fixed object offsets before frame layout.
2195 if (AIsFixed != BIsFixed)
2196 return StackGrowsDown ? !AIsFixed : AIsFixed;
2197 if (AIsFixed) {
2198 // Fixed objects have explicit offsets, and targets may create their
2199 // frame indices in an order unrelated to those offsets. Sort by the
2200 // actual object offsets so target clustering hooks see fixed object
2201 // bases in address order.
2202 int64_t AOffset = MFI.getObjectOffset(A->getIndex());
2203 int64_t BOffset = MFI.getObjectOffset(B->getIndex());
2204 if (AOffset != BOffset)
2205 return AOffset < BOffset;
2206 }
2207 return StackGrowsDown ? A->getIndex() > B->getIndex()
2208 : A->getIndex() < B->getIndex();
2209 }
2210
2211 llvm_unreachable("MemOpClusterMutation only supports register or frame "
2212 "index bases.");
2213 }
2214
2215 bool operator<(const MemOpInfo &RHS) const {
2216 // FIXME: Don't compare everything twice. Maybe use C++20 three way
2217 // comparison instead when it's available.
2218 if (std::lexicographical_compare(BaseOps.begin(), BaseOps.end(),
2219 RHS.BaseOps.begin(), RHS.BaseOps.end(),
2220 Compare))
2221 return true;
2222 if (std::lexicographical_compare(RHS.BaseOps.begin(), RHS.BaseOps.end(),
2223 BaseOps.begin(), BaseOps.end(), Compare))
2224 return false;
2225 if (Offset != RHS.Offset)
2226 return Offset < RHS.Offset;
2227 return SU->NodeNum < RHS.SU->NodeNum;
2228 }
2229 };
2230
2231 /// Encodes a relationship between two memops, A and B. Here, a path is 'safe'
2232 /// if it is of length 1 and consists of only memory or barrier edges.
2233 enum class MemOpRelationship {
2234 UnsafePath, ///< There is an unsafe path in either direction.
2235 Unrelated, ///< The two memops are mutually unreachable.
2236 DirectOrd, ///< All paths from A to B are safe and there is such a path.
2237 ReverseOrd, ///< All paths from B to A are safe and there is such a path.
2238 };
2239
2240 const TargetInstrInfo *TII;
2241 bool IsLoad;
2242 bool ReorderWhileClustering;
2243
2244public:
2245 BaseMemOpClusterMutation(const TargetInstrInfo *tii, bool IsLoad,
2246 bool ReorderWhileClustering)
2247 : TII(tii), IsLoad(IsLoad),
2248 ReorderWhileClustering(ReorderWhileClustering) {}
2249
2250 void apply(ScheduleDAGInstrs *DAGInstrs) override;
2251
2252private:
2253 MemOpRelationship computeRelationship(ScheduleDAGInstrs *DAG, SUnit *SUa,
2254 SUnit *SUb);
2255
2256protected:
2257 void clusterNeighboringMemOps(ArrayRef<MemOpInfo> MemOps, bool FastCluster,
2258 ScheduleDAGInstrs *DAG);
2259 void collectMemOpRecords(std::vector<SUnit> &SUnits,
2260 SmallVectorImpl<MemOpInfo> &MemOpRecords);
2261 bool groupMemOps(ArrayRef<MemOpInfo> MemOps, ScheduleDAGInstrs *DAG,
2262 DenseMap<unsigned, SmallVector<MemOpInfo, 32>> &Groups);
2263};
2264
2265class StoreClusterMutation : public BaseMemOpClusterMutation {
2266public:
2267 StoreClusterMutation(const TargetInstrInfo *tii, bool ReorderWhileClustering)
2268 : BaseMemOpClusterMutation(tii, false, ReorderWhileClustering) {}
2269};
2270
2271class LoadClusterMutation : public BaseMemOpClusterMutation {
2272public:
2273 LoadClusterMutation(const TargetInstrInfo *tii, bool ReorderWhileClustering)
2274 : BaseMemOpClusterMutation(tii, true, ReorderWhileClustering) {}
2275};
2276
2277} // end anonymous namespace
2278
2279std::unique_ptr<ScheduleDAGMutation>
2281 bool ReorderWhileClustering) {
2282 return std::make_unique<LoadClusterMutation>(TII, ReorderWhileClustering);
2283}
2284
2285std::unique_ptr<ScheduleDAGMutation>
2287 bool ReorderWhileClustering) {
2288 return std::make_unique<StoreClusterMutation>(TII, ReorderWhileClustering);
2289}
2290
2291BaseMemOpClusterMutation::MemOpRelationship
2292BaseMemOpClusterMutation::computeRelationship(ScheduleDAGInstrs *DAG,
2293 SUnit *SUa, SUnit *SUb) {
2294 bool AReachesB = DAG->IsReachable(SUb, SUa);
2295 bool BReachesA = DAG->IsReachable(SUa, SUb);
2296
2297 if (!BReachesA && !AReachesB)
2298 return MemOpRelationship::Unrelated;
2299
2300 // We have a path. Determine whether all paths are safe and which order they
2301 // run.
2302
2303 // If the path runs from B -> A, normalise so that it runs from A -> B for
2304 // the search.
2305 bool Reverse = false;
2306 if (BReachesA) {
2307 assert(!AReachesB && "Cycle detected");
2308 std::swap(SUa, SUb);
2309 Reverse = true;
2310 }
2311
2312 // Check each successor of A for reachability against B. For edges from A to
2313 // B, check that they are all memory or barrier edges.
2314 for (const SDep &Succ : SUa->Succs) {
2315 if (Succ.getSUnit() == &DAG->ExitSU)
2316 continue;
2317 if (Succ.getSUnit() == SUb) {
2318 if (!Succ.isNormalMemoryOrBarrier())
2319 return MemOpRelationship::UnsafePath;
2320 continue;
2321 }
2322
2323 if (DAG->IsReachable(SUb, Succ.getSUnit()))
2324 return MemOpRelationship::UnsafePath;
2325 }
2326
2327 return Reverse ? MemOpRelationship::ReverseOrd : MemOpRelationship::DirectOrd;
2328}
2329
2330// Sorting all the loads/stores first, then for each load/store, checking the
2331// following load/store one by one, until reach the first non-dependent one and
2332// call target hook to see if they can cluster.
2333// If FastCluster is enabled, we assume that, all the loads/stores have been
2334// preprocessed and now, they didn't have dependencies on each other.
2335void BaseMemOpClusterMutation::clusterNeighboringMemOps(
2336 ArrayRef<MemOpInfo> MemOpRecords, bool FastCluster,
2337 ScheduleDAGInstrs *DAG) {
2338 // Keep track of the current cluster length and bytes for each SUnit.
2341
2342 // At this point, `MemOpRecords` array must hold at least two mem ops. Try to
2343 // cluster mem ops collected within `MemOpRecords` array.
2344 for (unsigned Idx = 0, End = MemOpRecords.size(); Idx < (End - 1); ++Idx) {
2345 // Decision to cluster mem ops is taken based on target dependent logic
2346 auto MemOpa = MemOpRecords[Idx];
2347 MemOpRelationship Relationship = MemOpRelationship::UnsafePath;
2348
2349 // Seek for the next load/store to do the cluster.
2350 unsigned NextIdx = Idx + 1;
2351 for (; NextIdx < End; ++NextIdx) {
2352 // Skip if MemOpb has been clustered already.
2353 if (SUnit2ClusterInfo.count(MemOpRecords[NextIdx].SU->NodeNum))
2354 continue;
2355
2356 // If FastCluster is enabled, we assume everything is unrelated and
2357 // therefore trivially clusterable.
2358 if (FastCluster) {
2359 Relationship = MemOpRelationship::Unrelated;
2360 break;
2361 }
2362
2363 Relationship =
2364 computeRelationship(DAG, MemOpa.SU, MemOpRecords[NextIdx].SU);
2365 if (Relationship != MemOpRelationship::UnsafePath)
2366 break;
2367 }
2368
2369 if (NextIdx == End)
2370 continue;
2371
2372 auto MemOpb = MemOpRecords[NextIdx];
2373 unsigned ClusterLength = 2;
2374 unsigned CurrentClusterBytes = MemOpa.Width.getValue().getKnownMinValue() +
2375 MemOpb.Width.getValue().getKnownMinValue();
2376 auto It = SUnit2ClusterInfo.find(MemOpa.SU->NodeNum);
2377 if (It != SUnit2ClusterInfo.end()) {
2378 const auto &[Len, Bytes] = It->second;
2379 ClusterLength = Len + 1;
2380 CurrentClusterBytes = Bytes + MemOpb.Width.getValue().getKnownMinValue();
2381 }
2382
2383 if (!TII->shouldClusterMemOps(MemOpa.BaseOps, MemOpa.Offset,
2384 MemOpa.OffsetIsScalable, MemOpb.BaseOps,
2385 MemOpb.Offset, MemOpb.OffsetIsScalable,
2386 ClusterLength, CurrentClusterBytes))
2387 continue;
2388
2389 SUnit *SUa = MemOpa.SU;
2390 SUnit *SUb = MemOpb.SU;
2391
2392 // We insert each edge from A to B. Switch if such an edge would run in the
2393 // wrong order. When ReorderWhileClustering is disabled, so long as A and B
2394 // are unrelated, the 'wrong order' is any order contrary to program order.
2395 if (Relationship == MemOpRelationship::ReverseOrd ||
2396 (Relationship == MemOpRelationship::Unrelated &&
2397 !ReorderWhileClustering && SUa->NodeNum > SUb->NodeNum))
2398 std::swap(SUa, SUb);
2399
2400 // This check is necessary to ensure we don't create a cycle with
2401 // FastCluster enabled.
2402 if (!DAG->addEdge(SUb, SDep(SUa, SDep::Cluster))) {
2403 assert(FastCluster &&
2404 "Adding an edge would create a cycle without FastCluster enabled");
2405 continue;
2406 }
2407
2408 Clusters.unionSets(SUa, SUb);
2409 LLVM_DEBUG(dbgs() << "Cluster ld/st " << *SUa << " - " << *SUb << "\n");
2410 ++NumClustered;
2411
2412 if (IsLoad) {
2413 // Copy successor edges from SUa to SUb. Interleaving computation
2414 // dependent on SUa can prevent load combining due to register reuse.
2415 // Predecessor edges do not need to be copied from SUb to SUa since
2416 // nearby loads should have effectively the same inputs.
2417 for (const SDep &Succ : SUa->Succs) {
2418 if (Succ.getSUnit() == SUb)
2419 continue;
2420 LLVM_DEBUG(dbgs() << " Copy Succ ";
2421 DAG->dumpNodeName(*Succ.getSUnit()); dbgs() << "\n");
2422 DAG->addEdge(Succ.getSUnit(), SDep(SUb, SDep::Artificial));
2423 }
2424 } else {
2425 // Copy predecessor edges from SUb to SUa to avoid the SUnits that
2426 // SUb dependent on scheduled in-between SUb and SUa. Successor edges
2427 // do not need to be copied from SUa to SUb since no one will depend
2428 // on stores.
2429 for (const SDep &Pred : SUb->Preds) {
2430 if (Pred.getSUnit() == SUa)
2431 continue;
2432 LLVM_DEBUG(dbgs() << " Copy Pred " << *Pred.getSUnit() << "\n");
2433 DAG->addEdge(SUa, SDep(Pred.getSUnit(), SDep::Artificial));
2434 }
2435 }
2436
2437 SUnit2ClusterInfo[MemOpb.SU->NodeNum] = {ClusterLength,
2438 CurrentClusterBytes};
2439
2440 LLVM_DEBUG(dbgs() << " Curr cluster length: " << ClusterLength
2441 << ", Curr cluster bytes: " << CurrentClusterBytes
2442 << "\n");
2443 }
2444
2445 // Add cluster group information.
2446 // Iterate over all of the equivalence sets.
2447 auto &AllClusters = DAG->getClusters();
2448 for (const EquivalenceClasses<SUnit *>::ECValue *I : Clusters) {
2449 if (!I->isLeader())
2450 continue;
2451 ClusterInfo Group;
2452 unsigned ClusterIdx = AllClusters.size();
2453 for (SUnit *MemberI : Clusters.members(*I)) {
2454 MemberI->ParentClusterIdx = ClusterIdx;
2455 Group.insert(MemberI);
2456 }
2457 AllClusters.push_back(Group);
2458 }
2459}
2460
2461void BaseMemOpClusterMutation::collectMemOpRecords(
2462 std::vector<SUnit> &SUnits, SmallVectorImpl<MemOpInfo> &MemOpRecords) {
2463 for (auto &SU : SUnits) {
2464 if ((IsLoad && !SU.getInstr()->mayLoad()) ||
2465 (!IsLoad && !SU.getInstr()->mayStore()))
2466 continue;
2467
2468 const MachineInstr &MI = *SU.getInstr();
2470 int64_t Offset;
2471 bool OffsetIsScalable;
2474 OffsetIsScalable, Width)) {
2475 if (!Width.hasValue())
2476 continue;
2477
2478 MemOpRecords.push_back(
2479 MemOpInfo(&SU, BaseOps, Offset, OffsetIsScalable, Width));
2480
2481 LLVM_DEBUG(dbgs() << "Num BaseOps: " << BaseOps.size() << ", Offset: "
2482 << Offset << ", OffsetIsScalable: " << OffsetIsScalable
2483 << ", Width: " << Width << "\n");
2484 }
2485#ifndef NDEBUG
2486 for (const auto *Op : BaseOps)
2487 assert(Op);
2488#endif
2489 }
2490}
2491
2492bool BaseMemOpClusterMutation::groupMemOps(
2495 bool FastCluster = DAG->Opts.misched_force_fast_cluster ||
2496 MemOps.size() * DAG->SUnits.size() / 1000 >
2497 DAG->Opts.misched_fast_cluster_threshold;
2498
2499 for (const auto &MemOp : MemOps) {
2500 unsigned ChainPredID = DAG->SUnits.size();
2501 if (FastCluster) {
2502 for (const SDep &Pred : MemOp.SU->Preds) {
2503 // We only want to cluster the mem ops that have the same ctrl(non-data)
2504 // pred so that they didn't have ctrl dependency for each other. But for
2505 // store instrs, we can still cluster them if the pred is load instr.
2506 if ((Pred.isCtrl() &&
2507 (IsLoad ||
2508 (Pred.getSUnit() && Pred.getSUnit()->getInstr()->mayStore()))) &&
2509 !Pred.isArtificial()) {
2510 ChainPredID = Pred.getSUnit()->NodeNum;
2511 break;
2512 }
2513 }
2514 } else
2515 ChainPredID = 0;
2516
2517 Groups[ChainPredID].push_back(MemOp);
2518 }
2519 return FastCluster;
2520}
2521
2522/// Callback from DAG postProcessing to create cluster edges for loads/stores.
2523void BaseMemOpClusterMutation::apply(ScheduleDAGInstrs *DAG) {
2524 if (!DAG->Opts.misched_cluster)
2525 return;
2526
2527 // Collect all the clusterable loads/stores
2528 SmallVector<MemOpInfo, 32> MemOpRecords;
2529 collectMemOpRecords(DAG->SUnits, MemOpRecords);
2530
2531 if (MemOpRecords.size() < 2)
2532 return;
2533
2534 // Put the loads/stores without dependency into the same group with some
2535 // heuristic if the DAG is too complex to avoid compiling time blow up.
2536 // Notice that, some fusion pair could be lost with this.
2538 bool FastCluster = groupMemOps(MemOpRecords, DAG, Groups);
2539
2540 for (auto &Group : Groups) {
2541 // Sorting the loads/stores, so that, we can stop the cluster as early as
2542 // possible.
2543 llvm::sort(Group.second);
2544
2545 // Trying to cluster all the neighboring loads/stores.
2546 clusterNeighboringMemOps(Group.second, FastCluster, DAG);
2547 }
2548}
2549
2550//===----------------------------------------------------------------------===//
2551// CopyConstrain - DAG post-processing to encourage copy elimination.
2552//===----------------------------------------------------------------------===//
2553
2554namespace {
2555
2556/// Post-process the DAG to create weak edges from all uses of a copy to
2557/// the one use that defines the copy's source vreg, most likely an induction
2558/// variable increment.
2559class CopyConstrain : public ScheduleDAGMutation {
2560 // Transient state.
2561 SlotIndex RegionBeginIdx;
2562
2563 // RegionEndIdx is the slot index of the last non-debug instruction in the
2564 // scheduling region. So we may have RegionBeginIdx == RegionEndIdx.
2565 SlotIndex RegionEndIdx;
2566
2567public:
2568 CopyConstrain(const TargetInstrInfo *) {}
2569
2570 void apply(ScheduleDAGInstrs *DAGInstrs) override;
2571
2572protected:
2573 void constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG);
2574};
2575
2576} // end anonymous namespace
2577
2578std::unique_ptr<ScheduleDAGMutation>
2580 return std::make_unique<CopyConstrain>(TII);
2581}
2582
2583/// constrainLocalCopy handles two possibilities:
2584/// 1) Local src:
2585/// I0: = dst
2586/// I1: src = ...
2587/// I2: = dst
2588/// I3: dst = src (copy)
2589/// (create pred->succ edges I0->I1, I2->I1)
2590///
2591/// 2) Local copy:
2592/// I0: dst = src (copy)
2593/// I1: = dst
2594/// I2: src = ...
2595/// I3: = dst
2596/// (create pred->succ edges I1->I2, I3->I2)
2597///
2598/// Although the MachineScheduler is currently constrained to single blocks,
2599/// this algorithm should handle extended blocks. An EBB is a set of
2600/// contiguously numbered blocks such that the previous block in the EBB is
2601/// always the single predecessor.
2602void CopyConstrain::constrainLocalCopy(SUnit *CopySU, ScheduleDAGMILive *DAG) {
2603 LiveIntervals *LIS = DAG->getLIS();
2604 MachineInstr *Copy = CopySU->getInstr();
2605
2606 // Check for pure vreg copies.
2607 const MachineOperand &SrcOp = Copy->getOperand(1);
2608 Register SrcReg = SrcOp.getReg();
2609 if (!SrcReg.isVirtual() || !SrcOp.readsReg())
2610 return;
2611
2612 const MachineOperand &DstOp = Copy->getOperand(0);
2613 Register DstReg = DstOp.getReg();
2614 if (!DstReg.isVirtual() || DstOp.isDead())
2615 return;
2616
2617 // Check if either the dest or source is local. If it's live across a back
2618 // edge, it's not local. Note that if both vregs are live across the back
2619 // edge, we cannot successfully contrain the copy without cyclic scheduling.
2620 // If both the copy's source and dest are local live intervals, then we
2621 // should treat the dest as the global for the purpose of adding
2622 // constraints. This adds edges from source's other uses to the copy.
2623 unsigned LocalReg = SrcReg;
2624 unsigned GlobalReg = DstReg;
2625 LiveInterval *LocalLI = &LIS->getInterval(LocalReg);
2626 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx)) {
2627 LocalReg = DstReg;
2628 GlobalReg = SrcReg;
2629 LocalLI = &LIS->getInterval(LocalReg);
2630 if (!LocalLI->isLocal(RegionBeginIdx, RegionEndIdx))
2631 return;
2632 }
2633 LiveInterval *GlobalLI = &LIS->getInterval(GlobalReg);
2634
2635 // Find the global segment after the start of the local LI.
2636 LiveInterval::iterator GlobalSegment = GlobalLI->find(LocalLI->beginIndex());
2637 // If GlobalLI does not overlap LocalLI->start, then a copy directly feeds a
2638 // local live range. We could create edges from other global uses to the local
2639 // start, but the coalescer should have already eliminated these cases, so
2640 // don't bother dealing with it.
2641 if (GlobalSegment == GlobalLI->end())
2642 return;
2643
2644 // If GlobalSegment is killed at the LocalLI->start, the call to find()
2645 // returned the next global segment. But if GlobalSegment overlaps with
2646 // LocalLI->start, then advance to the next segment. If a hole in GlobalLI
2647 // exists in LocalLI's vicinity, GlobalSegment will be the end of the hole.
2648 if (GlobalSegment->contains(LocalLI->beginIndex()))
2649 ++GlobalSegment;
2650
2651 if (GlobalSegment == GlobalLI->end())
2652 return;
2653
2654 // Check if GlobalLI contains a hole in the vicinity of LocalLI.
2655 if (GlobalSegment != GlobalLI->begin()) {
2656 // Two address defs have no hole.
2657 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->end,
2658 GlobalSegment->start)) {
2659 return;
2660 }
2661 // If the prior global segment may be defined by the same two-address
2662 // instruction that also defines LocalLI, then can't make a hole here.
2663 if (SlotIndex::isSameInstr(std::prev(GlobalSegment)->start,
2664 LocalLI->beginIndex())) {
2665 return;
2666 }
2667 // If GlobalLI has a prior segment, it must be live into the EBB. Otherwise
2668 // it would be a disconnected component in the live range.
2669 assert(std::prev(GlobalSegment)->start < LocalLI->beginIndex() &&
2670 "Disconnected LRG within the scheduling region.");
2671 }
2672 MachineInstr *GlobalDef = LIS->getInstructionFromIndex(GlobalSegment->start);
2673 if (!GlobalDef)
2674 return;
2675
2676 SUnit *GlobalSU = DAG->getSUnit(GlobalDef);
2677 if (!GlobalSU)
2678 return;
2679
2680 // GlobalDef is the bottom of the GlobalLI hole. Open the hole by
2681 // constraining the uses of the last local def to precede GlobalDef.
2682 SmallVector<SUnit*,8> LocalUses;
2683 const VNInfo *LastLocalVN = LocalLI->getVNInfoBefore(LocalLI->endIndex());
2684 MachineInstr *LastLocalDef = LIS->getInstructionFromIndex(LastLocalVN->def);
2685 SUnit *LastLocalSU = DAG->getSUnit(LastLocalDef);
2686 for (const SDep &Succ : LastLocalSU->Succs) {
2687 if (Succ.getKind() != SDep::Data || Succ.getReg() != LocalReg)
2688 continue;
2689 if (Succ.getSUnit() == GlobalSU)
2690 continue;
2691 if (!DAG->canAddEdge(GlobalSU, Succ.getSUnit()))
2692 return;
2693 LocalUses.push_back(Succ.getSUnit());
2694 }
2695 // Open the top of the GlobalLI hole by constraining any earlier global uses
2696 // to precede the start of LocalLI.
2697 SmallVector<SUnit*,8> GlobalUses;
2698 MachineInstr *FirstLocalDef =
2699 LIS->getInstructionFromIndex(LocalLI->beginIndex());
2700 SUnit *FirstLocalSU = DAG->getSUnit(FirstLocalDef);
2701 for (const SDep &Pred : GlobalSU->Preds) {
2702 if (Pred.getKind() != SDep::Anti || Pred.getReg() != GlobalReg)
2703 continue;
2704 if (Pred.getSUnit() == FirstLocalSU)
2705 continue;
2706 if (!DAG->canAddEdge(FirstLocalSU, Pred.getSUnit()))
2707 return;
2708 GlobalUses.push_back(Pred.getSUnit());
2709 }
2710 LLVM_DEBUG(dbgs() << "Constraining copy " << *CopySU << "\n");
2711 // Add the weak edges.
2712 for (SUnit *LU : LocalUses) {
2713 LLVM_DEBUG(dbgs() << " Local use SU(" << LU->NodeNum << ") -> SU("
2714 << GlobalSU->NodeNum << ")\n");
2715 DAG->addEdge(GlobalSU, SDep(LU, SDep::Weak));
2716 }
2717 for (SUnit *GU : GlobalUses) {
2718 LLVM_DEBUG(dbgs() << " Global use " << *GU << " -> " << *FirstLocalSU
2719 << "\n");
2720 DAG->addEdge(FirstLocalSU, SDep(GU, SDep::Weak));
2721 }
2722}
2723
2724/// Callback from DAG postProcessing to create weak edges to encourage
2725/// copy elimination.
2726void CopyConstrain::apply(ScheduleDAGInstrs *DAGInstrs) {
2727 ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
2728 assert(DAG->hasVRegLiveness() && "Expect VRegs with LiveIntervals");
2729
2730 MachineBasicBlock::iterator FirstPos = nextIfDebug(DAG->begin(), DAG->end());
2731 if (FirstPos == DAG->end())
2732 return;
2733 RegionBeginIdx = DAG->getLIS()->getInstructionIndex(*FirstPos);
2734 RegionEndIdx = DAG->getLIS()->getInstructionIndex(
2735 *priorNonDebug(DAG->end(), DAG->begin()));
2736
2737 for (SUnit &SU : DAG->SUnits) {
2738 if (!SU.getInstr()->isCopy())
2739 continue;
2740
2741 constrainLocalCopy(&SU, static_cast<ScheduleDAGMILive*>(DAG));
2742 }
2743}
2744
2745//===----------------------------------------------------------------------===//
2746// MachineSchedStrategy helpers used by GenericScheduler, GenericPostScheduler
2747// and possibly other custom schedulers.
2748//===----------------------------------------------------------------------===//
2749
2750static const unsigned InvalidCycle = ~0U;
2751
2753
2754/// Given a Count of resource usage and a Latency value, return true if a
2755/// SchedBoundary becomes resource limited.
2756/// If we are checking after scheduling a node, we should return true when
2757/// we just reach the resource limit.
2758static bool checkResourceLimit(unsigned LFactor, unsigned Count,
2759 unsigned Latency, bool AfterSchedNode) {
2760 int ResCntFactor = (int)(Count - (Latency * LFactor));
2761 if (AfterSchedNode)
2762 return ResCntFactor >= (int)LFactor;
2763 else
2764 return ResCntFactor > (int)LFactor;
2765}
2766
2768 // A new HazardRec is created for each DAG and owned by SchedBoundary.
2769 // Destroying and reconstructing it is very expensive though. So keep
2770 // invalid, placeholder HazardRecs.
2771 if (HazardRec && HazardRec->isEnabled())
2772 HazardRec.reset();
2773 Available.clear();
2774 Pending.clear();
2775 CheckPending = false;
2776 CurrCycle = 0;
2777 CurrMOps = 0;
2778 MinReadyCycle = std::numeric_limits<unsigned>::max();
2779 ExpectedLatency = 0;
2780 DependentLatency = 0;
2781 RetiredMOps = 0;
2782 MaxExecutedResCount = 0;
2783 ZoneCritResIdx = 0;
2784 IsResourceLimited = false;
2785 ReservedCycles.clear();
2786 ReservedResourceSegments.clear();
2787 ReservedCyclesIndex.clear();
2788 ResourceGroupSubUnitMasks.clear();
2789#if LLVM_ENABLE_ABI_BREAKING_CHECKS
2790 // Track the maximum number of stall cycles that could arise either from the
2791 // latency of a DAG edge or the number of cycles that a processor resource is
2792 // reserved (SchedBoundary::ReservedCycles).
2793 MaxObservedStall = 0;
2794#endif
2795 // Reserve a zero-count for invalid CritResIdx.
2796 ExecutedResCounts.resize(1);
2797 assert(!ExecutedResCounts[0] && "nonzero count for bad resource");
2798}
2799
2801init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel) {
2802 reset();
2803 if (!SchedModel->hasInstrSchedModel())
2804 return;
2805 RemainingCounts.resize(SchedModel->getNumProcResourceKinds());
2806 for (SUnit &SU : DAG->SUnits) {
2807 const MCSchedClassDesc *SC = DAG->getSchedClass(&SU);
2808 RemIssueCount += SchedModel->getNumMicroOps(SU.getInstr(), SC)
2809 * SchedModel->getMicroOpFactor();
2811 PI = SchedModel->getWriteProcResBegin(SC),
2812 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
2813 unsigned PIdx = PI->ProcResourceIdx;
2814 unsigned Factor = SchedModel->getResourceFactor(PIdx);
2815 assert(PI->ReleaseAtCycle >= PI->AcquireAtCycle);
2816 RemainingCounts[PIdx] +=
2817 (Factor * (PI->ReleaseAtCycle - PI->AcquireAtCycle));
2818 }
2819 }
2820}
2821
2823init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem) {
2824 reset();
2825 DAG = dag;
2826 SchedModel = smodel;
2827 Rem = rem;
2828 if (SchedModel->hasInstrSchedModel()) {
2829 unsigned ResourceCount = SchedModel->getNumProcResourceKinds();
2830 ReservedCyclesIndex.resize(ResourceCount);
2831 ExecutedResCounts.resize(ResourceCount);
2832 ResourceGroupSubUnitMasks.resize(ResourceCount, APInt(ResourceCount, 0));
2833 unsigned NumUnits = 0;
2834
2835 for (unsigned i = 0; i < ResourceCount; ++i) {
2836 ReservedCyclesIndex[i] = NumUnits;
2837 NumUnits += SchedModel->getProcResource(i)->NumUnits;
2838 if (isReservedGroup(i)) {
2839 auto SubUnits = SchedModel->getProcResource(i)->SubUnitsIdxBegin;
2840 for (unsigned U = 0, UE = SchedModel->getProcResource(i)->NumUnits;
2841 U != UE; ++U)
2842 ResourceGroupSubUnitMasks[i].setBit(SubUnits[U]);
2843 }
2844 }
2845
2846 ReservedCycles.resize(NumUnits, InvalidCycle);
2847 }
2848}
2849
2850/// Compute the stall cycles based on this SUnit's ready time. Heuristics treat
2851/// these "soft stalls" differently than the hard stall cycles based on CPU
2852/// resources and computed by checkHazard(). A fully in-order model
2853/// (MicroOpBufferSize==0) will not make use of this since instructions are not
2854/// available for scheduling until they are ready. However, a weaker in-order
2855/// model may use this for heuristics. For example, if a processor has in-order
2856/// behavior when reading certain resources, this may come into play.
2858 if (!SU->isUnbuffered)
2859 return 0;
2860
2861 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
2862 if (ReadyCycle > CurrCycle)
2863 return ReadyCycle - CurrCycle;
2864 return 0;
2865}
2866
2867/// Compute the next cycle at which the given processor resource unit
2868/// can be scheduled.
2870 unsigned ReleaseAtCycle,
2871 unsigned AcquireAtCycle) {
2872 if (SchedModel && SchedModel->enableIntervals()) {
2873 if (isTop())
2874 return ReservedResourceSegments[InstanceIdx].getFirstAvailableAtFromTop(
2875 CurrCycle, AcquireAtCycle, ReleaseAtCycle);
2876
2877 return ReservedResourceSegments[InstanceIdx].getFirstAvailableAtFromBottom(
2878 CurrCycle, AcquireAtCycle, ReleaseAtCycle);
2879 }
2880
2881 unsigned NextUnreserved = ReservedCycles[InstanceIdx];
2882 // If this resource has never been used, always return cycle zero.
2883 if (NextUnreserved == InvalidCycle)
2884 return CurrCycle;
2885 // For bottom-up scheduling add the cycles needed for the current operation.
2886 if (!isTop())
2887 NextUnreserved = std::max(CurrCycle, NextUnreserved + ReleaseAtCycle);
2888 return NextUnreserved;
2889}
2890
2891/// Compute the next cycle at which the given processor resource can be
2892/// scheduled. Returns the next cycle and the index of the processor resource
2893/// instance in the reserved cycles vector.
2894std::pair<unsigned, unsigned>
2896 unsigned ReleaseAtCycle,
2897 unsigned AcquireAtCycle) {
2898 LLVM_DEBUG(if (DAG->Opts.misched_detail_resource_booking) {
2899 dbgs() << " Resource booking (@" << CurrCycle << "c): \n";
2900 dumpReservedCycles();
2901 dbgs() << " getNextResourceCycle (@" << CurrCycle << "c): \n";
2902 });
2903 unsigned MinNextUnreserved = InvalidCycle;
2904 unsigned InstanceIdx = 0;
2905 unsigned StartIndex = ReservedCyclesIndex[PIdx];
2906 unsigned NumberOfInstances = SchedModel->getProcResource(PIdx)->NumUnits;
2907 assert(NumberOfInstances > 0 &&
2908 "Cannot have zero instances of a ProcResource");
2909
2910 if (isReservedGroup(PIdx)) {
2911 // If any subunits are used by the instruction, report that the
2912 // subunits of the resource group are available at the first cycle
2913 // in which the unit is available, effectively removing the group
2914 // record from hazarding and basing the hazarding decisions on the
2915 // subunit records. Otherwise, choose the first available instance
2916 // from among the subunits. Specifications which assign cycles to
2917 // both the subunits and the group or which use an unbuffered
2918 // group with buffered subunits will appear to schedule
2919 // strangely. In the first case, the additional cycles for the
2920 // group will be ignored. In the second, the group will be
2921 // ignored entirely.
2922 for (const MCWriteProcResEntry &PE :
2923 make_range(SchedModel->getWriteProcResBegin(SC),
2924 SchedModel->getWriteProcResEnd(SC)))
2925 if (ResourceGroupSubUnitMasks[PIdx][PE.ProcResourceIdx])
2926 return std::make_pair(getNextResourceCycleByInstance(
2927 StartIndex, ReleaseAtCycle, AcquireAtCycle),
2928 StartIndex);
2929
2930 auto SubUnits = SchedModel->getProcResource(PIdx)->SubUnitsIdxBegin;
2931 for (unsigned I = 0, End = NumberOfInstances; I < End; ++I) {
2932 unsigned NextUnreserved, NextInstanceIdx;
2933 std::tie(NextUnreserved, NextInstanceIdx) =
2934 getNextResourceCycle(SC, SubUnits[I], ReleaseAtCycle, AcquireAtCycle);
2935 if (MinNextUnreserved > NextUnreserved) {
2936 InstanceIdx = NextInstanceIdx;
2937 MinNextUnreserved = NextUnreserved;
2938 }
2939 }
2940 return std::make_pair(MinNextUnreserved, InstanceIdx);
2941 }
2942
2943 for (unsigned I = StartIndex, End = StartIndex + NumberOfInstances; I < End;
2944 ++I) {
2945 unsigned NextUnreserved =
2946 getNextResourceCycleByInstance(I, ReleaseAtCycle, AcquireAtCycle);
2947 LLVM_DEBUG({
2948 if (DAG->Opts.misched_detail_resource_booking)
2949 dbgs() << " Instance " << I - StartIndex << " available @"
2950 << NextUnreserved << "c\n";
2951 });
2952 if (MinNextUnreserved > NextUnreserved) {
2953 InstanceIdx = I;
2954 MinNextUnreserved = NextUnreserved;
2955 }
2956 }
2957 LLVM_DEBUG({
2958 if (DAG->Opts.misched_detail_resource_booking)
2959 dbgs() << " selecting " << SchedModel->getResourceName(PIdx) << "["
2960 << InstanceIdx - StartIndex << "]"
2961 << " available @" << MinNextUnreserved << "c"
2962 << "\n";
2963 });
2964 return std::make_pair(MinNextUnreserved, InstanceIdx);
2965}
2966
2967/// Does this SU have a hazard within the current instruction group.
2968///
2969/// The scheduler supports two modes of hazard recognition. The first is the
2970/// ScheduleHazardRecognizer API. It is a fully general hazard recognizer that
2971/// supports highly complicated in-order reservation tables
2972/// (ScoreboardHazardRecognizer) and arbitrary target-specific logic.
2973///
2974/// The second is a streamlined mechanism that checks for hazards based on
2975/// simple counters that the scheduler itself maintains. It explicitly checks
2976/// for instruction dispatch limitations, including the number of micro-ops that
2977/// can dispatch per cycle.
2978///
2979/// TODO: Also check whether the SU must start a new group.
2981 if (HazardRec->isEnabled()
2982 && HazardRec->getHazardType(SU) != ScheduleHazardRecognizer::NoHazard) {
2984 << "hazard: " << *SU << " reported by HazardRec\n");
2985 return true;
2986 }
2987
2988 unsigned uops = SchedModel->getNumMicroOps(SU->getInstr());
2989 if ((CurrMOps > 0) && (CurrMOps + uops > SchedModel->getIssueWidth())) {
2990 LLVM_DEBUG(dbgs().indent(2) << "hazard: " << *SU << " uops=" << uops
2991 << ", CurrMOps = " << CurrMOps << ", "
2992 << "CurrMOps + uops > issue width of "
2993 << SchedModel->getIssueWidth() << "\n");
2994 return true;
2995 }
2996
2997 if (CurrMOps > 0 &&
2998 ((isTop() && SchedModel->mustBeginGroup(SU->getInstr())) ||
2999 (!isTop() && SchedModel->mustEndGroup(SU->getInstr())))) {
3000 LLVM_DEBUG(dbgs().indent(2) << "hazard: " << *SU << " must "
3001 << (isTop() ? "begin" : "end") << " group\n");
3002 return true;
3003 }
3004
3005 if (SchedModel->hasInstrSchedModel() && SU->hasReservedResource) {
3006 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
3007 for (const MCWriteProcResEntry &PE :
3008 make_range(SchedModel->getWriteProcResBegin(SC),
3009 SchedModel->getWriteProcResEnd(SC))) {
3010 unsigned ResIdx = PE.ProcResourceIdx;
3011 unsigned ReleaseAtCycle = PE.ReleaseAtCycle;
3012 unsigned AcquireAtCycle = PE.AcquireAtCycle;
3013 unsigned NRCycle, InstanceIdx;
3014 std::tie(NRCycle, InstanceIdx) =
3015 getNextResourceCycle(SC, ResIdx, ReleaseAtCycle, AcquireAtCycle);
3016 if (NRCycle > CurrCycle) {
3017#if LLVM_ENABLE_ABI_BREAKING_CHECKS
3018 MaxObservedStall = std::max(ReleaseAtCycle, MaxObservedStall);
3019#endif
3021 << "hazard: " << *SU << " "
3022 << SchedModel->getResourceName(ResIdx) << '['
3023 << InstanceIdx - ReservedCyclesIndex[ResIdx] << ']' << "="
3024 << NRCycle << "c, is later than "
3025 << "CurrCycle = " << CurrCycle << "c\n");
3026 return true;
3027 }
3028 }
3029 }
3030 return false;
3031}
3032
3033// Find the unscheduled node in ReadySUs with the highest latency.
3036 SUnit *LateSU = nullptr;
3037 unsigned RemLatency = 0;
3038 for (SUnit *SU : ReadySUs) {
3039 unsigned L = getUnscheduledLatency(SU);
3040 if (L > RemLatency) {
3041 RemLatency = L;
3042 LateSU = SU;
3043 }
3044 }
3045 if (LateSU) {
3046 LLVM_DEBUG(dbgs() << Available.getName() << " RemLatency " << *LateSU << " "
3047 << RemLatency << "c\n");
3048 }
3049 return RemLatency;
3050}
3051
3052// Count resources in this zone and the remaining unscheduled
3053// instruction. Return the max count, scaled. Set OtherCritIdx to the critical
3054// resource index, or zero if the zone is issue limited.
3056getOtherResourceCount(unsigned &OtherCritIdx) {
3057 OtherCritIdx = 0;
3058 if (!SchedModel->hasInstrSchedModel())
3059 return 0;
3060
3061 unsigned OtherCritCount = Rem->RemIssueCount
3062 + (RetiredMOps * SchedModel->getMicroOpFactor());
3063 LLVM_DEBUG(dbgs() << " " << Available.getName() << " + Remain MOps: "
3064 << OtherCritCount / SchedModel->getMicroOpFactor() << '\n');
3065 for (unsigned PIdx = 1, PEnd = SchedModel->getNumProcResourceKinds();
3066 PIdx != PEnd; ++PIdx) {
3067 unsigned OtherCount = getResourceCount(PIdx) + Rem->RemainingCounts[PIdx];
3068 if (OtherCount > OtherCritCount) {
3069 OtherCritCount = OtherCount;
3070 OtherCritIdx = PIdx;
3071 }
3072 }
3073 if (OtherCritIdx) {
3074 LLVM_DEBUG(
3075 dbgs() << " " << Available.getName() << " + Remain CritRes: "
3076 << OtherCritCount / SchedModel->getResourceFactor(OtherCritIdx)
3077 << " " << SchedModel->getResourceName(OtherCritIdx) << "\n");
3078 }
3079 return OtherCritCount;
3080}
3081
3082void SchedBoundary::releaseNode(SUnit *SU, unsigned ReadyCycle, bool InPQueue,
3083 unsigned Idx) {
3084 assert(SU->getInstr() && "Scheduled SUnit must have instr");
3085
3086#if LLVM_ENABLE_ABI_BREAKING_CHECKS
3087 // ReadyCycle was been bumped up to the CurrCycle when this node was
3088 // scheduled, but CurrCycle may have been eagerly advanced immediately after
3089 // scheduling, so may now be greater than ReadyCycle.
3090 if (ReadyCycle > CurrCycle)
3091 MaxObservedStall = std::max(ReadyCycle - CurrCycle, MaxObservedStall);
3092#endif
3093
3094 if (ReadyCycle < MinReadyCycle)
3095 MinReadyCycle = ReadyCycle;
3096
3097 // Check for interlocks first. For the purpose of other heuristics, an
3098 // instruction that cannot issue appears as if it's not in the ReadyQueue.
3099 bool IsBuffered = SchedModel->getMicroOpBufferSize() != 0;
3100 bool HazardDetected = !IsBuffered && ReadyCycle > CurrCycle;
3101 if (HazardDetected)
3103 << "hazard: " << *SU << " ReadyCycle = " << ReadyCycle
3104 << " is later than CurrCycle = " << CurrCycle
3105 << " on an unbuffered resource" << "\n");
3106 else
3107 HazardDetected = checkHazard(SU);
3108
3109 if (!HazardDetected && Available.size() >= DAG->Opts.misched_limit) {
3110 HazardDetected = true;
3111 LLVM_DEBUG(dbgs().indent(2) << "hazard: Available Q is full (size: "
3112 << Available.size() << ")\n");
3113 }
3114
3115 if (!HazardDetected) {
3116 Available.push(SU);
3117 LLVM_DEBUG(dbgs().indent(2) << "Move " << *SU << " into Available Q\n");
3118
3119 if (InPQueue)
3120 Pending.remove(Pending.begin() + Idx);
3121 return;
3122 }
3123
3124 if (!InPQueue)
3125 Pending.push(SU);
3126}
3127
3128/// Move the boundary of scheduled code by one cycle.
3129void SchedBoundary::bumpCycle(unsigned NextCycle) {
3130 if (SchedModel->getMicroOpBufferSize() == 0) {
3131 assert(MinReadyCycle < std::numeric_limits<unsigned>::max() &&
3132 "MinReadyCycle uninitialized");
3133 if (MinReadyCycle > NextCycle)
3134 NextCycle = MinReadyCycle;
3135 }
3136 // Update the current micro-ops, which will issue in the next cycle.
3137 unsigned DecMOps = SchedModel->getIssueWidth() * (NextCycle - CurrCycle);
3138 CurrMOps = (CurrMOps <= DecMOps) ? 0 : CurrMOps - DecMOps;
3139
3140 // Decrement DependentLatency based on the next cycle.
3141 if ((NextCycle - CurrCycle) > DependentLatency)
3142 DependentLatency = 0;
3143 else
3144 DependentLatency -= (NextCycle - CurrCycle);
3145
3146 if (!HazardRec->isEnabled()) {
3147 // Bypass HazardRec virtual calls.
3148 CurrCycle = NextCycle;
3149 } else {
3150 // Bypass getHazardType calls in case of long latency.
3151 for (; CurrCycle != NextCycle; ++CurrCycle) {
3152 if (isTop())
3153 HazardRec->AdvanceCycle();
3154 else
3155 HazardRec->RecedeCycle();
3156 }
3157 }
3158 CheckPending = true;
3159 IsResourceLimited =
3160 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
3161 getScheduledLatency(), true);
3162
3163 LLVM_DEBUG(dbgs() << "Cycle: " << CurrCycle << ' ' << Available.getName()
3164 << '\n');
3165}
3166
3167void SchedBoundary::incExecutedResources(unsigned PIdx, unsigned Count) {
3168 ExecutedResCounts[PIdx] += Count;
3169 if (ExecutedResCounts[PIdx] > MaxExecutedResCount)
3170 MaxExecutedResCount = ExecutedResCounts[PIdx];
3171}
3172
3173/// Add the given processor resource to this scheduled zone.
3174///
3175/// \param ReleaseAtCycle indicates the number of consecutive (non-pipelined)
3176/// cycles during which this resource is released.
3177///
3178/// \param AcquireAtCycle indicates the number of consecutive (non-pipelined)
3179/// cycles at which the resource is aquired after issue (assuming no stalls).
3180///
3181/// \return the next cycle at which the instruction may execute without
3182/// oversubscribing resources.
3183unsigned SchedBoundary::countResource(const MCSchedClassDesc *SC, unsigned PIdx,
3184 unsigned ReleaseAtCycle,
3185 unsigned NextCycle,
3186 unsigned AcquireAtCycle) {
3187 unsigned Factor = SchedModel->getResourceFactor(PIdx);
3188 unsigned Count = Factor * (ReleaseAtCycle- AcquireAtCycle);
3189 LLVM_DEBUG(dbgs() << " " << SchedModel->getResourceName(PIdx) << " +"
3190 << ReleaseAtCycle << "x" << Factor << "u\n");
3191
3192 // Update Executed resources counts.
3194 assert(Rem->RemainingCounts[PIdx] >= Count && "resource double counted");
3195 Rem->RemainingCounts[PIdx] -= Count;
3196
3197 // Check if this resource exceeds the current critical resource. If so, it
3198 // becomes the critical resource.
3199 if (ZoneCritResIdx != PIdx && (getResourceCount(PIdx) > getCriticalCount())) {
3200 ZoneCritResIdx = PIdx;
3201 LLVM_DEBUG(dbgs() << " *** Critical resource "
3202 << SchedModel->getResourceName(PIdx) << ": "
3203 << getResourceCount(PIdx) / SchedModel->getLatencyFactor()
3204 << "c\n");
3205 }
3206 // For reserved resources, record the highest cycle using the resource.
3207 unsigned NextAvailable, InstanceIdx;
3208 std::tie(NextAvailable, InstanceIdx) =
3209 getNextResourceCycle(SC, PIdx, ReleaseAtCycle, AcquireAtCycle);
3210 if (NextAvailable > CurrCycle) {
3211 LLVM_DEBUG(dbgs() << " Resource conflict: "
3212 << SchedModel->getResourceName(PIdx)
3213 << '[' << InstanceIdx - ReservedCyclesIndex[PIdx] << ']'
3214 << " reserved until @" << NextAvailable << "\n");
3215 }
3216 return NextAvailable;
3217}
3218
3219/// Move the boundary of scheduled code by one SUnit.
3221 // checkHazard should prevent scheduling multiple instructions per cycle that
3222 // exceed the issue width.
3223 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
3224 unsigned IncMOps = SchedModel->getNumMicroOps(SU->getInstr());
3225 assert(
3226 (CurrMOps == 0 || (CurrMOps + IncMOps) <= SchedModel->getIssueWidth()) &&
3227 "Cannot schedule this instruction's MicroOps in the current cycle.");
3228
3229 unsigned ReadyCycle = (isTop() ? SU->TopReadyCycle : SU->BotReadyCycle);
3230 LLVM_DEBUG(dbgs() << " Ready @" << ReadyCycle << "c\n");
3231
3232 unsigned NextCycle = CurrCycle;
3233 switch (SchedModel->getMicroOpBufferSize()) {
3234 case 0:
3235 assert(ReadyCycle <= CurrCycle && "Broken PendingQueue");
3236 break;
3237 case 1:
3238 if (ReadyCycle > NextCycle) {
3239 NextCycle = ReadyCycle;
3240 LLVM_DEBUG(dbgs() << " *** Stall until: " << ReadyCycle << "\n");
3241 }
3242 break;
3243 default:
3244 // We don't currently model the OOO reorder buffer, so consider all
3245 // scheduled MOps to be "retired". We do loosely model in-order resource
3246 // latency. If this instruction uses an in-order resource, account for any
3247 // likely stall cycles.
3248 if (SU->isUnbuffered && ReadyCycle > NextCycle)
3249 NextCycle = ReadyCycle;
3250 break;
3251 }
3252 RetiredMOps += IncMOps;
3253
3254 // Update resource counts and critical resource.
3255 if (SchedModel->hasInstrSchedModel()) {
3256 unsigned DecRemIssue = IncMOps * SchedModel->getMicroOpFactor();
3257 assert(Rem->RemIssueCount >= DecRemIssue && "MOps double counted");
3258 Rem->RemIssueCount -= DecRemIssue;
3259 if (ZoneCritResIdx) {
3260 // Scale scheduled micro-ops for comparing with the critical resource.
3261 unsigned ScaledMOps =
3262 RetiredMOps * SchedModel->getMicroOpFactor();
3263
3264 // If scaled micro-ops are now more than the previous critical resource by
3265 // a full cycle, then micro-ops issue becomes critical.
3266 if ((int)(ScaledMOps - getResourceCount(ZoneCritResIdx))
3267 >= (int)SchedModel->getLatencyFactor()) {
3268 ZoneCritResIdx = 0;
3269 LLVM_DEBUG(dbgs() << " *** Critical resource NumMicroOps: "
3270 << ScaledMOps / SchedModel->getLatencyFactor()
3271 << "c\n");
3272 }
3273 }
3275 PI = SchedModel->getWriteProcResBegin(SC),
3276 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
3277 unsigned RCycle =
3278 countResource(SC, PI->ProcResourceIdx, PI->ReleaseAtCycle, NextCycle,
3279 PI->AcquireAtCycle);
3280 if (RCycle > NextCycle)
3281 NextCycle = RCycle;
3282 }
3283 if (SU->hasReservedResource) {
3284 // For reserved resources, record the highest cycle using the resource.
3285 // For top-down scheduling, this is the cycle in which we schedule this
3286 // instruction plus the number of cycles the operations reserves the
3287 // resource. For bottom-up is it simply the instruction's cycle.
3289 PI = SchedModel->getWriteProcResBegin(SC),
3290 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
3291 unsigned PIdx = PI->ProcResourceIdx;
3292 if (SchedModel->getResourceBufferSize(PIdx) == 0) {
3293
3294 if (SchedModel && SchedModel->enableIntervals()) {
3295 unsigned ReservedUntil, InstanceIdx;
3296 std::tie(ReservedUntil, InstanceIdx) = getNextResourceCycle(
3297 SC, PIdx, PI->ReleaseAtCycle, PI->AcquireAtCycle);
3298 if (isTop()) {
3299 ReservedResourceSegments[InstanceIdx].add(
3301 NextCycle, PI->AcquireAtCycle, PI->ReleaseAtCycle),
3302 DAG->Opts.misched_resource_cutoff);
3303 } else {
3304 ReservedResourceSegments[InstanceIdx].add(
3306 NextCycle, PI->AcquireAtCycle, PI->ReleaseAtCycle),
3307 DAG->Opts.misched_resource_cutoff);
3308 }
3309 } else {
3310
3311 unsigned ReservedUntil, InstanceIdx;
3312 std::tie(ReservedUntil, InstanceIdx) = getNextResourceCycle(
3313 SC, PIdx, PI->ReleaseAtCycle, PI->AcquireAtCycle);
3314 if (isTop()) {
3315 ReservedCycles[InstanceIdx] =
3316 std::max(ReservedUntil, NextCycle + PI->ReleaseAtCycle);
3317 } else
3318 ReservedCycles[InstanceIdx] = NextCycle;
3319 }
3320 }
3321 }
3322 }
3323 }
3324 // Update ExpectedLatency and DependentLatency.
3325 unsigned &TopLatency = isTop() ? ExpectedLatency : DependentLatency;
3326 unsigned &BotLatency = isTop() ? DependentLatency : ExpectedLatency;
3327 if (SU->getDepth() > TopLatency) {
3328 TopLatency = SU->getDepth();
3329 LLVM_DEBUG(dbgs() << " " << Available.getName() << " TopLatency " << *SU
3330 << " " << TopLatency << "c\n");
3331 }
3332 if (SU->getHeight() > BotLatency) {
3333 BotLatency = SU->getHeight();
3334 LLVM_DEBUG(dbgs() << " " << Available.getName() << " BotLatency " << *SU
3335 << " " << BotLatency << "c\n");
3336 }
3337 // If we stall for any reason, bump the cycle.
3338 if (NextCycle > CurrCycle)
3339 bumpCycle(NextCycle);
3340 else
3341 // After updating ZoneCritResIdx and ExpectedLatency, check if we're
3342 // resource limited. If a stall occurred, bumpCycle does this.
3343 IsResourceLimited =
3344 checkResourceLimit(SchedModel->getLatencyFactor(), getCriticalCount(),
3345 getScheduledLatency(), true);
3346
3347 // Update the reservation table.
3348 if (HazardRec->isEnabled()) {
3349 if (!isTop() && SU->isCall) {
3350 // Calls are scheduled with their preceding instructions. For bottom-up
3351 // scheduling, clear the pipeline state before emitting.
3352 HazardRec->Reset();
3353 }
3354 HazardRec->EmitInstruction(SU);
3355 // Scheduling an instruction may have made pending instructions available.
3356 CheckPending = true;
3357 }
3358
3359 // Update CurrMOps after calling bumpCycle to handle stalls, since bumpCycle
3360 // resets CurrMOps. Loop to handle instructions with more MOps than issue in
3361 // one cycle. Since we commonly reach the max MOps here, opportunistically
3362 // bump the cycle to avoid uselessly checking everything in the readyQ.
3363 CurrMOps += IncMOps;
3364
3365 // Bump the cycle count for issue group constraints.
3366 // This must be done after NextCycle has been adjust for all other stalls.
3367 // Calling bumpCycle(X) will reduce CurrMOps by one issue group and set
3368 // currCycle to X.
3369 if ((isTop() && SchedModel->mustEndGroup(SU->getInstr())) ||
3370 (!isTop() && SchedModel->mustBeginGroup(SU->getInstr()))) {
3371 LLVM_DEBUG(dbgs() << " Bump cycle to " << (isTop() ? "end" : "begin")
3372 << " group\n");
3373 bumpCycle(++NextCycle);
3374 }
3375
3376 while (CurrMOps >= SchedModel->getIssueWidth()) {
3377 LLVM_DEBUG(dbgs() << " *** Max MOps " << CurrMOps << " at cycle "
3378 << CurrCycle << '\n');
3379 bumpCycle(++NextCycle);
3380 }
3382}
3383
3384/// Release pending ready nodes in to the available queue. This makes them
3385/// visible to heuristics.
3387 // If the available queue is empty, it is safe to reset MinReadyCycle.
3388 if (Available.empty())
3389 MinReadyCycle = std::numeric_limits<unsigned>::max();
3390
3391 // Check to see if any of the pending instructions are ready to issue. If
3392 // so, add them to the available queue.
3393 for (unsigned I = 0, E = Pending.size(); I < E; ++I) {
3394 SUnit *SU = *(Pending.begin() + I);
3395 unsigned ReadyCycle = isTop() ? SU->TopReadyCycle : SU->BotReadyCycle;
3396
3397 LLVM_DEBUG(dbgs() << "Checking pending node " << *SU << "\n");
3398
3399 if (ReadyCycle < MinReadyCycle)
3400 MinReadyCycle = ReadyCycle;
3401
3402 if (Available.size() >= DAG->Opts.misched_limit)
3403 break;
3404
3405 releaseNode(SU, ReadyCycle, true, I);
3406 if (E != Pending.size()) {
3407 --I;
3408 --E;
3409 }
3410 }
3411 CheckPending = false;
3412}
3413
3414/// Remove SU from the ready set for this boundary.
3416 if (Available.isInQueue(SU))
3417 Available.remove(Available.find(SU));
3418 else {
3419 assert(Pending.isInQueue(SU) && "bad ready count");
3420 Pending.remove(Pending.find(SU));
3421 }
3422}
3423
3424/// If this queue only has one ready candidate, return it. As a side effect,
3425/// defer any nodes that now hit a hazard, and advance the cycle until at least
3426/// one node is ready. If multiple instructions are ready, return NULL.
3428 if (CheckPending)
3430
3431 // Defer any ready instrs that now have a hazard.
3432 for (ReadyQueue::iterator I = Available.begin(); I != Available.end();) {
3433 if (checkHazard(*I)) {
3434 Pending.push(*I);
3435 I = Available.remove(I);
3436 continue;
3437 }
3438 ++I;
3439 }
3440 for (unsigned i = 0; Available.empty(); ++i) {
3441// FIXME: Re-enable assert once PR20057 is resolved.
3442// assert(i <= (HazardRec->getMaxLookAhead() + MaxObservedStall) &&
3443// "permanent hazard");
3444 (void)i;
3445 bumpCycle(CurrCycle + 1);
3447 }
3448
3449 LLVM_DEBUG(Pending.dump());
3450 LLVM_DEBUG(Available.dump());
3451
3452 if (Available.size() == 1)
3453 return *Available.begin();
3454 return nullptr;
3455}
3456
3457#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3458
3459/// Dump the content of the \ref ReservedCycles vector for the
3460/// resources that are used in the basic block.
3461///
3463 if (!SchedModel->hasInstrSchedModel())
3464 return;
3465
3466 unsigned ResourceCount = SchedModel->getNumProcResourceKinds();
3467 unsigned StartIdx = 0;
3468
3469 for (unsigned ResIdx = 0; ResIdx < ResourceCount; ++ResIdx) {
3470 const unsigned NumUnits = SchedModel->getProcResource(ResIdx)->NumUnits;
3471 std::string ResName = SchedModel->getResourceName(ResIdx);
3472 for (unsigned UnitIdx = 0; UnitIdx < NumUnits; ++UnitIdx) {
3473 dbgs() << ResName << "(" << UnitIdx << ") = ";
3474 if (SchedModel && SchedModel->enableIntervals()) {
3475 if (ReservedResourceSegments.count(StartIdx + UnitIdx))
3476 dbgs() << ReservedResourceSegments.at(StartIdx + UnitIdx);
3477 else
3478 dbgs() << "{ }\n";
3479 } else
3480 dbgs() << ReservedCycles[StartIdx + UnitIdx] << "\n";
3481 }
3482 StartIdx += NumUnits;
3483 }
3484}
3485
3486// This is useful information to dump after bumpNode.
3487// Note that the Queue contents are more useful before pickNodeFromQueue.
3489 unsigned ResFactor;
3490 unsigned ResCount;
3491 if (ZoneCritResIdx) {
3492 ResFactor = SchedModel->getResourceFactor(ZoneCritResIdx);
3493 ResCount = getResourceCount(ZoneCritResIdx);
3494 } else {
3495 ResFactor = SchedModel->getMicroOpFactor();
3496 ResCount = RetiredMOps * ResFactor;
3497 }
3498 unsigned LFactor = SchedModel->getLatencyFactor();
3499 dbgs() << Available.getName() << " @" << CurrCycle << "c\n"
3500 << " Retired: " << RetiredMOps;
3501 dbgs() << "\n Executed: " << getExecutedCount() / LFactor << "c";
3502 dbgs() << "\n Critical: " << ResCount / LFactor << "c, "
3503 << ResCount / ResFactor << " "
3504 << SchedModel->getResourceName(ZoneCritResIdx)
3505 << "\n ExpectedLatency: " << ExpectedLatency << "c\n"
3506 << (IsResourceLimited ? " - Resource" : " - Latency")
3507 << " limited.\n";
3508#ifndef NDEBUG
3509 if (DAG->Opts.misched_dump_reserved_cycles)
3511#endif
3512}
3513#endif
3514
3515//===----------------------------------------------------------------------===//
3516// GenericScheduler - Generic implementation of MachineSchedStrategy.
3517//===----------------------------------------------------------------------===//
3518
3522 if (!Policy.ReduceResIdx && !Policy.DemandResIdx)
3523 return;
3524
3525 const MCSchedClassDesc *SC = DAG->getSchedClass(SU);
3527 PI = SchedModel->getWriteProcResBegin(SC),
3528 PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) {
3529 if (PI->ProcResourceIdx == Policy.ReduceResIdx)
3530 ResDelta.CritResources += PI->ReleaseAtCycle;
3531 if (PI->ProcResourceIdx == Policy.DemandResIdx)
3532 ResDelta.DemandedResources += PI->ReleaseAtCycle;
3533 }
3534}
3535
3536/// Returns true if the current cycle plus remaning latency is greater than
3537/// the critical path in the scheduling region.
3538bool GenericSchedulerBase::shouldReduceLatency(const CandPolicy &Policy,
3539 SchedBoundary &CurrZone,
3540 bool ComputeRemLatency,
3541 unsigned &RemLatency) const {
3542 // The current cycle is already greater than the critical path, so we are
3543 // already latency limited and don't need to compute the remaining latency.
3544 if (CurrZone.getCurrCycle() > Rem.CriticalPath)
3545 return true;
3546
3547 // If we haven't scheduled anything yet, then we aren't latency limited.
3548 if (CurrZone.getCurrCycle() == 0)
3549 return false;
3550
3551 if (ComputeRemLatency)
3552 RemLatency = computeRemLatency(CurrZone);
3553
3554 return RemLatency + CurrZone.getCurrCycle() > Rem.CriticalPath;
3555}
3556
3557/// Set the CandPolicy given a scheduling zone given the current resources and
3558/// latencies inside and outside the zone.
3560 SchedBoundary &CurrZone,
3561 SchedBoundary *OtherZone) {
3562 // Apply preemptive heuristics based on the total latency and resources
3563 // inside and outside this zone. Potential stalls should be considered before
3564 // following this policy.
3565
3566 // Compute the critical resource outside the zone.
3567 unsigned OtherCritIdx = 0;
3568 unsigned OtherCount =
3569 OtherZone ? OtherZone->getOtherResourceCount(OtherCritIdx) : 0;
3570
3571 bool OtherResLimited = false;
3572 unsigned RemLatency = 0;
3573 bool RemLatencyComputed = false;
3574 if (SchedModel->hasInstrSchedModel() && OtherCount != 0) {
3575 RemLatency = computeRemLatency(CurrZone);
3576 RemLatencyComputed = true;
3577 OtherResLimited = checkResourceLimit(SchedModel->getLatencyFactor(),
3578 OtherCount, RemLatency, false);
3579 }
3580
3581 // Schedule aggressively for latency in PostRA mode. We don't check for
3582 // acyclic latency during PostRA, and highly out-of-order processors will
3583 // skip PostRA scheduling.
3584 if (!OtherResLimited &&
3585 (IsPostRA || shouldReduceLatency(Policy, CurrZone, !RemLatencyComputed,
3586 RemLatency))) {
3587 Policy.ReduceLatency |= true;
3588 LLVM_DEBUG(dbgs() << " " << CurrZone.Available.getName()
3589 << " RemainingLatency " << RemLatency << " + "
3590 << CurrZone.getCurrCycle() << "c > CritPath "
3591 << Rem.CriticalPath << "\n");
3592 }
3593 // If the same resource is limiting inside and outside the zone, do nothing.
3594 if (CurrZone.getZoneCritResIdx() == OtherCritIdx)
3595 return;
3596
3597 LLVM_DEBUG(if (CurrZone.isResourceLimited()) {
3598 dbgs() << " " << CurrZone.Available.getName() << " ResourceLimited: "
3599 << SchedModel->getResourceName(CurrZone.getZoneCritResIdx()) << "\n";
3600 } if (OtherResLimited) dbgs()
3601 << " RemainingLimit: "
3602 << SchedModel->getResourceName(OtherCritIdx) << "\n";
3603 if (!CurrZone.isResourceLimited() && !OtherResLimited) dbgs()
3604 << " Latency limited both directions.\n");
3605
3606 if (CurrZone.isResourceLimited() && !Policy.ReduceResIdx)
3607 Policy.ReduceResIdx = CurrZone.getZoneCritResIdx();
3608
3609 if (OtherResLimited)
3610 Policy.DemandResIdx = OtherCritIdx;
3611}
3612
3613#ifndef NDEBUG
3616 // clang-format off
3617 switch (Reason) {
3618 case NoCand: return "NOCAND ";
3619 case Only1: return "ONLY1 ";
3620 case PhysReg: return "PHYS-REG ";
3621 case RegExcess: return "REG-EXCESS";
3622 case RegCritical: return "REG-CRIT ";
3623 case Stall: return "STALL ";
3624 case Cluster: return "CLUSTER ";
3625 case Weak: return "WEAK ";
3626 case RegMax: return "REG-MAX ";
3627 case ResourceReduce: return "RES-REDUCE";
3628 case ResourceDemand: return "RES-DEMAND";
3629 case TopDepthReduce: return "TOP-DEPTH ";
3630 case TopPathReduce: return "TOP-PATH ";
3631 case BotHeightReduce:return "BOT-HEIGHT";
3632 case BotPathReduce: return "BOT-PATH ";
3633 case NodeOrder: return "ORDER ";
3634 case FirstValid: return "FIRST ";
3635 };
3636 // clang-format on
3637 llvm_unreachable("Unknown reason!");
3638}
3639
3642 unsigned ResIdx = 0;
3643 unsigned Latency = 0;
3644 switch (Cand.Reason) {
3645 default:
3646 break;
3647 case RegExcess:
3648 P = Cand.RPDelta.Excess;
3649 break;
3650 case RegCritical:
3651 P = Cand.RPDelta.CriticalMax;
3652 break;
3653 case RegMax:
3654 P = Cand.RPDelta.CurrentMax;
3655 break;
3656 case ResourceReduce:
3657 ResIdx = Cand.Policy.ReduceResIdx;
3658 break;
3659 case ResourceDemand:
3660 ResIdx = Cand.Policy.DemandResIdx;
3661 break;
3662 case TopDepthReduce:
3663 Latency = Cand.SU->getDepth();
3664 break;
3665 case TopPathReduce:
3666 Latency = Cand.SU->getHeight();
3667 break;
3668 case BotHeightReduce:
3669 Latency = Cand.SU->getHeight();
3670 break;
3671 case BotPathReduce:
3672 Latency = Cand.SU->getDepth();
3673 break;
3674 }
3675 dbgs() << " Cand " << *Cand.SU << " " << getReasonStr(Cand.Reason);
3676 if (P.isValid())
3677 dbgs() << " " << TRI->getRegPressureSetName(P.getPSet())
3678 << ":" << P.getUnitInc() << " ";
3679 else
3680 dbgs() << " ";
3681 if (ResIdx)
3682 dbgs() << " " << SchedModel->getProcResource(ResIdx)->Name << " ";
3683 else
3684 dbgs() << " ";
3685 if (Latency)
3686 dbgs() << " " << Latency << " cycles ";
3687 else
3688 dbgs() << " ";
3689 dbgs() << '\n';
3690}
3691#endif
3692
3693/// Compute remaining latency. We need this both to determine whether the
3694/// overall schedule has become latency-limited and whether the instructions
3695/// outside this zone are resource or latency limited.
3696///
3697/// The "dependent" latency is updated incrementally during scheduling as the
3698/// max height/depth of scheduled nodes minus the cycles since it was
3699/// scheduled:
3700/// DLat = max (N.depth - (CurrCycle - N.ReadyCycle) for N in Zone
3701///
3702/// The "independent" latency is the max ready queue depth:
3703/// ILat = max N.depth for N in Available|Pending
3704///
3705/// RemainingLatency is the greater of independent and dependent latency.
3706///
3707/// These computations are expensive, especially in DAGs with many edges, so
3708/// only do them if necessary.
3710 unsigned RemLatency = CurrZone.getDependentLatency();
3711 RemLatency = std::max(RemLatency,
3712 CurrZone.findMaxLatency(CurrZone.Available.elements()));
3713 RemLatency = std::max(RemLatency,
3714 CurrZone.findMaxLatency(CurrZone.Pending.elements()));
3715 return RemLatency;
3716}
3717
3718/// Return true if this heuristic determines order.
3719/// TODO: Consider refactor return type of these functions as integer or enum,
3720/// as we may need to differentiate whether TryCand is better than Cand.
3721bool llvm::tryLess(int TryVal, int CandVal,
3725 if (TryVal < CandVal) {
3726 TryCand.Reason = Reason;
3727 return true;
3728 }
3729 if (TryVal > CandVal) {
3730 if (Cand.Reason > Reason)
3731 Cand.Reason = Reason;
3732 return true;
3733 }
3734 return false;
3735}
3736
3737bool llvm::tryGreater(int TryVal, int CandVal,
3741 if (TryVal > CandVal) {
3742 TryCand.Reason = Reason;
3743 return true;
3744 }
3745 if (TryVal < CandVal) {
3746 if (Cand.Reason > Reason)
3747 Cand.Reason = Reason;
3748 return true;
3749 }
3750 return false;
3751}
3752
3755 SchedBoundary &Zone) {
3756 if (Zone.isTop()) {
3757 // Prefer the candidate with the lesser depth, but only if one of them has
3758 // depth greater than the total latency scheduled so far, otherwise either
3759 // of them could be scheduled now with no stall.
3760 if (std::max(TryCand.SU->getDepth(), Cand.SU->getDepth()) >
3761 Zone.getScheduledLatency()) {
3762 if (tryLess(TryCand.SU->getDepth(), Cand.SU->getDepth(),
3764 return true;
3765 }
3766 if (tryGreater(TryCand.SU->getHeight(), Cand.SU->getHeight(),
3768 return true;
3769 } else {
3770 // Prefer the candidate with the lesser height, but only if one of them has
3771 // height greater than the total latency scheduled so far, otherwise either
3772 // of them could be scheduled now with no stall.
3773 if (std::max(TryCand.SU->getHeight(), Cand.SU->getHeight()) >
3774 Zone.getScheduledLatency()) {
3775 if (tryLess(TryCand.SU->getHeight(), Cand.SU->getHeight(),
3777 return true;
3778 }
3779 if (tryGreater(TryCand.SU->getDepth(), Cand.SU->getDepth(),
3781 return true;
3782 }
3783 return false;
3784}
3785
3786static void tracePick(const SUnit *SU,
3788 const bool IsTop, const bool IsPostRA = false) {
3789 assert(SU && "SU must not be null for tracing");
3790 LLVM_DEBUG(dbgs() << "Pick " << (IsTop ? "Top " : "Bot ") << "Cand " << *SU
3791 << " " << GenericSchedulerBase::getReasonStr(Reason) << " ["
3792 << (IsPostRA ? "post-RA" : "pre-RA") << "]\n");
3793
3794 if (IsPostRA) {
3795 if (IsTop)
3796 NumTopPostRA++;
3797 else
3798 NumBotPostRA++;
3799
3800 switch (Reason) {
3802 NumNoCandPostRA++;
3803 return;
3805 NumOnly1PostRA++;
3806 return;
3808 NumPhysRegPostRA++;
3809 return;
3811 NumRegExcessPostRA++;
3812 return;
3814 NumRegCriticalPostRA++;
3815 return;
3817 NumStallPostRA++;
3818 return;
3820 NumClusterPostRA++;
3821 return;
3823 NumWeakPostRA++;
3824 return;
3826 NumRegMaxPostRA++;
3827 return;
3829 NumResourceReducePostRA++;
3830 return;
3832 NumResourceDemandPostRA++;
3833 return;
3835 NumTopDepthReducePostRA++;
3836 return;
3838 NumTopPathReducePostRA++;
3839 return;
3841 NumBotHeightReducePostRA++;
3842 return;
3844 NumBotPathReducePostRA++;
3845 return;
3847 NumNodeOrderPostRA++;
3848 return;
3850 NumFirstValidPostRA++;
3851 return;
3852 };
3853 } else {
3854 if (IsTop)
3855 NumTopPreRA++;
3856 else
3857 NumBotPreRA++;
3858
3859 switch (Reason) {
3861 NumNoCandPreRA++;
3862 return;
3864 NumOnly1PreRA++;
3865 return;
3867 NumPhysRegPreRA++;
3868 return;
3870 NumRegExcessPreRA++;
3871 return;
3873 NumRegCriticalPreRA++;
3874 return;
3876 NumStallPreRA++;
3877 return;
3879 NumClusterPreRA++;
3880 return;
3882 NumWeakPreRA++;
3883 return;
3885 NumRegMaxPreRA++;
3886 return;
3888 NumResourceReducePreRA++;
3889 return;
3891 NumResourceDemandPreRA++;
3892 return;
3894 NumTopDepthReducePreRA++;
3895 return;
3897 NumTopPathReducePreRA++;
3898 return;
3900 NumBotHeightReducePreRA++;
3901 return;
3903 NumBotPathReducePreRA++;
3904 return;
3906 NumNodeOrderPreRA++;
3907 return;
3909 NumFirstValidPreRA++;
3910 return;
3911 };
3912 }
3913 llvm_unreachable("Unknown reason!");
3914}
3915
3917 const bool IsPostRA = false) {
3918 tracePick(Cand.SU, Cand.Reason, Cand.AtTop, IsPostRA);
3919}
3920
3922 assert(dag->hasVRegLiveness() &&
3923 "(PreRA)GenericScheduler needs vreg liveness");
3924 DAG = static_cast<ScheduleDAGMILive*>(dag);
3925 SchedModel = DAG->getSchedModel();
3926 TRI = DAG->TRI;
3927
3928 if (RegionPolicy.ComputeDFSResult)
3929 DAG->computeDFSResult();
3930
3931 Rem.init(DAG, SchedModel);
3932 Top.init(DAG, SchedModel, &Rem);
3933 Bot.init(DAG, SchedModel, &Rem);
3934
3935 // Initialize resource counts.
3936
3937 // Initialize the HazardRecognizers. If itineraries don't exist, are empty, or
3938 // are disabled, then these HazardRecs will be disabled.
3939 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
3940 if (!Top.HazardRec)
3941 Top.HazardRec.reset(DAG->TII->CreateTargetMIHazardRecognizer(Itin, DAG));
3942 if (!Bot.HazardRec)
3943 Bot.HazardRec.reset(DAG->TII->CreateTargetMIHazardRecognizer(Itin, DAG));
3944 TopCand.SU = nullptr;
3945 BotCand.SU = nullptr;
3946
3949}
3950
3951/// Initialize the per-region scheduling policy.
3954 unsigned NumRegionInstrs) {
3955 const MachineFunction &MF = *Begin->getMF();
3957
3958 // Avoid setting up the register pressure tracker for small regions to save
3959 // compile time. As a rough heuristic, only track pressure when the number of
3960 // schedulable instructions exceeds half the allocatable integer register file
3961 // that is the largest legal integer regiser type.
3962 RegionPolicy.ShouldTrackPressure = true;
3963 for (unsigned VT = MVT::i64; VT > (unsigned)MVT::i1; --VT) {
3965 if (TLI->isTypeLegal(LegalIntVT)) {
3966 unsigned NIntRegs = Context->RegClassInfo->getNumAllocatableRegs(
3967 TLI->getRegClassFor(LegalIntVT));
3968 RegionPolicy.ShouldTrackPressure = NumRegionInstrs > (NIntRegs / 2);
3969 break;
3970 }
3971 }
3972
3973 // For generic targets, we default to bottom-up, because it's simpler and more
3974 // compile-time optimizations have been implemented in that direction.
3975 RegionPolicy.OnlyBottomUp = true;
3976
3977 // Allow the subtarget to override default policy.
3980
3981 // After subtarget overrides, apply command line options.
3982 const CodeGenOptions &Opts = getCodeGenOptions(MF);
3983 MISched::Direction PreRADirection = Opts.misched_prera_direction;
3984 if (!Opts.misched_regpressure) {
3985 RegionPolicy.ShouldTrackPressure = false;
3986 RegionPolicy.ShouldTrackLaneMasks = false;
3987 }
3988
3989 if (PreRADirection == MISched::TopDown) {
3990 RegionPolicy.OnlyTopDown = true;
3991 RegionPolicy.OnlyBottomUp = false;
3992 } else if (PreRADirection == MISched::BottomUp) {
3993 RegionPolicy.OnlyTopDown = false;
3994 RegionPolicy.OnlyBottomUp = true;
3995 } else if (PreRADirection == MISched::Bidirectional) {
3996 RegionPolicy.OnlyBottomUp = false;
3997 RegionPolicy.OnlyTopDown = false;
3998 }
3999
4000 BotIdx = NumRegionInstrs - 1;
4001 this->NumRegionInstrs = NumRegionInstrs;
4002}
4003
4005 // Cannot completely remove virtual function even in release mode.
4006#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4007 dbgs() << "GenericScheduler RegionPolicy: "
4008 << " ShouldTrackPressure=" << RegionPolicy.ShouldTrackPressure
4009 << " OnlyTopDown=" << RegionPolicy.OnlyTopDown
4010 << " OnlyBottomUp=" << RegionPolicy.OnlyBottomUp
4011 << "\n";
4012#endif
4013}
4014
4015/// Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic
4016/// critical path by more cycles than it takes to drain the instruction buffer.
4017/// We estimate an upper bounds on in-flight instructions as:
4018///
4019/// CyclesPerIteration = max( CyclicPath, Loop-Resource-Height )
4020/// InFlightIterations = AcyclicPath / CyclesPerIteration
4021/// InFlightResources = InFlightIterations * LoopResources
4022///
4023/// TODO: Check execution resources in addition to IssueCount.
4025 if (Rem.CyclicCritPath == 0 || Rem.CyclicCritPath >= Rem.CriticalPath)
4026 return;
4027
4028 // Scaled number of cycles per loop iteration.
4029 unsigned IterCount =
4030 std::max(Rem.CyclicCritPath * SchedModel->getLatencyFactor(),
4031 Rem.RemIssueCount);
4032 // Scaled acyclic critical path.
4033 unsigned AcyclicCount = Rem.CriticalPath * SchedModel->getLatencyFactor();
4034 // InFlightCount = (AcyclicPath / IterCycles) * InstrPerLoop
4035 unsigned InFlightCount =
4036 (AcyclicCount * Rem.RemIssueCount + IterCount-1) / IterCount;
4037 unsigned BufferLimit =
4038 SchedModel->getMicroOpBufferSize() * SchedModel->getMicroOpFactor();
4039
4040 Rem.IsAcyclicLatencyLimited = InFlightCount > BufferLimit;
4041
4042 LLVM_DEBUG(
4043 dbgs() << "IssueCycles="
4044 << Rem.RemIssueCount / SchedModel->getLatencyFactor() << "c "
4045 << "IterCycles=" << IterCount / SchedModel->getLatencyFactor()
4046 << "c NumIters=" << (AcyclicCount + IterCount - 1) / IterCount
4047 << " InFlight=" << InFlightCount / SchedModel->getMicroOpFactor()
4048 << "m BufferLim=" << SchedModel->getMicroOpBufferSize() << "m\n";
4049 if (Rem.IsAcyclicLatencyLimited) dbgs() << " ACYCLIC LATENCY LIMIT\n");
4050}
4051
4053 Rem.CriticalPath = DAG->ExitSU.getDepth();
4054
4055 // Some roots may not feed into ExitSU. Check all of them in case.
4056 for (const SUnit *SU : Bot.Available) {
4057 if (SU->getDepth() > Rem.CriticalPath)
4058 Rem.CriticalPath = SU->getDepth();
4059 }
4060 LLVM_DEBUG(dbgs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << '\n');
4061 if (DAG->Opts.misched_dcpl) {
4062 errs() << "Critical Path(GS-RR ): " << Rem.CriticalPath << " \n";
4063 }
4064
4065 if (DAG->Opts.misched_cyclicpath && SchedModel->getMicroOpBufferSize() > 0) {
4066 Rem.CyclicCritPath = DAG->computeCyclicCriticalPath();
4068 }
4069}
4070
4071bool llvm::tryPressure(const PressureChange &TryP, const PressureChange &CandP,
4075 const TargetRegisterInfo *TRI,
4076 const MachineFunction &MF) {
4077 // If one candidate decreases and the other increases, go with it.
4078 // Invalid candidates have UnitInc==0.
4079 if (tryGreater(TryP.getUnitInc() < 0, CandP.getUnitInc() < 0, TryCand, Cand,
4080 Reason)) {
4081 return true;
4082 }
4083 // Do not compare the magnitude of pressure changes between top and bottom
4084 // boundary.
4085 if (Cand.AtTop != TryCand.AtTop)
4086 return false;
4087
4088 // If both candidates affect the same set in the same boundary, go with the
4089 // smallest increase.
4090 unsigned TryPSet = TryP.getPSetOrMax();
4091 unsigned CandPSet = CandP.getPSetOrMax();
4092 if (TryPSet == CandPSet) {
4093 return tryLess(TryP.getUnitInc(), CandP.getUnitInc(), TryCand, Cand,
4094 Reason);
4095 }
4096
4097 int TryRank = TryP.isValid() ? TRI->getRegPressureSetScore(MF, TryPSet) :
4098 std::numeric_limits<int>::max();
4099
4100 int CandRank = CandP.isValid() ? TRI->getRegPressureSetScore(MF, CandPSet) :
4101 std::numeric_limits<int>::max();
4102
4103 // If the candidates are decreasing pressure, reverse priority.
4104 if (TryP.getUnitInc() < 0)
4105 std::swap(TryRank, CandRank);
4106 return tryGreater(TryRank, CandRank, TryCand, Cand, Reason);
4107}
4108
4109unsigned llvm::getWeakLeft(const SUnit *SU, bool isTop) {
4110 return (isTop) ? SU->WeakPredsLeft : SU->WeakSuccsLeft;
4111}
4112
4113/// Minimize physical register live ranges. Regalloc wants them adjacent to
4114/// their physreg def/use.
4115///
4116/// FIXME: This is an unnecessary check on the critical path. Most are root/leaf
4117/// copies which can be prescheduled. The rest (e.g. x86 MUL) could be bundled
4118/// with the operation that produces or consumes the physreg. We'll do this when
4119/// regalloc has support for parallel copies.
4120int llvm::biasPhysReg(const SUnit *SU, bool isTop, bool BiasPRegsExtra) {
4121 const MachineInstr *MI = SU->getInstr();
4122
4123 if (MI->isCopy()) {
4124 unsigned ScheduledOper = isTop ? 1 : 0;
4125 unsigned UnscheduledOper = isTop ? 0 : 1;
4126 // If we have already scheduled the physreg produce/consumer, immediately
4127 // schedule the copy.
4128 if (MI->getOperand(ScheduledOper).getReg().isPhysical())
4129 return 1;
4130 // If the physreg is at the boundary, defer it. Otherwise schedule it
4131 // immediately to free the dependent. We can hoist the copy later.
4132 bool AtBoundary = isTop ? !SU->NumSuccsLeft : !SU->NumPredsLeft;
4133 if (MI->getOperand(UnscheduledOper).getReg().isPhysical())
4134 return AtBoundary ? -1 : 1;
4135 }
4136
4137 if (MI->isMoveImmediate()) {
4138 // If we have a move immediate and all successors have been assigned, bias
4139 // towards scheduling this later. Make sure all register defs are to
4140 // physical registers.
4141 bool DoBias = true;
4142 for (const MachineOperand &Op : MI->defs()) {
4143 if (Op.isReg() && !Op.getReg().isPhysical()) {
4144 DoBias = false;
4145 break;
4146 }
4147 }
4148
4149 if (DoBias)
4150 return isTop ? -1 : 1;
4151 }
4152
4153 if (BiasPRegsExtra && !isTop && MI->getNumExplicitDefs() == 1)
4154 // Register coalescer will create cases of e.g. Load Address of a frame
4155 // index directly into a physreg.
4156 return MI->getOperand(0).getReg().isPhysical();
4157
4158 return 0;
4159}
4160
4163 SchedBoundary *Zone, bool BiasPRegsExtra) {
4164 int TryCandPRegBias = biasPhysReg(TryCand.SU, TryCand.AtTop, BiasPRegsExtra);
4165 int CandPRegBias = biasPhysReg(Cand.SU, Cand.AtTop, BiasPRegsExtra);
4166 if (tryGreater(TryCandPRegBias, CandPRegBias, TryCand, Cand,
4168 return true;
4169 if (BiasPRegsExtra && Zone != nullptr && TryCandPRegBias &&
4170 TryCandPRegBias == CandPRegBias) {
4171 // Both biased same way - maintain their input order.
4172 if (Zone->isTop())
4173 tryLess(TryCand.SU->NodeNum, Cand.SU->NodeNum, TryCand, Cand,
4175 else
4176 tryGreater(TryCand.SU->NodeNum, Cand.SU->NodeNum, TryCand, Cand,
4178 return true;
4179 }
4180 return false;
4181}
4182
4184 bool AtTop,
4185 const RegPressureTracker &RPTracker,
4186 RegPressureTracker &TempTracker) {
4187 Cand.SU = SU;
4188 Cand.AtTop = AtTop;
4189 if (DAG->isTrackingPressure()) {
4190 if (AtTop) {
4191 TempTracker.getMaxDownwardPressureDelta(
4192 Cand.SU->getInstr(),
4193 Cand.RPDelta,
4194 DAG->getRegionCriticalPSets(),
4195 DAG->getRegPressure().MaxSetPressure);
4196 } else {
4197 if (DAG->Opts.verify_misched) {
4198 TempTracker.getMaxUpwardPressureDelta(
4199 Cand.SU->getInstr(),
4200 &DAG->getPressureDiff(Cand.SU),
4201 Cand.RPDelta,
4202 DAG->getRegionCriticalPSets(),
4203 DAG->getRegPressure().MaxSetPressure);
4204 } else {
4205 RPTracker.getUpwardPressureDelta(
4206 Cand.SU->getInstr(),
4207 DAG->getPressureDiff(Cand.SU),
4208 Cand.RPDelta,
4209 DAG->getRegionCriticalPSets(),
4210 DAG->getRegPressure().MaxSetPressure);
4211 }
4212 }
4213 }
4214 LLVM_DEBUG(if (Cand.RPDelta.Excess.isValid()) dbgs()
4215 << " Try " << *Cand.SU << " "
4216 << TRI->getRegPressureSetName(Cand.RPDelta.Excess.getPSet()) << ":"
4217 << Cand.RPDelta.Excess.getUnitInc() << "\n");
4218}
4219
4220/// Apply a set of heuristics to a new candidate. Heuristics are currently
4221/// hierarchical. This may be more efficient than a graduated cost model because
4222/// we don't need to evaluate all aspects of the model for each node in the
4223/// queue. But it's really done to make the heuristics easier to debug and
4224/// statistically analyze.
4225///
4226/// \param Cand provides the policy and current best candidate.
4227/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
4228/// \param Zone describes the scheduled zone that we are extending, or nullptr
4229/// if Cand is from a different zone than TryCand.
4230/// \return \c true if TryCand is better than Cand (Reason is NOT NoCand)
4232 SchedCandidate &TryCand,
4233 SchedBoundary *Zone) const {
4234 // Initialize the candidate if needed.
4235 if (!Cand.isValid()) {
4236 TryCand.Reason = FirstValid;
4237 return true;
4238 }
4239
4240 // Bias PhysReg Defs and copies to their uses and defined respectively.
4241 if (tryBiasPhysRegs(TryCand, Cand, Zone, RegionPolicy.BiasPRegsExtra))
4242 return TryCand.Reason != NoCand;
4243
4244 // Avoid exceeding the target's limit.
4245 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.Excess,
4246 Cand.RPDelta.Excess,
4247 TryCand, Cand, RegExcess, TRI,
4248 DAG->MF))
4249 return TryCand.Reason != NoCand;
4250
4251 // Avoid increasing the max critical pressure in the scheduled region.
4252 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CriticalMax,
4253 Cand.RPDelta.CriticalMax,
4254 TryCand, Cand, RegCritical, TRI,
4255 DAG->MF))
4256 return TryCand.Reason != NoCand;
4257
4258 // We only compare a subset of features when comparing nodes between
4259 // Top and Bottom boundary. Some properties are simply incomparable, in many
4260 // other instances we should only override the other boundary if something
4261 // is a clear good pick on one boundary. Skip heuristics that are more
4262 // "tie-breaking" in nature.
4263 bool SameBoundary = Zone != nullptr;
4264 if (SameBoundary) {
4265 // For loops that are acyclic path limited, aggressively schedule for
4266 // latency. Within an single cycle, whenever CurrMOps > 0, allow normal
4267 // heuristics to take precedence.
4268 if (Rem.IsAcyclicLatencyLimited && !Zone->getCurrMOps() &&
4269 tryLatency(TryCand, Cand, *Zone))
4270 return TryCand.Reason != NoCand;
4271
4272 // Prioritize instructions that read unbuffered resources by stall cycles.
4273 if (tryLess(Zone->getLatencyStallCycles(TryCand.SU),
4274 Zone->getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
4275 return TryCand.Reason != NoCand;
4276 }
4277
4278 // Keep clustered nodes together to encourage downstream peephole
4279 // optimizations which may reduce resource requirements.
4280 //
4281 // This is a best effort to set things up for a post-RA pass. Optimizations
4282 // like generating loads of multiple registers should ideally be done within
4283 // the scheduler pass by combining the loads during DAG postprocessing.
4284 unsigned CandZoneCluster = Cand.AtTop ? TopClusterID : BotClusterID;
4285 unsigned TryCandZoneCluster = TryCand.AtTop ? TopClusterID : BotClusterID;
4286 bool CandIsClusterSucc =
4287 isTheSameCluster(CandZoneCluster, Cand.SU->ParentClusterIdx);
4288 bool TryCandIsClusterSucc =
4289 isTheSameCluster(TryCandZoneCluster, TryCand.SU->ParentClusterIdx);
4290
4291 if (tryGreater(TryCandIsClusterSucc, CandIsClusterSucc, TryCand, Cand,
4292 Cluster))
4293 return TryCand.Reason != NoCand;
4294
4295 if (SameBoundary) {
4296 // Weak edges are for clustering and other constraints.
4297 if (tryLess(getWeakLeft(TryCand.SU, TryCand.AtTop),
4298 getWeakLeft(Cand.SU, Cand.AtTop),
4299 TryCand, Cand, Weak))
4300 return TryCand.Reason != NoCand;
4301 }
4302
4303 // Avoid increasing the max pressure of the entire region.
4304 if (DAG->isTrackingPressure() && tryPressure(TryCand.RPDelta.CurrentMax,
4305 Cand.RPDelta.CurrentMax,
4306 TryCand, Cand, RegMax, TRI,
4307 DAG->MF))
4308 return TryCand.Reason != NoCand;
4309
4310 if (SameBoundary) {
4311 // Avoid critical resource consumption and balance the schedule.
4314 TryCand, Cand, ResourceReduce))
4315 return TryCand.Reason != NoCand;
4318 TryCand, Cand, ResourceDemand))
4319 return TryCand.Reason != NoCand;
4320
4321 // Avoid serializing long latency dependence chains.
4322 // For acyclic path limited loops, latency was already checked above.
4323 if (!RegionPolicy.DisableLatencyHeuristic && TryCand.Policy.ReduceLatency &&
4324 !Rem.IsAcyclicLatencyLimited && tryLatency(TryCand, Cand, *Zone))
4325 return TryCand.Reason != NoCand;
4326
4327 // Fall through to original instruction order.
4328 if ((Zone->isTop() && TryCand.SU->NodeNum < Cand.SU->NodeNum)
4329 || (!Zone->isTop() && TryCand.SU->NodeNum > Cand.SU->NodeNum)) {
4330 TryCand.Reason = NodeOrder;
4331 return true;
4332 }
4333 }
4334
4335 return false;
4336}
4337
4338/// Pick the best candidate from the queue.
4339///
4340/// TODO: getMaxPressureDelta results can be mostly cached for each SUnit during
4341/// DAG building. To adjust for the current scheduling location we need to
4342/// maintain the number of vreg uses remaining to be top-scheduled.
4344 const CandPolicy &ZonePolicy,
4345 const RegPressureTracker &RPTracker,
4346 SchedCandidate &Cand) {
4347 // getMaxPressureDelta temporarily modifies the tracker.
4348 RegPressureTracker &TempTracker = const_cast<RegPressureTracker&>(RPTracker);
4349
4350 ReadyQueue &Q = Zone.Available;
4351 for (SUnit *SU : Q) {
4352
4353 SchedCandidate TryCand(ZonePolicy);
4354 initCandidate(TryCand, SU, Zone.isTop(), RPTracker, TempTracker);
4355 // Pass SchedBoundary only when comparing nodes from the same boundary.
4356 SchedBoundary *ZoneArg = Cand.AtTop == TryCand.AtTop ? &Zone : nullptr;
4357 if (tryCandidate(Cand, TryCand, ZoneArg)) {
4358 // Initialize resource delta if needed in case future heuristics query it.
4359 if (TryCand.ResDelta == SchedResourceDelta())
4361 Cand.setBest(TryCand);
4363 }
4364 }
4365}
4366
4367/// Pick the best candidate node from either the top or bottom queue.
4369 // Schedule as far as possible in the direction of no choice. This is most
4370 // efficient, but also provides the best heuristics for CriticalPSets.
4371 if (SUnit *SU = Bot.pickOnlyChoice()) {
4372 IsTopNode = false;
4373 tracePick(SU, Only1, /*IsTopNode=*/false);
4374 return SU;
4375 }
4376 if (SUnit *SU = Top.pickOnlyChoice()) {
4377 IsTopNode = true;
4378 tracePick(SU, Only1, /*IsTopNode=*/true);
4379 return SU;
4380 }
4381 // Set the bottom-up policy based on the state of the current bottom zone and
4382 // the instructions outside the zone, including the top zone.
4383 CandPolicy BotPolicy;
4384 setPolicy(BotPolicy, /*IsPostRA=*/false, Bot, &Top);
4385 // Set the top-down policy based on the state of the current top zone and
4386 // the instructions outside the zone, including the bottom zone.
4387 CandPolicy TopPolicy;
4388 setPolicy(TopPolicy, /*IsPostRA=*/false, Top, &Bot);
4389
4390 // See if BotCand is still valid (because we previously scheduled from Top).
4391 LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
4392 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
4393 BotCand.Policy != BotPolicy) {
4394 BotCand.reset(CandPolicy());
4395 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), BotCand);
4396 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
4397 } else {
4399#ifndef NDEBUG
4400 if (DAG->Opts.verify_misched) {
4401 SchedCandidate TCand;
4402 TCand.reset(CandPolicy());
4403 pickNodeFromQueue(Bot, BotPolicy, DAG->getBotRPTracker(), TCand);
4404 assert(TCand.SU == BotCand.SU &&
4405 "Last pick result should correspond to re-picking right now");
4406 }
4407#endif
4408 }
4409
4410 // Check if the top Q has a better candidate.
4411 LLVM_DEBUG(dbgs() << "Picking from Top:\n");
4412 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
4413 TopCand.Policy != TopPolicy) {
4414 TopCand.reset(CandPolicy());
4415 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TopCand);
4416 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
4417 } else {
4419#ifndef NDEBUG
4420 if (DAG->Opts.verify_misched) {
4421 SchedCandidate TCand;
4422 TCand.reset(CandPolicy());
4423 pickNodeFromQueue(Top, TopPolicy, DAG->getTopRPTracker(), TCand);
4424 assert(TCand.SU == TopCand.SU &&
4425 "Last pick result should correspond to re-picking right now");
4426 }
4427#endif
4428 }
4429
4430 // Pick best from BotCand and TopCand.
4431 assert(BotCand.isValid());
4432 assert(TopCand.isValid());
4433 SchedCandidate Cand = BotCand;
4434 TopCand.Reason = NoCand;
4435 if (tryCandidate(Cand, TopCand, nullptr)) {
4436 Cand.setBest(TopCand);
4438 }
4439
4440 IsTopNode = Cand.AtTop;
4441 tracePick(Cand);
4442 return Cand.SU;
4443}
4444
4445/// Pick the best node to balance the schedule. Implements MachineSchedStrategy.
4447 if (DAG->top() == DAG->bottom()) {
4448 assert(Top.Available.empty() && Top.Pending.empty() &&
4449 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
4450 return nullptr;
4451 }
4452 SUnit *SU;
4453 if (RegionPolicy.OnlyTopDown) {
4454 SU = Top.pickOnlyChoice();
4455 if (SU) {
4456 tracePick(SU, Only1, /*IsTopNode=*/true);
4457 } else {
4458 CandPolicy NoPolicy;
4459 TopCand.reset(NoPolicy);
4460 pickNodeFromQueue(Top, NoPolicy, DAG->getTopRPTracker(), TopCand);
4461 assert(TopCand.Reason != NoCand && "failed to find a candidate");
4463 SU = TopCand.SU;
4464 }
4465 IsTopNode = true;
4466 } else if (RegionPolicy.OnlyBottomUp) {
4467 SU = Bot.pickOnlyChoice();
4468 if (SU) {
4469 tracePick(SU, Only1, /*IsTopNode=*/false);
4470 } else {
4471 CandPolicy NoPolicy;
4472 BotCand.reset(NoPolicy);
4473 pickNodeFromQueue(Bot, NoPolicy, DAG->getBotRPTracker(), BotCand);
4474 assert(BotCand.Reason != NoCand && "failed to find a candidate");
4476 SU = BotCand.SU;
4477 }
4478 IsTopNode = false;
4479 } else {
4480 SU = pickNodeBidirectional(IsTopNode);
4481 }
4482 assert(!SU->isScheduled && "SUnit scheduled twice.");
4483
4484 // If IsTopNode, then SU is in Top.Available and must be removed. Otherwise,
4485 // if isTopReady(), then SU is in either Top.Available or Top.Pending.
4486 // If !IsTopNode, then SU is in Bot.Available and must be removed. Otherwise,
4487 // if isBottomReady(), then SU is in either Bot.Available or Bot.Pending.
4488 //
4489 // It is coincidental when !IsTopNode && isTopReady or when IsTopNode &&
4490 // isBottomReady. That is, it didn't factor into the decision to choose SU
4491 // because it isTopReady or isBottomReady, respectively. In fact, if the
4492 // RegionPolicy is OnlyTopDown or OnlyBottomUp, then the Bot queues and Top
4493 // queues respectivley contain the original roots and don't get updated when
4494 // picking a node. So if SU isTopReady on a OnlyBottomUp pick, then it was
4495 // because we schduled everything but the top roots. Conversley, if SU
4496 // isBottomReady on OnlyTopDown, then it was because we scheduled everything
4497 // but the bottom roots. If its in a queue even coincidentally, it should be
4498 // removed so it does not get re-picked in a subsequent pickNode call.
4499 if (SU->isTopReady())
4500 Top.removeReady(SU);
4501 if (SU->isBottomReady())
4502 Bot.removeReady(SU);
4503
4504 LLVM_DEBUG(dbgs() << "Scheduling " << *SU << " " << *SU->getInstr());
4505
4506 if (IsTopNode) {
4507 if (SU->NodeNum == TopIdx++)
4508 ++NumInstrsInSourceOrderPreRA;
4509 } else {
4510 assert(BotIdx < NumRegionInstrs && "out of bounds");
4511 if (SU->NodeNum == BotIdx--)
4512 ++NumInstrsInSourceOrderPreRA;
4513 }
4514
4515 NumInstrsScheduledPreRA += 1;
4516
4517 return SU;
4518}
4519
4521 MachineBasicBlock::iterator InsertPos = SU->getInstr();
4522 if (!isTop)
4523 ++InsertPos;
4524 SmallVectorImpl<SDep> &Deps = isTop ? SU->Preds : SU->Succs;
4525
4526 // Find already scheduled copies with a single physreg dependence and move
4527 // them just above the scheduled instruction.
4528 for (SDep &Dep : Deps) {
4529 if (Dep.getKind() != SDep::Data || !Dep.getReg().isPhysical())
4530 continue;
4531 SUnit *DepSU = Dep.getSUnit();
4532 if (isTop ? DepSU->Succs.size() > 1 : DepSU->Preds.size() > 1)
4533 continue;
4534 MachineInstr *Copy = DepSU->getInstr();
4535 if (!Copy->isCopy() && !Copy->isMoveImmediate())
4536 continue;
4537 LLVM_DEBUG(dbgs() << " Rescheduling physreg copy ";
4538 DAG->dumpNode(*Dep.getSUnit()));
4539 // Moving a copy past subregister defs can leave stale read-undef flags,
4540 // dropping true dependencies in a later DAG build. Recompute them from
4541 // LiveIntervals after the move. Only vreg copies need this, and only when
4542 // lane masks are tracked.
4543 LiveIntervals *LIS = DAG->getLIS();
4544 SmallVector<Register, 8> CopyVRegs;
4545 if (LIS && DAG->hasVRegLiveness() && shouldTrackLaneMasks())
4546 for (const MachineOperand &MO : Copy->operands())
4547 if (MO.isReg() && MO.getReg().isVirtual())
4548 CopyVRegs.push_back(MO.getReg());
4549 bool FixUndef = !CopyVRegs.empty();
4550
4551 // Remember the old location to limit the fixup below to the range moved.
4552 SlotIndex OldIdx;
4554 if (FixUndef) {
4555 OldIdx = LIS->getInstructionIndex(*Copy);
4556 OldNext = std::next(Copy->getIterator());
4557 }
4558
4559 DAG->moveInstruction(Copy, InsertPos);
4560 if (!FixUndef)
4561 continue;
4562
4563 // Fix up the copy itself and everything it moved past.
4565 /*TrackLaneMasks=*/true, CopyVRegs);
4566 MachineBasicBlock::iterator NewIt = Copy->getIterator();
4567 SlotIndex NewIdx = LIS->getInstructionIndex(*Copy);
4568 MachineBasicBlock::iterator FixBegin = NewIt, FixEnd = NewIt;
4569 if (NewIdx < OldIdx) {
4570 FixBegin = std::next(NewIt);
4571 FixEnd = OldNext;
4572 } else if (OldIdx < NewIdx) {
4573 FixBegin = OldNext;
4574 FixEnd = NewIt;
4575 }
4576 for (auto I = FixBegin; I != FixEnd; ++I)
4577 if (!I->isDebugInstr())
4579 /*TrackLaneMasks=*/true,
4580 CopyVRegs);
4581 }
4582}
4583
4584/// Update the scheduler's state after scheduling a node. This is the same node
4585/// that was just returned by pickNode(). However, ScheduleDAGMILive needs to
4586/// update it's state based on the current cycle before MachineSchedStrategy
4587/// does.
4588///
4589/// FIXME: Eventually, we may bundle physreg copies rather than rescheduling
4590/// them here. See comments in biasPhysReg.
4591void GenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
4592 if (IsTopNode) {
4593 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
4595 LLVM_DEBUG({
4597 ClusterInfo *TopCluster = DAG->getCluster(TopClusterID);
4598 dbgs() << " Top Cluster: ";
4599 for (auto *N : *TopCluster) {
4600 DAG->dumpNodeName(*N);
4601 dbgs() << '\t';
4602 }
4603 dbgs() << '\n';
4604 }
4605 });
4606 Top.bumpNode(SU);
4607 if (SU->hasPhysRegUses)
4608 reschedulePhysReg(SU, true);
4609 } else {
4610 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
4612 LLVM_DEBUG({
4614 ClusterInfo *BotCluster = DAG->getCluster(BotClusterID);
4615 dbgs() << " Bot Cluster: ";
4616 for (auto *N : *BotCluster) {
4617 DAG->dumpNodeName(*N);
4618 dbgs() << '\t';
4619 }
4620 dbgs() << '\n';
4621 }
4622 });
4623 Bot.bumpNode(SU);
4624 if (SU->hasPhysRegDefs)
4625 reschedulePhysReg(SU, false);
4626 }
4627}
4628
4632
4633static MachineSchedRegistry
4634GenericSchedRegistry("converge", "Standard converging scheduler.",
4636
4637//===----------------------------------------------------------------------===//
4638// PostGenericScheduler - Generic PostRA implementation of MachineSchedStrategy.
4639//===----------------------------------------------------------------------===//
4640
4642 DAG = Dag;
4643 SchedModel = DAG->getSchedModel();
4644 TRI = DAG->TRI;
4645
4646 Rem.init(DAG, SchedModel);
4647 Top.init(DAG, SchedModel, &Rem);
4648 Bot.init(DAG, SchedModel, &Rem);
4649
4650 // Initialize the HazardRecognizers. If itineraries don't exist, are empty,
4651 // or are disabled, then these HazardRecs will be disabled.
4652 const InstrItineraryData *Itin = SchedModel->getInstrItineraries();
4653 if (!Top.HazardRec)
4654 Top.HazardRec.reset(DAG->TII->CreateTargetMIHazardRecognizer(Itin, DAG));
4655 if (!Bot.HazardRec)
4656 Bot.HazardRec.reset(DAG->TII->CreateTargetMIHazardRecognizer(Itin, DAG));
4659}
4660
4663 unsigned NumRegionInstrs) {
4664 const MachineFunction &MF = *Begin->getMF();
4665
4666 // Default to top-down because it was implemented first and existing targets
4667 // expect that behavior by default.
4668 RegionPolicy.OnlyTopDown = true;
4669 RegionPolicy.OnlyBottomUp = false;
4670
4671 // Allow the subtarget to override default policy.
4674
4675 // After subtarget overrides, apply command line options.
4676 MISched::Direction PostRADirection =
4677 getCodeGenOptions(MF).misched_postra_direction;
4678 if (PostRADirection == MISched::TopDown) {
4679 RegionPolicy.OnlyTopDown = true;
4680 RegionPolicy.OnlyBottomUp = false;
4681 } else if (PostRADirection == MISched::BottomUp) {
4682 RegionPolicy.OnlyTopDown = false;
4683 RegionPolicy.OnlyBottomUp = true;
4684 } else if (PostRADirection == MISched::Bidirectional) {
4685 RegionPolicy.OnlyBottomUp = false;
4686 RegionPolicy.OnlyTopDown = false;
4687 }
4688
4689 BotIdx = NumRegionInstrs - 1;
4690 this->NumRegionInstrs = NumRegionInstrs;
4691}
4692
4694 Rem.CriticalPath = DAG->ExitSU.getDepth();
4695
4696 // Some roots may not feed into ExitSU. Check all of them in case.
4697 for (const SUnit *SU : Bot.Available) {
4698 if (SU->getDepth() > Rem.CriticalPath)
4699 Rem.CriticalPath = SU->getDepth();
4700 }
4701 LLVM_DEBUG(dbgs() << "Critical Path: (PGS-RR) " << Rem.CriticalPath << '\n');
4702 if (DAG->Opts.misched_dcpl) {
4703 errs() << "Critical Path(PGS-RR ): " << Rem.CriticalPath << " \n";
4704 }
4705}
4706
4707/// Apply a set of heuristics to a new candidate for PostRA scheduling.
4708///
4709/// \param Cand provides the policy and current best candidate.
4710/// \param TryCand refers to the next SUnit candidate, otherwise uninitialized.
4711/// \return \c true if TryCand is better than Cand (Reason is NOT NoCand)
4713 SchedCandidate &TryCand) {
4714 // Initialize the candidate if needed.
4715 if (!Cand.isValid()) {
4716 TryCand.Reason = FirstValid;
4717 return true;
4718 }
4719
4720 // Prioritize instructions that read unbuffered resources by stall cycles.
4721 if (tryLess(Top.getLatencyStallCycles(TryCand.SU),
4722 Top.getLatencyStallCycles(Cand.SU), TryCand, Cand, Stall))
4723 return TryCand.Reason != NoCand;
4724
4725 // Keep clustered nodes together.
4726 unsigned CandZoneCluster = Cand.AtTop ? TopClusterID : BotClusterID;
4727 unsigned TryCandZoneCluster = TryCand.AtTop ? TopClusterID : BotClusterID;
4728 bool CandIsClusterSucc =
4729 isTheSameCluster(CandZoneCluster, Cand.SU->ParentClusterIdx);
4730 bool TryCandIsClusterSucc =
4731 isTheSameCluster(TryCandZoneCluster, TryCand.SU->ParentClusterIdx);
4732
4733 if (tryGreater(TryCandIsClusterSucc, CandIsClusterSucc, TryCand, Cand,
4734 Cluster))
4735 return TryCand.Reason != NoCand;
4736 // Avoid critical resource consumption and balance the schedule.
4738 TryCand, Cand, ResourceReduce))
4739 return TryCand.Reason != NoCand;
4742 TryCand, Cand, ResourceDemand))
4743 return TryCand.Reason != NoCand;
4744
4745 // We only compare a subset of features when comparing nodes between
4746 // Top and Bottom boundary.
4747 if (Cand.AtTop == TryCand.AtTop) {
4748 // Avoid serializing long latency dependence chains.
4749 if (Cand.Policy.ReduceLatency &&
4750 tryLatency(TryCand, Cand, Cand.AtTop ? Top : Bot))
4751 return TryCand.Reason != NoCand;
4752 }
4753
4754 // Fall through to original instruction order.
4755 if (TryCand.SU->NodeNum < Cand.SU->NodeNum) {
4756 TryCand.Reason = NodeOrder;
4757 return true;
4758 }
4759
4760 return false;
4761}
4762
4764 SchedCandidate &Cand) {
4765 ReadyQueue &Q = Zone.Available;
4766 for (SUnit *SU : Q) {
4767 SchedCandidate TryCand(Cand.Policy);
4768 TryCand.SU = SU;
4769 TryCand.AtTop = Zone.isTop();
4771 if (tryCandidate(Cand, TryCand)) {
4772 Cand.setBest(TryCand);
4774 }
4775 }
4776}
4777
4778/// Pick the best candidate node from either the top or bottom queue.
4780 // FIXME: This is similiar to GenericScheduler::pickNodeBidirectional. Factor
4781 // out common parts.
4782
4783 // Schedule as far as possible in the direction of no choice. This is most
4784 // efficient, but also provides the best heuristics for CriticalPSets.
4785 if (SUnit *SU = Bot.pickOnlyChoice()) {
4786 IsTopNode = false;
4787 tracePick(SU, Only1, /*IsTopNode=*/false, /*IsPostRA=*/true);
4788 return SU;
4789 }
4790 if (SUnit *SU = Top.pickOnlyChoice()) {
4791 IsTopNode = true;
4792 tracePick(SU, Only1, /*IsTopNode=*/true, /*IsPostRA=*/true);
4793 return SU;
4794 }
4795 // Set the bottom-up policy based on the state of the current bottom zone and
4796 // the instructions outside the zone, including the top zone.
4797 CandPolicy BotPolicy;
4798 setPolicy(BotPolicy, /*IsPostRA=*/true, Bot, &Top);
4799 // Set the top-down policy based on the state of the current top zone and
4800 // the instructions outside the zone, including the bottom zone.
4801 CandPolicy TopPolicy;
4802 setPolicy(TopPolicy, /*IsPostRA=*/true, Top, &Bot);
4803
4804 // See if BotCand is still valid (because we previously scheduled from Top).
4805 LLVM_DEBUG(dbgs() << "Picking from Bot:\n");
4806 if (!BotCand.isValid() || BotCand.SU->isScheduled ||
4807 BotCand.Policy != BotPolicy) {
4808 BotCand.reset(CandPolicy());
4810 assert(BotCand.Reason != NoCand && "failed to find the first candidate");
4811 } else {
4813#ifndef NDEBUG
4814 if (DAG->Opts.verify_misched) {
4815 SchedCandidate TCand;
4816 TCand.reset(CandPolicy());
4818 assert(TCand.SU == BotCand.SU &&
4819 "Last pick result should correspond to re-picking right now");
4820 }
4821#endif
4822 }
4823
4824 // Check if the top Q has a better candidate.
4825 LLVM_DEBUG(dbgs() << "Picking from Top:\n");
4826 if (!TopCand.isValid() || TopCand.SU->isScheduled ||
4827 TopCand.Policy != TopPolicy) {
4828 TopCand.reset(CandPolicy());
4830 assert(TopCand.Reason != NoCand && "failed to find the first candidate");
4831 } else {
4833#ifndef NDEBUG
4834 if (DAG->Opts.verify_misched) {
4835 SchedCandidate TCand;
4836 TCand.reset(CandPolicy());
4838 assert(TCand.SU == TopCand.SU &&
4839 "Last pick result should correspond to re-picking right now");
4840 }
4841#endif
4842 }
4843
4844 // Pick best from BotCand and TopCand.
4845 assert(BotCand.isValid());
4846 assert(TopCand.isValid());
4847 SchedCandidate Cand = BotCand;
4848 TopCand.Reason = NoCand;
4849 if (tryCandidate(Cand, TopCand)) {
4850 Cand.setBest(TopCand);
4852 }
4853
4854 IsTopNode = Cand.AtTop;
4855 tracePick(Cand, /*IsPostRA=*/true);
4856 return Cand.SU;
4857}
4858
4859/// Pick the next node to schedule.
4861 if (DAG->top() == DAG->bottom()) {
4862 assert(Top.Available.empty() && Top.Pending.empty() &&
4863 Bot.Available.empty() && Bot.Pending.empty() && "ReadyQ garbage");
4864 return nullptr;
4865 }
4866 SUnit *SU;
4867 if (RegionPolicy.OnlyBottomUp) {
4868 SU = Bot.pickOnlyChoice();
4869 if (SU) {
4870 tracePick(SU, Only1, /*IsTopNode=*/false, /*IsPostRA=*/true);
4871 } else {
4872 CandPolicy NoPolicy;
4873 BotCand.reset(NoPolicy);
4874 // Set the bottom-up policy based on the state of the current bottom
4875 // zone and the instructions outside the zone, including the top zone.
4876 setPolicy(BotCand.Policy, /*IsPostRA=*/true, Bot, nullptr);
4878 assert(BotCand.Reason != NoCand && "failed to find a candidate");
4879 tracePick(BotCand, /*IsPostRA=*/true);
4880 SU = BotCand.SU;
4881 }
4882 IsTopNode = false;
4883 } else if (RegionPolicy.OnlyTopDown) {
4884 SU = Top.pickOnlyChoice();
4885 if (SU) {
4886 tracePick(SU, Only1, /*IsTopNode=*/true, /*IsPostRA=*/true);
4887 } else {
4888 CandPolicy NoPolicy;
4889 TopCand.reset(NoPolicy);
4890 // Set the top-down policy based on the state of the current top zone
4891 // and the instructions outside the zone, including the bottom zone.
4892 setPolicy(TopCand.Policy, /*IsPostRA=*/true, Top, nullptr);
4894 assert(TopCand.Reason != NoCand && "failed to find a candidate");
4895 tracePick(TopCand, /*IsPostRA=*/true);
4896 SU = TopCand.SU;
4897 }
4898 IsTopNode = true;
4899 } else {
4900 SU = pickNodeBidirectional(IsTopNode);
4901 }
4902 assert(!SU->isScheduled && "SUnit scheduled twice.");
4903
4904 if (SU->isTopReady())
4905 Top.removeReady(SU);
4906 if (SU->isBottomReady())
4907 Bot.removeReady(SU);
4908
4909 LLVM_DEBUG(dbgs() << "Scheduling " << *SU << " " << *SU->getInstr());
4910
4911 if (IsTopNode) {
4912 if (SU->NodeNum == TopIdx++)
4913 ++NumInstrsInSourceOrderPostRA;
4914 } else {
4915 assert(BotIdx < NumRegionInstrs && "out of bounds");
4916 if (SU->NodeNum == BotIdx--)
4917 ++NumInstrsInSourceOrderPostRA;
4918 }
4919
4920 NumInstrsScheduledPostRA += 1;
4921
4922 return SU;
4923}
4924
4925/// Called after ScheduleDAGMI has scheduled an instruction and updated
4926/// scheduled/remaining flags in the DAG nodes.
4927void PostGenericScheduler::schedNode(SUnit *SU, bool IsTopNode) {
4928 if (IsTopNode) {
4929 SU->TopReadyCycle = std::max(SU->TopReadyCycle, Top.getCurrCycle());
4931 Top.bumpNode(SU);
4932 } else {
4933 SU->BotReadyCycle = std::max(SU->BotReadyCycle, Bot.getCurrCycle());
4935 Bot.bumpNode(SU);
4936 }
4937}
4938
4939//===----------------------------------------------------------------------===//
4940// ILP Scheduler. Currently for experimental analysis of heuristics.
4941//===----------------------------------------------------------------------===//
4942
4943namespace {
4944
4945/// Order nodes by the ILP metric.
4946struct ILPOrder {
4947 const SchedDFSResult *DFSResult = nullptr;
4948 const BitVector *ScheduledTrees = nullptr;
4949 bool MaximizeILP;
4950
4951 ILPOrder(bool MaxILP) : MaximizeILP(MaxILP) {}
4952
4953 /// Apply a less-than relation on node priority.
4954 ///
4955 /// (Return true if A comes after B in the Q.)
4956 bool operator()(const SUnit *A, const SUnit *B) const {
4957 unsigned SchedTreeA = DFSResult->getSubtreeID(A);
4958 unsigned SchedTreeB = DFSResult->getSubtreeID(B);
4959 if (SchedTreeA != SchedTreeB) {
4960 // Unscheduled trees have lower priority.
4961 if (ScheduledTrees->test(SchedTreeA) != ScheduledTrees->test(SchedTreeB))
4962 return ScheduledTrees->test(SchedTreeB);
4963
4964 // Trees with shallower connections have lower priority.
4965 if (DFSResult->getSubtreeLevel(SchedTreeA)
4966 != DFSResult->getSubtreeLevel(SchedTreeB)) {
4967 return DFSResult->getSubtreeLevel(SchedTreeA)
4968 < DFSResult->getSubtreeLevel(SchedTreeB);
4969 }
4970 }
4971 if (MaximizeILP)
4972 return DFSResult->getILP(A) < DFSResult->getILP(B);
4973 else
4974 return DFSResult->getILP(A) > DFSResult->getILP(B);
4975 }
4976};
4977
4978/// Schedule based on the ILP metric.
4979class ILPScheduler : public MachineSchedStrategy {
4980 ScheduleDAGMILive *DAG = nullptr;
4981 ILPOrder Cmp;
4982
4983 std::vector<SUnit*> ReadyQ;
4984
4985public:
4986 ILPScheduler(bool MaximizeILP) : Cmp(MaximizeILP) {}
4987
4988 void initialize(ScheduleDAGMI *dag) override {
4989 assert(dag->hasVRegLiveness() && "ILPScheduler needs vreg liveness");
4990 DAG = static_cast<ScheduleDAGMILive*>(dag);
4991 DAG->computeDFSResult();
4992 Cmp.DFSResult = DAG->getDFSResult();
4993 Cmp.ScheduledTrees = &DAG->getScheduledTrees();
4994 ReadyQ.clear();
4995 }
4996
4997 void registerRoots() override {
4998 // Restore the heap in ReadyQ with the updated DFS results.
4999 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
5000 }
5001
5002 /// Implement MachineSchedStrategy interface.
5003 /// -----------------------------------------
5004
5005 /// Callback to select the highest priority node from the ready Q.
5006 SUnit *pickNode(bool &IsTopNode) override {
5007 if (ReadyQ.empty()) return nullptr;
5008 std::pop_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
5009 SUnit *SU = ReadyQ.back();
5010 ReadyQ.pop_back();
5011 IsTopNode = false;
5012 LLVM_DEBUG(dbgs() << "Pick node " << *SU << " "
5013 << " ILP: " << DAG->getDFSResult()->getILP(SU)
5014 << " Tree: " << DAG->getDFSResult()->getSubtreeID(SU)
5015 << " @"
5016 << DAG->getDFSResult()->getSubtreeLevel(
5017 DAG->getDFSResult()->getSubtreeID(SU))
5018 << '\n'
5019 << "Scheduling " << *SU->getInstr());
5020 return SU;
5021 }
5022
5023 /// Scheduler callback to notify that a new subtree is scheduled.
5024 void scheduleTree(unsigned SubtreeID) override {
5025 std::make_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
5026 }
5027
5028 /// Callback after a node is scheduled. Mark a newly scheduled tree, notify
5029 /// DFSResults, and resort the priority Q.
5030 void schedNode(SUnit *SU, bool IsTopNode) override {
5031 assert(!IsTopNode && "SchedDFSResult needs bottom-up");
5032 }
5033
5034 void releaseTopNode(SUnit *) override { /*only called for top roots*/ }
5035
5036 void releaseBottomNode(SUnit *SU) override {
5037 ReadyQ.push_back(SU);
5038 std::push_heap(ReadyQ.begin(), ReadyQ.end(), Cmp);
5039 }
5040};
5041
5042} // end anonymous namespace
5043
5045 return new ScheduleDAGMILive(C, std::make_unique<ILPScheduler>(true));
5046}
5048 return new ScheduleDAGMILive(C, std::make_unique<ILPScheduler>(false));
5049}
5050
5052 "ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler);
5054 "ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler);
5055
5056//===----------------------------------------------------------------------===//
5057// Machine Instruction Shuffler for Correctness Testing
5058//===----------------------------------------------------------------------===//
5059
5060#ifndef NDEBUG
5061namespace {
5062
5063/// Apply a less-than relation on the node order, which corresponds to the
5064/// instruction order prior to scheduling. IsReverse implements greater-than.
5065template<bool IsReverse>
5066struct SUnitOrder {
5067 bool operator()(SUnit *A, SUnit *B) const {
5068 if (IsReverse)
5069 return A->NodeNum > B->NodeNum;
5070 else
5071 return A->NodeNum < B->NodeNum;
5072 }
5073};
5074
5075/// Reorder instructions as much as possible.
5076class InstructionShuffler : public MachineSchedStrategy {
5077 bool IsAlternating;
5078 bool IsTopDown;
5079
5080 // Using a less-than relation (SUnitOrder<false>) for the TopQ priority
5081 // gives nodes with a higher number higher priority causing the latest
5082 // instructions to be scheduled first.
5083 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<false>>
5084 TopQ;
5085
5086 // When scheduling bottom-up, use greater-than as the queue priority.
5087 PriorityQueue<SUnit*, std::vector<SUnit*>, SUnitOrder<true>>
5088 BottomQ;
5089
5090public:
5091 InstructionShuffler(bool alternate, bool topdown)
5092 : IsAlternating(alternate), IsTopDown(topdown) {}
5093
5094 void initialize(ScheduleDAGMI*) override {
5095 TopQ.clear();
5096 BottomQ.clear();
5097 }
5098
5099 /// Implement MachineSchedStrategy interface.
5100 /// -----------------------------------------
5101
5102 SUnit *pickNode(bool &IsTopNode) override {
5103 SUnit *SU;
5104 if (IsTopDown) {
5105 do {
5106 if (TopQ.empty()) return nullptr;
5107 SU = TopQ.top();
5108 TopQ.pop();
5109 } while (SU->isScheduled);
5110 IsTopNode = true;
5111 } else {
5112 do {
5113 if (BottomQ.empty()) return nullptr;
5114 SU = BottomQ.top();
5115 BottomQ.pop();
5116 } while (SU->isScheduled);
5117 IsTopNode = false;
5118 }
5119 if (IsAlternating)
5120 IsTopDown = !IsTopDown;
5121 return SU;
5122 }
5123
5124 void schedNode(SUnit *SU, bool IsTopNode) override {}
5125
5126 void releaseTopNode(SUnit *SU) override {
5127 TopQ.push(SU);
5128 }
5129 void releaseBottomNode(SUnit *SU) override {
5130 BottomQ.push(SU);
5131 }
5132};
5133
5134} // end anonymous namespace
5135
5137 MISched::Direction PreRADirection =
5138 getCodeGenOptions(*C->MF).misched_prera_direction;
5139 bool Alternate =
5140 PreRADirection != MISched::TopDown && PreRADirection != MISched::BottomUp;
5141 bool TopDown = PreRADirection != MISched::BottomUp;
5142 return new ScheduleDAGMILive(
5143 C, std::make_unique<InstructionShuffler>(Alternate, TopDown));
5144}
5145
5147 "shuffle", "Shuffle machine instructions alternating directions",
5149#endif // !NDEBUG
5150
5151//===----------------------------------------------------------------------===//
5152// GraphWriter support for ScheduleDAGMILive.
5153//===----------------------------------------------------------------------===//
5154
5155#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
5156
5157template <>
5159};
5160
5161template <>
5162struct llvm::DOTGraphTraits<ScheduleDAGMI *> : public DefaultDOTGraphTraits {
5163 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
5164
5165 static std::string getGraphName(const ScheduleDAG *G) {
5166 return std::string(G->MF.getName());
5167 }
5168
5169 static bool renderGraphFromBottomUp() {
5170 return true;
5171 }
5172
5173 static bool isNodeHidden(const SUnit *Node, const ScheduleDAG *G) {
5174 unsigned Cutoff = getCodeGenOptions(G->MF).misched_view_cutoff;
5175 if (Cutoff == 0)
5176 return false;
5177 return Node->Preds.size() > Cutoff || Node->Succs.size() > Cutoff;
5178 }
5179
5180 /// If you want to override the dot attributes printed for a particular
5181 /// edge, override this method.
5182 static std::string getEdgeAttributes(const SUnit *Node,
5183 SUnitIterator EI,
5184 const ScheduleDAG *Graph) {
5185 if (EI.isArtificialDep())
5186 return "color=cyan,style=dashed";
5187 if (EI.isCtrlDep())
5188 return "color=blue,style=dashed";
5189 return "";
5190 }
5191
5192 static std::string getNodeLabel(const SUnit *SU, const ScheduleDAG *G) {
5193 std::string Str;
5194 raw_string_ostream SS(Str);
5195 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
5196 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
5197 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
5198 SS << *SU;
5199 if (DFS)
5200 SS << " I:" << DFS->getNumInstrs(SU);
5201 return Str;
5202 }
5203
5204 static std::string getNodeDescription(const SUnit *SU, const ScheduleDAG *G) {
5205 return G->getGraphNodeLabel(SU);
5206 }
5207
5208 static std::string getNodeAttributes(const SUnit *N, const ScheduleDAG *G) {
5209 std::string Str("shape=Mrecord");
5210 const ScheduleDAGMI *DAG = static_cast<const ScheduleDAGMI*>(G);
5211 const SchedDFSResult *DFS = DAG->hasVRegLiveness() ?
5212 static_cast<const ScheduleDAGMILive*>(G)->getDFSResult() : nullptr;
5213 if (DFS) {
5214 Str += ",style=filled,fillcolor=\"#";
5215 Str += DOT::getColorString(DFS->getSubtreeID(N));
5216 Str += '"';
5217 }
5218 return Str;
5219 }
5220};
5221
5222#endif // NDEBUG
5223
5224/// viewGraph - Pop up a ghostview window with the reachable parts of the DAG
5225/// rendered using 'dot'.
5226void ScheduleDAGMI::viewGraph(const Twine &Name, const Twine &Title) {
5227#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
5228 ViewGraph(this, Name, false, Title);
5229#else
5230 errs() << "ScheduleDAGMI::viewGraph is only available in debug builds on "
5231 << "systems with Graphviz or gv!\n";
5232#endif // NDEBUG
5233}
5234
5235/// Out-of-line implementation with no arguments is handy for gdb.
5237 viewGraph(getDAGName(), "Scheduling-Units Graph for " + getDAGName());
5238}
5239
5240/// Sort predicate for the intervals stored in an instance of
5241/// ResourceSegments. Intervals are always disjoint (no intersection
5242/// for any pairs of intervals), therefore we can sort the totality of
5243/// the intervals by looking only at the left boundary.
5246 return A.first < B.first;
5247}
5248
5249unsigned ResourceSegments::getFirstAvailableAt(
5250 unsigned CurrCycle, unsigned AcquireAtCycle, unsigned ReleaseAtCycle,
5251 std::function<ResourceSegments::IntervalTy(unsigned, unsigned, unsigned)>
5252 IntervalBuilder) const {
5253 assert(llvm::is_sorted(_Intervals, sortIntervals) &&
5254 "Cannot execute on an un-sorted set of intervals.");
5255
5256 // Zero resource usage is allowed by TargetSchedule.td but we do not construct
5257 // a ResourceSegment interval for that situation.
5258 if (AcquireAtCycle == ReleaseAtCycle)
5259 return CurrCycle;
5260
5261 unsigned RetCycle = CurrCycle;
5262 ResourceSegments::IntervalTy NewInterval =
5263 IntervalBuilder(RetCycle, AcquireAtCycle, ReleaseAtCycle);
5264 for (auto &Interval : _Intervals) {
5265 if (!intersects(NewInterval, Interval))
5266 continue;
5267
5268 // Move the interval right next to the top of the one it
5269 // intersects.
5270 assert(Interval.second > NewInterval.first &&
5271 "Invalid intervals configuration.");
5272 RetCycle += (unsigned)Interval.second - (unsigned)NewInterval.first;
5273 NewInterval = IntervalBuilder(RetCycle, AcquireAtCycle, ReleaseAtCycle);
5274 }
5275 return RetCycle;
5276}
5277
5279 const unsigned CutOff) {
5280 assert(A.first <= A.second && "Cannot add negative resource usage");
5281 assert(CutOff > 0 && "0-size interval history has no use.");
5282 // Zero resource usage is allowed by TargetSchedule.td, in the case that the
5283 // instruction needed the resource to be available but does not use it.
5284 // However, ResourceSegment represents an interval that is closed on the left
5285 // and open on the right. It is impossible to represent an empty interval when
5286 // the left is closed. Do not add it to Intervals.
5287 if (A.first == A.second)
5288 return;
5289
5290 assert(all_of(_Intervals,
5291 [&A](const ResourceSegments::IntervalTy &Interval) -> bool {
5292 return !intersects(A, Interval);
5293 }) &&
5294 "A resource is being overwritten");
5295 _Intervals.push_back(A);
5296
5297 sortAndMerge();
5298
5299 // Do not keep the full history of the intervals, just the
5300 // latest #CutOff.
5301 while (_Intervals.size() > CutOff)
5302 _Intervals.pop_front();
5303}
5304
5307 assert(A.first <= A.second && "Invalid interval");
5308 assert(B.first <= B.second && "Invalid interval");
5309
5310 // Share one boundary.
5311 if ((A.first == B.first) || (A.second == B.second))
5312 return true;
5313
5314 // full intersersect: [ *** ) B
5315 // [***) A
5316 if ((A.first > B.first) && (A.second < B.second))
5317 return true;
5318
5319 // right intersect: [ ***) B
5320 // [*** ) A
5321 if ((A.first > B.first) && (A.first < B.second) && (A.second > B.second))
5322 return true;
5323
5324 // left intersect: [*** ) B
5325 // [ ***) A
5326 if ((A.first < B.first) && (B.first < A.second) && (B.second > B.first))
5327 return true;
5328
5329 return false;
5330}
5331
5332void ResourceSegments::sortAndMerge() {
5333 if (_Intervals.size() <= 1)
5334 return;
5335
5336 // First sort the collection.
5337 _Intervals.sort(sortIntervals);
5338
5339 // can use next because I have at least 2 elements in the list
5340 auto next = std::next(std::begin(_Intervals));
5341 auto E = std::end(_Intervals);
5342 for (; next != E; ++next) {
5343 if (std::prev(next)->second >= next->first) {
5344 next->first = std::prev(next)->first;
5345 _Intervals.erase(std::prev(next));
5346 continue;
5347 }
5348 }
5349}
MachineInstrBuilder MachineInstrBuilder & DefMI
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
Function Alias Analysis false
static const Function * getParent(const Value *V)
basic Basic Alias true
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
static std::optional< ArrayRef< InsnRange >::iterator > intersects(const MachineInstr *StartMI, const MachineInstr *EndMI, ArrayRef< InsnRange > Ranges, const InstructionOrdering &Ordering)
Check if the instruction range [StartMI, EndMI] intersects any instruction range in Ranges.
This file defines the DenseMap class.
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
A common definition of LaneBitmask for use in TableGen and CodeGen.
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
static bool isSchedBoundary(MachineBasicBlock::iterator MI, MachineBasicBlock *MBB, MachineFunction *MF, const TargetInstrInfo *TII)
Return true of the given instruction should not be included in a scheduling region.
static MachineSchedRegistry ILPMaxRegistry("ilpmax", "Schedule bottom-up for max ILP", createILPMaxScheduler)
PostRA Machine Instruction Scheduler
static MachineBasicBlock::const_iterator nextIfDebug(MachineBasicBlock::const_iterator I, MachineBasicBlock::const_iterator End)
If this iterator is a debug value, increment until reaching the End or a non-debug instruction.
static const unsigned MinSubtreeSize
static const unsigned InvalidCycle
static MachineBasicBlock::const_iterator priorNonDebug(MachineBasicBlock::const_iterator I, MachineBasicBlock::const_iterator Beg)
Decrement this iterator until reaching the top or a non-debug instr.
static cl::opt< MachineSchedRegistry::ScheduleDAGCtor, false, RegisterPassParser< MachineSchedRegistry > > MachineSchedOpt("misched", cl::init(&useDefaultMachineSched), cl::Hidden, cl::desc("Machine instruction scheduler to use"))
MachineSchedOpt allows command line selection of the scheduler.
static MachineSchedRegistry GenericSchedRegistry("converge", "Standard converging scheduler.", createConvergingSched)
static cl::opt< TargetSubtargetInfo::AntiDepBreakMode > PostRABreakAntiDeps("misched-postra-break-antideps", cl::Hidden, cl::desc("Set the post-RA MISched anti-dependency break mode"), cl::init(TargetSubtargetInfo::ANTIDEP_NONE), cl::values(clEnumValN(TargetSubtargetInfo::ANTIDEP_NONE, "none", "No anti-dependency breaking"), clEnumValN(TargetSubtargetInfo::ANTIDEP_CRITICAL, "critical", "Break critical-path anti-dependencies"), clEnumValN(TargetSubtargetInfo::ANTIDEP_ALL, "all", "Break all anti-dependencies")))
static bool checkResourceLimit(unsigned LFactor, unsigned Count, unsigned Latency, bool AfterSchedNode)
Given a Count of resource usage and a Latency value, return true if a SchedBoundary becomes resource ...
static ScheduleDAGInstrs * createInstructionShuffler(MachineSchedContext *C)
static ScheduleDAGInstrs * useDefaultMachineSched(MachineSchedContext *C)
A dummy default scheduler factory indicates whether the scheduler is overridden on the command line.
static bool sortIntervals(const ResourceSegments::IntervalTy &A, const ResourceSegments::IntervalTy &B)
Sort predicate for the intervals stored in an instance of ResourceSegments.
static MachineSchedRegistry DefaultSchedRegistry("default", "Use the target's default scheduler choice.", useDefaultMachineSched)
static const char * scheduleTableLegend
static ScheduleDAGInstrs * createConvergingSched(MachineSchedContext *C)
static MachineSchedRegistry ShufflerRegistry("shuffle", "Shuffle machine instructions alternating directions", createInstructionShuffler)
static void tracePick(const SUnit *SU, const GenericSchedulerBase::CandReason Reason, const bool IsTop, const bool IsPostRA=false)
static void getSchedRegions(MachineBasicBlock *MBB, MBBRegionsVector &Regions, bool RegionsTopDown)
static ScheduleDAGInstrs * createILPMaxScheduler(MachineSchedContext *C)
SmallVector< SchedRegion, 16 > MBBRegionsVector
static ScheduleDAGInstrs * createILPMinScheduler(MachineSchedContext *C)
static MachineSchedRegistry ILPMinRegistry("ilpmin", "Schedule bottom-up for min ILP", createILPMinScheduler)
Register const TargetRegisterInfo * TRI
std::pair< uint64_t, uint64_t > Interval
static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS)
#define P(N)
FunctionAnalysisManager FAM
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the PriorityQueue class.
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
static const X86InstrFMA3Group Groups[]
Value * RHS
Class recording the (high level) value of a variable.
A manager for alias analyses.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object.
Class for arbitrary precision integers.
Definition APInt.h:78
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:280
std::vector< std::pair< MachineInstr *, MachineInstr * > > DbgValueVector
void startBlock(MachineBasicBlock *MBB)
bool breakAntiDependencies(const std::vector< SUnit > &SUnits, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, AntiDepBreaker::DbgValueVector &DbgValues)
void exitRegion(MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End)
AntiDepState(MachineSchedContext *C, TargetSubtargetInfo::AntiDepBreakMode AntiDepMode)
void enterRegion(MachineBasicBlock::iterator End)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
reverse_iterator rend() const
Definition ArrayRef.h:133
size_t size() const
Get the array size.
Definition ArrayRef.h:141
reverse_iterator rbegin() const
Definition ArrayRef.h:132
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:762
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
Register getReg() const
The EquivalenceClasses data structure is just a set of these.
This represents a collection of equivalence classes and supports three efficient operations: insert a...
iterator_range< member_iterator > members(const ECValue &ECV) const
member_iterator unionSets(const ElemTy &V1, const ElemTy &V2)
Merge the two equivalence sets for the specified values, inserting them if they do not already exist ...
void traceCandidate(const SchedCandidate &Cand)
LLVM_ABI void setPolicy(CandPolicy &Policy, bool IsPostRA, SchedBoundary &CurrZone, SchedBoundary *OtherZone)
Set the CandPolicy given a scheduling zone given the current resources and latencies inside and outsi...
MachineSchedPolicy RegionPolicy
const TargetSchedModel * SchedModel
static const char * getReasonStr(GenericSchedulerBase::CandReason Reason)
const MachineSchedContext * Context
CandReason
Represent the type of SchedCandidate found within a single queue.
const TargetRegisterInfo * TRI
void checkAcyclicLatency()
Set IsAcyclicLatencyLimited if the acyclic path is longer than the cyclic critical path by more cycle...
SchedCandidate BotCand
Candidate last picked from Bot boundary.
SchedCandidate TopCand
Candidate last picked from Top boundary.
virtual bool tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand, SchedBoundary *Zone) const
Apply a set of heuristics to a new candidate.
ScheduleDAGMILive * DAG
void dumpPolicy() const override
void initialize(ScheduleDAGMI *dag) override
Initialize the strategy after building the DAG for a new region.
void initCandidate(SchedCandidate &Cand, SUnit *SU, bool AtTop, const RegPressureTracker &RPTracker, RegPressureTracker &TempTracker)
void registerRoots() override
Notify this strategy that all roots have been released (including those that depend on EntrySU or Exi...
void initPolicy(MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, unsigned NumRegionInstrs) override
Initialize the per-region scheduling policy.
void reschedulePhysReg(SUnit *SU, bool isTop)
SUnit * pickNode(bool &IsTopNode) override
Pick the best node to balance the schedule. Implements MachineSchedStrategy.
void pickNodeFromQueue(SchedBoundary &Zone, const CandPolicy &ZonePolicy, const RegPressureTracker &RPTracker, SchedCandidate &Candidate)
Pick the best candidate from the queue.
bool shouldTrackLaneMasks() const override
Returns true if lanemasks should be tracked.
void schedNode(SUnit *SU, bool IsTopNode) override
Update the scheduler's state after scheduling a node.
SUnit * pickNodeBidirectional(bool &IsTopNode)
Pick the best candidate node from either the top or bottom queue.
bool getMemOperandsWithOffsetWidth(const MachineInstr &LdSt, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const override
Get the base register and byte offset of a load/store instr.
Itinerary data supplied by a subtarget to be used by a target.
LiveInterval - This class represents the liveness of a register, or stack slot.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
LiveInterval & getInterval(Register Reg)
Result of a LiveRange query.
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
Segments::iterator iterator
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
iterator begin()
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
bool isLocal(SlotIndex Start, SlotIndex End) const
True iff this segment is a single segment that lies between the specified boundaries,...
LLVM_ABI iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
bool hasValue() const
static LocationSize precise(uint64_t Value)
MachineInstrBundleIterator< const MachineInstr > const_iterator
MachineInstrBundleIterator< MachineInstr > iterator
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream.
Representation of each machine instruction.
bool isCopy() const
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
Analysis pass that exposes the MachineLoopInfo for a machine function.
MachineOperand class - Representation of each machine instruction operand.
MachinePassRegistry - Track the registration of machine passes.
MachineSchedRegistry provides a selection of available machine instruction schedulers.
static LLVM_ABI MachinePassRegistry< ScheduleDAGCtor > Registry
ScheduleDAGInstrs *(*)(MachineSchedContext *) ScheduleDAGCtor
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI MachineSchedulerPass(const TargetMachine *TM)
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void initPolicy(MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, unsigned NumRegionInstrs) override
Optionally override the per-region scheduling policy.
virtual bool tryCandidate(SchedCandidate &Cand, SchedCandidate &TryCand)
Apply a set of heuristics to a new candidate for PostRA scheduling.
void schedNode(SUnit *SU, bool IsTopNode) override
Called after ScheduleDAGMI has scheduled an instruction and updated scheduled/remaining flags in the ...
SchedCandidate BotCand
Candidate last picked from Bot boundary.
void pickNodeFromQueue(SchedBoundary &Zone, SchedCandidate &Cand)
void initialize(ScheduleDAGMI *Dag) override
Initialize the strategy after building the DAG for a new region.
SchedCandidate TopCand
Candidate last picked from Top boundary.
SUnit * pickNodeBidirectional(bool &IsTopNode)
Pick the best candidate node from either the top or bottom queue.
void registerRoots() override
Notify this strategy that all roots have been released (including those that depend on EntrySU or Exi...
SUnit * pickNode(bool &IsTopNode) override
Pick the next node to schedule.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI PostMachineSchedulerPass(const TargetMachine *TM)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:152
Capture a change in pressure for a single pressure set.
unsigned getPSetOrMax() const
unsigned getPSet() const
List of PressureChanges in order of increasing, unique PSetID.
LLVM_ABI void dump(const TargetRegisterInfo &TRI) const
LLVM_ABI void addPressureChange(VirtRegOrUnit VRegOrUnit, bool IsDec, const MachineRegisterInfo *MRI)
Add a change in pressure to the pressure diff of a given instruction.
void clear()
clear - Erase all elements from the queue.
Helpers for implementing custom MachineSchedStrategy classes.
ArrayRef< SUnit * > elements()
LLVM_ABI void dump() const
std::vector< SUnit * >::iterator iterator
StringRef getName() const
Track the current register pressure at some position in the instruction stream, and remember the high...
LLVM_ABI void getMaxUpwardPressureDelta(const MachineInstr *MI, PressureDiff *PDiff, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit)
Consider the pressure increase caused by traversing this instruction bottom-up.
LLVM_ABI void getMaxDownwardPressureDelta(const MachineInstr *MI, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit)
Consider the pressure increase caused by traversing this instruction top-down.
LLVM_ABI void getUpwardPressureDelta(const MachineInstr *MI, PressureDiff &PDiff, RegPressureDelta &Delta, ArrayRef< PressureChange > CriticalPSets, ArrayRef< unsigned > MaxPressureLimit) const
This is the fast version of querying register pressure that does not directly depend on current liven...
List of registers defined and used by a machine instruction.
LLVM_ABI void detectDeadDefs(const MachineInstr &MI, LiveIntervals &LIS, const MachineRegisterInfo &MRI)
Use liveness information to find dead defs at MI's dead slot not marked with a dead flag and move the...
LLVM_ABI void adjustLaneLiveness(LiveIntervals &LIS, const MachineRegisterInfo &MRI, SlotIndex Pos)
Use liveness information to find out which uses/defs are partially undefined/dead at Pos and adjust t...
LLVM_ABI void collect(const MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, bool TrackLaneMasks, bool IgnoreDead)
Analyze the given instruction MI and fill in the Uses, Defs and DeadDefs list based on the MachineOpe...
static LLVM_ABI void restoreLivenessFlags(MachineInstr &MI, const TargetRegisterInfo &TRI, const MachineRegisterInfo &MRI, LiveIntervals &LIS, bool TrackLaneMasks=true, ArrayRef< Register > OnlyRegs={})
Clear potentially-stale read-undef flags on the defs of MI, then recompute them from LIS.
RegisterPassParser class - Handle the addition of new machine passes.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
LLVM_ABI void add(IntervalTy A, const unsigned CutOff=10)
Adds an interval [a, b) to the collection of the instance.
static IntervalTy getResourceIntervalBottom(unsigned C, unsigned AcquireAtCycle, unsigned ReleaseAtCycle)
These function return the interval used by a resource in bottom and top scheduling.
static LLVM_ABI bool intersects(IntervalTy A, IntervalTy B)
Checks whether intervals intersect.
std::pair< int64_t, int64_t > IntervalTy
Represents an interval of discrete integer values closed on the left and open on the right: [a,...
static IntervalTy getResourceIntervalTop(unsigned C, unsigned AcquireAtCycle, unsigned ReleaseAtCycle)
Scheduling dependency.
Definition ScheduleDAG.h:54
SUnit * getSUnit() const
Kind getKind() const
Returns an enum value representing the kind of the dependence.
@ Anti
A register anti-dependence (aka WAR).
Definition ScheduleDAG.h:59
@ Data
Regular data dependence (aka true-dependence).
Definition ScheduleDAG.h:58
bool isWeak() const
Tests if this a weak dependence.
@ Cluster
Weak DAG edge linking a chain of clustered instrs.
Definition ScheduleDAG.h:79
@ Artificial
Arbitrary strong DAG edge (no real dependence).
Definition ScheduleDAG.h:77
@ Weak
Arbitrary weak DAG edge.
Definition ScheduleDAG.h:78
unsigned getLatency() const
Returns the latency value for this edge, which roughly means the minimum number of cycles that must e...
Register getReg() const
Returns the register associated with this edge.
bool isNormalMemoryOrBarrier() const
Tests if this is could be any kind of memory dependence.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI SSAMachineSchedulerPass(const TargetMachine *TM)
bool isArtificialDep() const
bool isCtrlDep() const
Tests if this is not an SDep::Data dependence.
Scheduling unit. This is a node in the scheduling DAG.
bool isCall
Is a function call.
unsigned TopReadyCycle
Cycle relative to start when node is ready.
unsigned NodeNum
Entry # of node in the node vector.
unsigned NumSuccsLeft
bool isUnbuffered
Uses an unbuffered resource.
unsigned getHeight() const
Returns the height of this node, which is the length of the maximum path down to any node which has n...
unsigned short Latency
Node latency.
unsigned getDepth() const
Returns the depth of this node, which is the length of the maximum path up to any node which has no p...
bool isScheduled
True once scheduled.
unsigned ParentClusterIdx
The parent cluster id.
unsigned NumPredsLeft
bool hasPhysRegDefs
Has physreg defs that are being used.
unsigned BotReadyCycle
Cycle relative to end when node is ready.
SmallVector< SDep, 4 > Succs
All sunit successors.
bool hasReservedResource
Uses a reserved resource.
unsigned WeakPredsLeft
bool isBottomReady() const
bool hasPhysRegUses
Has physreg uses.
bool isTopReady() const
SmallVector< SDep, 4 > Preds
All sunit predecessors.
unsigned WeakSuccsLeft
MachineInstr * getInstr() const
Returns the representative MachineInstr for this SUnit.
Each Scheduling boundary is associated with ready queues.
LLVM_ABI unsigned getNextResourceCycleByInstance(unsigned InstanceIndex, unsigned ReleaseAtCycle, unsigned AcquireAtCycle)
Compute the next cycle at which the given processor resource unit can be scheduled.
LLVM_ABI void releasePending()
Release pending ready nodes in to the available queue.
unsigned getDependentLatency() const
bool isReservedGroup(unsigned PIdx) const
unsigned getScheduledLatency() const
Get the number of latency cycles "covered" by the scheduled instructions.
LLVM_ABI void incExecutedResources(unsigned PIdx, unsigned Count)
bool isResourceLimited() const
const TargetSchedModel * SchedModel
unsigned getExecutedCount() const
Get a scaled count for the minimum execution time of the scheduled micro-ops that are ready to execut...
LLVM_ABI unsigned getLatencyStallCycles(SUnit *SU)
Get the difference between the given SUnit's ready time and the current cycle.
LLVM_ABI unsigned findMaxLatency(ArrayRef< SUnit * > ReadySUs)
LLVM_ABI void dumpReservedCycles() const
Dump the state of the information that tracks resource usage.
LLVM_ABI unsigned getOtherResourceCount(unsigned &OtherCritIdx)
SchedRemainder * Rem
LLVM_ABI void bumpNode(SUnit *SU)
Move the boundary of scheduled code by one SUnit.
unsigned getCriticalCount() const
Get the scaled count of scheduled micro-ops and resources, including executed resources.
LLVM_ABI SUnit * pickOnlyChoice()
Call this before applying any other heuristics to the Available queue.
LLVM_ABI void releaseNode(SUnit *SU, unsigned ReadyCycle, bool InPQueue, unsigned Idx=0)
Release SU to make it ready.
LLVM_ABI unsigned countResource(const MCSchedClassDesc *SC, unsigned PIdx, unsigned Cycles, unsigned ReadyCycle, unsigned StartAtCycle)
Add the given processor resource to this scheduled zone.
LLVM_ABI ~SchedBoundary()
LLVM_ABI void init(ScheduleDAGMI *dag, const TargetSchedModel *smodel, SchedRemainder *rem)
unsigned getResourceCount(unsigned ResIdx) const
LLVM_ABI void bumpCycle(unsigned NextCycle)
Move the boundary of scheduled code by one cycle.
unsigned getCurrMOps() const
Micro-ops issued in the current cycle.
unsigned getCurrCycle() const
Number of cycles to issue the instructions scheduled in this zone.
std::unique_ptr< ScheduleHazardRecognizer > HazardRec
LLVM_ABI bool checkHazard(SUnit *SU)
Does this SU have a hazard within the current instruction group.
LLVM_ABI std::pair< unsigned, unsigned > getNextResourceCycle(const MCSchedClassDesc *SC, unsigned PIdx, unsigned ReleaseAtCycle, unsigned AcquireAtCycle)
Compute the next cycle at which the given processor resource can be scheduled.
LLVM_ABI void dumpScheduledState() const
LLVM_ABI void removeReady(SUnit *SU)
Remove SU from the ready set for this boundary.
unsigned getZoneCritResIdx() const
unsigned getUnscheduledLatency(SUnit *SU) const
Compute the values of each DAG node for various metrics during DFS.
Definition ScheduleDFS.h:65
unsigned getNumInstrs(const SUnit *SU) const
Get the number of instructions in the given subtree and its children.
unsigned getSubtreeID(const SUnit *SU) const
Get the ID of the subtree the given DAG node belongs to.
ILPValue getILP(const SUnit *SU) const
Get the ILP value for a DAG node.
unsigned getSubtreeLevel(unsigned SubtreeID) const
Get the connection level of a subtree.
A ScheduleDAG for scheduling lists of MachineInstr.
SmallVector< ClusterInfo > & getClusters()
Returns the array of the clusters.
virtual void finishBlock()
Cleans up after scheduling in the given block.
MachineBasicBlock::iterator end() const
Returns an iterator to the bottom of the current scheduling region.
std::string getDAGName() const override
Returns a label for the region of code covered by the DAG.
MachineBasicBlock * BB
The block in which to insert instructions.
virtual void startBlock(MachineBasicBlock *BB)
Prepares to perform scheduling in the given block.
const CodeGenOptions & Opts
MachineBasicBlock::iterator RegionEnd
The end of the range to be scheduled.
const MCSchedClassDesc * getSchedClass(SUnit *SU) const
Resolves and cache a resolved scheduling class for an SUnit.
DbgValueVector DbgValues
Remember instruction that precedes DBG_VALUE.
bool addEdge(SUnit *SuccSU, const SDep &PredDep)
Add a DAG edge to the given SU with the given predecessor dependence data.
DumpDirection
The direction that should be used to dump the scheduled Sequence.
bool TrackLaneMasks
Whether lane masks should get tracked.
void dumpNode(const SUnit &SU) const override
bool IsReachable(SUnit *SU, SUnit *TargetSU)
IsReachable - Checks if SU is reachable from TargetSU.
MachineBasicBlock::iterator begin() const
Returns an iterator to the top of the current scheduling region.
void buildSchedGraph(AAResults *AA, RegPressureTracker *RPTracker=nullptr, PressureDiffs *PDiffs=nullptr, LiveIntervals *LIS=nullptr, bool TrackLaneMasks=false)
Builds SUnits for the current region.
SUnit * getSUnit(MachineInstr *MI) const
Returns an existing SUnit for this MI, or nullptr.
TargetSchedModel SchedModel
TargetSchedModel provides an interface to the machine model.
virtual void exitRegion()
Called when the scheduler has finished scheduling the current region.
bool canAddEdge(SUnit *SuccSU, SUnit *PredSU)
True if an edge can be added from PredSU to SuccSU without creating a cycle.
MachineBasicBlock::iterator RegionBegin
The beginning of the range to be scheduled.
virtual void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs)
Initialize the DAG and common scheduler state for a new scheduling region.
void dump() const override
void setDumpDirection(DumpDirection D)
ScheduleDAGMILive is an implementation of ScheduleDAGInstrs that schedules machine instructions while...
void scheduleMI(SUnit *SU, bool IsTopNode)
Move an instruction and update register pressure.
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
VReg2SUnitMultiMap VRegUses
Maps vregs to the SUnits of their uses in the current scheduling region.
void computeDFSResult()
Compute a DFSResult after DAG building is complete, and before any queue comparisons.
PressureDiff & getPressureDiff(const SUnit *SU)
SchedDFSResult * DFSResult
Information about DAG subtrees.
void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs) override
Implement the ScheduleDAGInstrs interface for handling the next scheduling region.
void initQueues(ArrayRef< SUnit * > TopRoots, ArrayRef< SUnit * > BotRoots)
Release ExitSU predecessors and setup scheduler queues.
RegPressureTracker BotRPTracker
void buildDAGWithRegPressure()
Call ScheduleDAGInstrs::buildSchedGraph with register pressure tracking enabled.
std::vector< PressureChange > RegionCriticalPSets
List of pressure sets that exceed the target's pressure limit before scheduling, listed in increasing...
void updateScheduledPressure(const SUnit *SU, const std::vector< unsigned > &NewMaxPressure)
unsigned computeCyclicCriticalPath()
Compute the cyclic critical path through the DAG.
void updatePressureDiffs(ArrayRef< VRegMaskOrUnit > LiveUses)
Update the PressureDiff array for liveness after scheduling this instruction.
RegisterClassInfo * RegClassInfo
const SchedDFSResult * getDFSResult() const
Return a non-null DFS result if the scheduling strategy initialized it.
RegPressureTracker RPTracker
bool ShouldTrackPressure
Register pressure in this region computed by initRegPressure.
void dump() const override
MachineBasicBlock::iterator LiveRegionEnd
RegPressureTracker TopRPTracker
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
void dumpSchedule() const
dump the scheduled Sequence.
std::unique_ptr< MachineSchedStrategy > SchedImpl
void exitRegion() override
Called when the scheduler has finished scheduling the current region.
void startBlock(MachineBasicBlock *bb) override
Prepares to perform scheduling in the given block.
void releasePred(SUnit *SU, SDep *PredEdge)
ReleasePred - Decrement the NumSuccsLeft count of a predecessor.
void initQueues(ArrayRef< SUnit * > TopRoots, ArrayRef< SUnit * > BotRoots)
Release ExitSU predecessors and setup scheduler queues.
void moveInstruction(MachineInstr *MI, MachineBasicBlock::iterator InsertPos)
Change the position of an instruction within the basic block and update live ranges and region bounda...
void releasePredecessors(SUnit *SU)
releasePredecessors - Call releasePred on each of SU's predecessors.
void postProcessDAG()
Apply each ScheduleDAGMutation step in order.
void dumpScheduleTraceTopDown() const
Print execution trace of the schedule top-down or bottom-up.
void schedule() override
Implement ScheduleDAGInstrs interface for scheduling a sequence of reorderable instructions.
AntiDepState AntiDep
State for optional post-RA anti-dependency breaking.
void findRootsAndBiasEdges(SmallVectorImpl< SUnit * > &TopRoots, SmallVectorImpl< SUnit * > &BotRoots)
MachineBasicBlock::iterator CurrentBottom
The bottom of the unscheduled zone.
virtual bool hasVRegLiveness() const
Return true if this DAG supports VReg liveness and RegPressure.
void enterRegion(MachineBasicBlock *bb, MachineBasicBlock::iterator begin, MachineBasicBlock::iterator end, unsigned regioninstrs) override
Implement the ScheduleDAGInstrs interface for handling the next scheduling region.
LiveIntervals * getLIS() const
void viewGraph(const Twine &Name, const Twine &Title) override
viewGraph - Pop up a ghostview window with the reachable parts of the DAG rendered using 'dot'.
void viewGraph() override
Out-of-line implementation with no arguments is handy for gdb.
void releaseSucc(SUnit *SU, SDep *SuccEdge)
ReleaseSucc - Decrement the NumPredsLeft count of a successor.
void dumpScheduleTraceBottomUp() const
~ScheduleDAGMI() override
void finishBlock() override
Cleans up after scheduling in the given block.
void updateQueues(SUnit *SU, bool IsTopNode)
Update scheduler DAG and queues after scheduling an instruction.
void placeDebugValues()
Reinsert debug_values recorded in ScheduleDAGInstrs::DbgValues.
MachineBasicBlock::iterator CurrentTop
The top of the unscheduled zone.
void releaseSuccessors(SUnit *SU)
releaseSuccessors - Call releaseSucc on each of SU's successors.
std::vector< std::unique_ptr< ScheduleDAGMutation > > Mutations
Ordered list of DAG postprocessing steps.
Mutate the DAG as a postpass after normal DAG building.
MachineRegisterInfo & MRI
Virtual/real register map.
std::vector< SUnit > SUnits
The scheduling units.
const TargetRegisterInfo * TRI
Target processor register info.
SUnit EntrySU
Special node for the region entry.
MachineFunction & MF
Machine function.
void dumpNodeAll(const SUnit &SU) const
void dumpNodeName(const SUnit &SU) const
SUnit ExitSU
Special node for the region exit.
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
std::reverse_iterator< const_iterator > const_reverse_iterator
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Register getReg() const
Information about stack frame layout on the target.
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
TargetInstrInfo - Interface to description of machine instruction set.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Primary interface to the complete machine description for the target machine.
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Provide an instruction scheduling machine model to CodeGen passes.
unsigned getMicroOpFactor() const
Multiply number of micro-ops by this factor to normalize it relative to other resources.
ProcResIter getWriteProcResEnd(const MCSchedClassDesc *SC) const
LLVM_ABI bool hasInstrSchedModel() const
Return true if this machine model includes an instruction-level scheduling model.
const MCWriteProcResEntry * ProcResIter
unsigned getResourceFactor(unsigned ResIdx) const
Multiply the number of units consumed for a resource by this factor to normalize it relative to other...
LLVM_ABI unsigned getNumMicroOps(const MachineInstr *MI, const MCSchedClassDesc *SC=nullptr) const
Return the number of issue slots required for this MI.
unsigned getNumProcResourceKinds() const
Get the number of kinds of resources for this target.
ProcResIter getWriteProcResBegin(const MCSchedClassDesc *SC) const
enum { ANTIDEP_NONE, ANTIDEP_CRITICAL, ANTIDEP_ALL } AntiDepBreakMode
virtual void overridePostRASchedPolicy(MachineSchedPolicy &Policy, const SchedRegion &Region) const
Override generic post-ra scheduling policy within a region.
virtual void overrideSchedPolicy(MachineSchedPolicy &Policy, const SchedRegion &Region) const
Override generic scheduling policy within a region.
virtual bool enableMachineScheduler() const
True if the subtarget should run MachineScheduler after aggressive coalescing.
virtual bool enableSSAMachineScheduler() const
True if the subtarget should run a machine scheduler before PHI elimination.
virtual bool enablePostRAMachineScheduler() const
True if the subtarget should run a machine scheduler after register allocation.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetLowering * getTargetLowering() const
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
VNInfo - Value Number Information.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
Wrapper class representing a virtual register or register unit.
Definition Register.h:175
Base class for the machine scheduler classes.
void scheduleRegions(ScheduleDAGInstrs &Scheduler, bool FixKillFlags)
Main driver for both MachineScheduler and PostMachineScheduler.
Impl class for MachineScheduler.
void setMFAM(MachineFunctionAnalysisManager *MFAM)
void setLegacyPass(MachineFunctionPass *P)
bool run(MachineFunction &MF, const TargetMachine &TM, const RequiredAnalyses &Analyses)
ScheduleDAGInstrs * createMachineScheduler()
Instantiate a ScheduleDAGInstrs that will be owned by the caller.
Impl class for PostMachineScheduler.
bool run(MachineFunction &Func, const TargetMachine &TM, const RequiredAnalyses &Analyses)
void setMFAM(MachineFunctionAnalysisManager *MFAM)
ScheduleDAGInstrs * createPostMachineScheduler()
Instantiate a ScheduleDAGInstrs for PostRA scheduling that will be owned by the caller.
Impl class for SSAMachineScheduler.
bool run(MachineFunction &MF, const TargetMachine &TM, const RequiredAnalyses &Analyses)
ScheduleDAGInstrs * createMachineScheduler()
Instantiate a ScheduleDAGInstrs that will be owned by the caller.
void setMFAM(MachineFunctionAnalysisManager *MFAM)
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
LLVM_ABI StringRef getColorString(unsigned NodeNumber)
Get a color string for this node number.
void apply(Opt *O, const Mod &M, const Mods &... Ms)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
bool isSimple(Instruction *I)
Definition SLPUtils.cpp:843
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI int biasPhysReg(const SUnit *SU, bool isTop, bool BiasPRegsExtra=false)
Minimize physical register live ranges.
ScheduleDAGMILive * createSchedLive(MachineSchedContext *C)
Create the standard converging machine scheduler.
@ Offset
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
void stable_sort(R &&Range)
Definition STLExtras.h:2132
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI unsigned getWeakLeft(const SUnit *SU, bool isTop)
LLVM_ABI AntiDepBreaker * createAggressiveAntiDepBreaker(MachineFunction &MFi, const RegisterClassInfo &RCI, TargetSubtargetInfo::RegClassVector &CriticalPathRCs)
FormattedString right_justify(StringRef Str, unsigned Width)
right_justify - add spaces before string so total output is Width characters.
Definition Format.h:130
LLVM_ABI bool shouldVerifyScheduling(const MachineFunction &MF)
Returns whether -verify-misched is set.
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createLoadClusterDAGMutation(const TargetInstrInfo *TII, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI TargetSubtargetInfo::AntiDepBreakMode getPostRABreakAntiDeps()
Returns -misched-postra-break-antideps.
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
Definition LaneBitmask.h:92
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI char & MachineSchedulerID
MachineScheduler - This pass schedules machine instructions.
LLVM_ABI char & PostMachineSchedulerID
PostMachineScheduler - This pass schedules machine instructions postRA.
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createStoreClusterDAGMutation(const TargetInstrInfo *TII, bool ReorderWhileClustering=false)
If ReorderWhileClustering is set to true, no attempt will be made to reduce reordering due to store c...
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool tryPressure(const PressureChange &TryP, const PressureChange &CandP, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason, const TargetRegisterInfo *TRI, const MachineFunction &MF)
LLVM_ABI void initializeSSAMachineSchedulerLegacyPass(PassRegistry &)
ScheduleDAGMI * createSchedPostRA(MachineSchedContext *C)
Create a generic scheduler with no vreg liveness or DAG mutation passes.
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool shouldPrintMISchedDAGs(const MachineFunction &MF)
Return -misched-print-dags, which is false in a build without assertions.
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1986
LLVM_ABI bool tryLatency(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary &Zone)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
constexpr unsigned InvalidClusterId
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI MISched::Direction getPreRADirection(const MachineFunction &MF)
Returns -misched-prera-direction.
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition Format.h:123
bool isTheSameCluster(unsigned A, unsigned B)
Return whether the input cluster ID's are the same and valid.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool tryBiasPhysRegs(GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, SchedBoundary *Zone, bool BiasPRegsExtra)
LLVM_ABI char & SSAMachineSchedulerID
SSAMachineScheduler - This pass schedules machine instructions in SSA.
LLVM_ABI std::unique_ptr< ScheduleDAGMutation > createCopyConstrainDAGMutation(const TargetInstrInfo *TII)
DWARFExpression::Operation Op
constexpr std::optional< bool > toOptional(BoolOrDefault X)
LLVM_ABI bool tryGreater(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
SmallPtrSet< SUnit *, 8 > ClusterInfo
Keep record of which SUnit are in the same cluster group.
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI AntiDepBreaker * createCriticalAntiDepBreaker(MachineFunction &MFi, const RegisterClassInfo &RCI)
LLVM_ABI unsigned computeRemLatency(SchedBoundary &CurrZone)
Compute remaining latency.
constexpr bool valueOr(BoolOrDefault X, bool Default)
LLVM_ABI void dumpRegSetPressure(ArrayRef< unsigned > SetPressure, const TargetRegisterInfo *TRI)
LLVM_ABI bool tryLess(int TryVal, int CandVal, GenericSchedulerBase::SchedCandidate &TryCand, GenericSchedulerBase::SchedCandidate &Cand, GenericSchedulerBase::CandReason Reason)
Return true if this heuristic determines order.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI bool shouldViewMISchedDAGs(const MachineFunction &MF)
Return -misched-view-dags, which is false in a build without assertions.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
@ Enable
Enable colors.
Definition WithColor.h:47
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
Policy for scheduling the next instruction in the candidate's zone.
Store the state used by GenericScheduler heuristics, required for the lifetime of one invocation of p...
void reset(const CandPolicy &NewPolicy)
LLVM_ABI void initResourceDelta(const ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel)
Status of an instruction's critical resource consumption.
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81
Summarize the scheduling resources required for an instruction of a particular scheduling class.
Definition MCSchedule.h:124
Identify one of the processor resource kinds consumed by a particular scheduling class for the specif...
Definition MCSchedule.h:69
MachineSchedContext provides enough context from the MachineScheduler pass for the target to instanti...
RegisterClassInfo * RegClassInfo
MachineBlockFrequencyInfo * MBFI
const MachineLoopInfo * MLI
const TargetMachine * TM
RegisterPressure computed within a region of instructions delimited by TopPos and BottomPos.
A region of an MBB for scheduling.
Summarize the unscheduled region.
LLVM_ABI void init(ScheduleDAGMI *DAG, const TargetSchedModel *SchedModel)
SmallVector< unsigned, 16 > RemainingCounts
An individual mapping from virtual register number to SUnit.