[WebAssembly] Add new target feature in support of 'extended-const' proposal
[llvm-project.git] / llvm / lib / CodeGen / PostRASchedulerList.cpp
blobf8fb21ef356b4331a720cfc64829c40f548e8faf
1 //===----- SchedulePostRAList.cpp - list 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 // This implements a top-down list scheduler, using standard algorithms.
10 // The basic approach uses a priority queue of available nodes to schedule.
11 // One at a time, nodes are taken from the priority queue (thus in priority
12 // order), checked for legality to schedule, and emitted if legal.
14 // Nodes may not be legal to schedule either due to structural hazards (e.g.
15 // pipeline or resource constraints) or because an input to the instruction has
16 // not completed execution.
18 //===----------------------------------------------------------------------===//
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/AntiDepBreaker.h"
23 #include "llvm/CodeGen/LatencyPriorityQueue.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/RegisterClassInfo.h"
30 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
31 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
32 #include "llvm/CodeGen/SchedulerRegistry.h"
33 #include "llvm/CodeGen/TargetInstrInfo.h"
34 #include "llvm/CodeGen/TargetLowering.h"
35 #include "llvm/CodeGen/TargetPassConfig.h"
36 #include "llvm/CodeGen/TargetRegisterInfo.h"
37 #include "llvm/CodeGen/TargetSubtargetInfo.h"
38 #include "llvm/Config/llvm-config.h"
39 #include "llvm/InitializePasses.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 using namespace llvm;
46 #define DEBUG_TYPE "post-RA-sched"
48 STATISTIC(NumNoops, "Number of noops inserted");
49 STATISTIC(NumStalls, "Number of pipeline stalls");
50 STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
52 // Post-RA scheduling is enabled with
53 // TargetSubtargetInfo.enablePostRAScheduler(). This flag can be used to
54 // override the target.
55 static cl::opt<bool>
56 EnablePostRAScheduler("post-RA-scheduler",
57 cl::desc("Enable scheduling after register allocation"),
58 cl::init(false), cl::Hidden);
59 static cl::opt<std::string>
60 EnableAntiDepBreaking("break-anti-dependencies",
61 cl::desc("Break post-RA scheduling anti-dependencies: "
62 "\"critical\", \"all\", or \"none\""),
63 cl::init("none"), cl::Hidden);
65 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
66 static cl::opt<int>
67 DebugDiv("postra-sched-debugdiv",
68 cl::desc("Debug control MBBs that are scheduled"),
69 cl::init(0), cl::Hidden);
70 static cl::opt<int>
71 DebugMod("postra-sched-debugmod",
72 cl::desc("Debug control MBBs that are scheduled"),
73 cl::init(0), cl::Hidden);
75 AntiDepBreaker::~AntiDepBreaker() = default;
77 namespace {
78 class PostRAScheduler : public MachineFunctionPass {
79 const TargetInstrInfo *TII = nullptr;
80 RegisterClassInfo RegClassInfo;
82 public:
83 static char ID;
84 PostRAScheduler() : MachineFunctionPass(ID) {}
86 void getAnalysisUsage(AnalysisUsage &AU) const override {
87 AU.setPreservesCFG();
88 AU.addRequired<AAResultsWrapperPass>();
89 AU.addRequired<TargetPassConfig>();
90 AU.addRequired<MachineDominatorTree>();
91 AU.addPreserved<MachineDominatorTree>();
92 AU.addRequired<MachineLoopInfo>();
93 AU.addPreserved<MachineLoopInfo>();
94 MachineFunctionPass::getAnalysisUsage(AU);
97 MachineFunctionProperties getRequiredProperties() const override {
98 return MachineFunctionProperties().set(
99 MachineFunctionProperties::Property::NoVRegs);
102 bool runOnMachineFunction(MachineFunction &Fn) override;
104 private:
105 bool enablePostRAScheduler(
106 const TargetSubtargetInfo &ST, CodeGenOpt::Level OptLevel,
107 TargetSubtargetInfo::AntiDepBreakMode &Mode,
108 TargetSubtargetInfo::RegClassVector &CriticalPathRCs) const;
110 char PostRAScheduler::ID = 0;
112 class SchedulePostRATDList : public ScheduleDAGInstrs {
113 /// AvailableQueue - The priority queue to use for the available SUnits.
115 LatencyPriorityQueue AvailableQueue;
117 /// PendingQueue - This contains all of the instructions whose operands have
118 /// been issued, but their results are not ready yet (due to the latency of
119 /// the operation). Once the operands becomes available, the instruction is
120 /// added to the AvailableQueue.
121 std::vector<SUnit*> PendingQueue;
123 /// HazardRec - The hazard recognizer to use.
124 ScheduleHazardRecognizer *HazardRec;
126 /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
127 AntiDepBreaker *AntiDepBreak;
129 /// AA - AliasAnalysis for making memory reference queries.
130 AliasAnalysis *AA;
132 /// The schedule. Null SUnit*'s represent noop instructions.
133 std::vector<SUnit*> Sequence;
135 /// Ordered list of DAG postprocessing steps.
136 std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
138 /// The index in BB of RegionEnd.
140 /// This is the instruction number from the top of the current block, not
141 /// the SlotIndex. It is only used by the AntiDepBreaker.
142 unsigned EndIndex = 0;
144 public:
145 SchedulePostRATDList(
146 MachineFunction &MF, MachineLoopInfo &MLI, AliasAnalysis *AA,
147 const RegisterClassInfo &,
148 TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
149 SmallVectorImpl<const TargetRegisterClass *> &CriticalPathRCs);
151 ~SchedulePostRATDList() override;
153 /// startBlock - Initialize register live-range state for scheduling in
154 /// this block.
156 void startBlock(MachineBasicBlock *BB) override;
158 // Set the index of RegionEnd within the current BB.
159 void setEndIndex(unsigned EndIdx) { EndIndex = EndIdx; }
161 /// Initialize the scheduler state for the next scheduling region.
162 void enterRegion(MachineBasicBlock *bb,
163 MachineBasicBlock::iterator begin,
164 MachineBasicBlock::iterator end,
165 unsigned regioninstrs) override;
167 /// Notify that the scheduler has finished scheduling the current region.
168 void exitRegion() override;
170 /// Schedule - Schedule the instruction range using list scheduling.
172 void schedule() override;
174 void EmitSchedule();
176 /// Observe - Update liveness information to account for the current
177 /// instruction, which will not be scheduled.
179 void Observe(MachineInstr &MI, unsigned Count);
181 /// finishBlock - Clean up register live-range state.
183 void finishBlock() override;
185 private:
186 /// Apply each ScheduleDAGMutation step in order.
187 void postprocessDAG();
189 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
190 void ReleaseSuccessors(SUnit *SU);
191 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
192 void ListScheduleTopDown();
194 void dumpSchedule() const;
195 void emitNoop(unsigned CurCycle);
199 char &llvm::PostRASchedulerID = PostRAScheduler::ID;
201 INITIALIZE_PASS(PostRAScheduler, DEBUG_TYPE,
202 "Post RA top-down list latency scheduler", false, false)
204 SchedulePostRATDList::SchedulePostRATDList(
205 MachineFunction &MF, MachineLoopInfo &MLI, AliasAnalysis *AA,
206 const RegisterClassInfo &RCI,
207 TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
208 SmallVectorImpl<const TargetRegisterClass *> &CriticalPathRCs)
209 : ScheduleDAGInstrs(MF, &MLI), AA(AA) {
211 const InstrItineraryData *InstrItins =
212 MF.getSubtarget().getInstrItineraryData();
213 HazardRec =
214 MF.getSubtarget().getInstrInfo()->CreateTargetPostRAHazardRecognizer(
215 InstrItins, this);
216 MF.getSubtarget().getPostRAMutations(Mutations);
218 assert((AntiDepMode == TargetSubtargetInfo::ANTIDEP_NONE ||
219 MRI.tracksLiveness()) &&
220 "Live-ins must be accurate for anti-dependency breaking");
221 AntiDepBreak = ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL)
222 ? createAggressiveAntiDepBreaker(MF, RCI, CriticalPathRCs)
223 : ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL)
224 ? createCriticalAntiDepBreaker(MF, RCI)
225 : nullptr));
228 SchedulePostRATDList::~SchedulePostRATDList() {
229 delete HazardRec;
230 delete AntiDepBreak;
233 /// Initialize state associated with the next scheduling region.
234 void SchedulePostRATDList::enterRegion(MachineBasicBlock *bb,
235 MachineBasicBlock::iterator begin,
236 MachineBasicBlock::iterator end,
237 unsigned regioninstrs) {
238 ScheduleDAGInstrs::enterRegion(bb, begin, end, regioninstrs);
239 Sequence.clear();
242 /// Print the schedule before exiting the region.
243 void SchedulePostRATDList::exitRegion() {
244 LLVM_DEBUG({
245 dbgs() << "*** Final schedule ***\n";
246 dumpSchedule();
247 dbgs() << '\n';
249 ScheduleDAGInstrs::exitRegion();
252 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
253 /// dumpSchedule - dump the scheduled Sequence.
254 LLVM_DUMP_METHOD void SchedulePostRATDList::dumpSchedule() const {
255 for (const SUnit *SU : Sequence) {
256 if (SU)
257 dumpNode(*SU);
258 else
259 dbgs() << "**** NOOP ****\n";
262 #endif
264 bool PostRAScheduler::enablePostRAScheduler(
265 const TargetSubtargetInfo &ST,
266 CodeGenOpt::Level OptLevel,
267 TargetSubtargetInfo::AntiDepBreakMode &Mode,
268 TargetSubtargetInfo::RegClassVector &CriticalPathRCs) const {
269 Mode = ST.getAntiDepBreakMode();
270 ST.getCriticalPathRCs(CriticalPathRCs);
272 // Check for explicit enable/disable of post-ra scheduling.
273 if (EnablePostRAScheduler.getPosition() > 0)
274 return EnablePostRAScheduler;
276 return ST.enablePostRAScheduler() &&
277 OptLevel >= ST.getOptLevelToEnablePostRAScheduler();
280 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
281 if (skipFunction(Fn.getFunction()))
282 return false;
284 TII = Fn.getSubtarget().getInstrInfo();
285 MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
286 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
287 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
289 RegClassInfo.runOnMachineFunction(Fn);
291 TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =
292 TargetSubtargetInfo::ANTIDEP_NONE;
293 SmallVector<const TargetRegisterClass*, 4> CriticalPathRCs;
295 // Check that post-RA scheduling is enabled for this target.
296 // This may upgrade the AntiDepMode.
297 if (!enablePostRAScheduler(Fn.getSubtarget(), PassConfig->getOptLevel(),
298 AntiDepMode, CriticalPathRCs))
299 return false;
301 // Check for antidep breaking override...
302 if (EnableAntiDepBreaking.getPosition() > 0) {
303 AntiDepMode = (EnableAntiDepBreaking == "all")
304 ? TargetSubtargetInfo::ANTIDEP_ALL
305 : ((EnableAntiDepBreaking == "critical")
306 ? TargetSubtargetInfo::ANTIDEP_CRITICAL
307 : TargetSubtargetInfo::ANTIDEP_NONE);
310 LLVM_DEBUG(dbgs() << "PostRAScheduler\n");
312 SchedulePostRATDList Scheduler(Fn, MLI, AA, RegClassInfo, AntiDepMode,
313 CriticalPathRCs);
315 // Loop over all of the basic blocks
316 for (auto &MBB : Fn) {
317 #ifndef NDEBUG
318 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
319 if (DebugDiv > 0) {
320 static int bbcnt = 0;
321 if (bbcnt++ % DebugDiv != DebugMod)
322 continue;
323 dbgs() << "*** DEBUG scheduling " << Fn.getName() << ":"
324 << printMBBReference(MBB) << " ***\n";
326 #endif
328 // Initialize register live-range state for scheduling in this block.
329 Scheduler.startBlock(&MBB);
331 // Schedule each sequence of instructions not interrupted by a label
332 // or anything else that effectively needs to shut down scheduling.
333 MachineBasicBlock::iterator Current = MBB.end();
334 unsigned Count = MBB.size(), CurrentCount = Count;
335 for (MachineBasicBlock::iterator I = Current; I != MBB.begin();) {
336 MachineInstr &MI = *std::prev(I);
337 --Count;
338 // Calls are not scheduling boundaries before register allocation, but
339 // post-ra we don't gain anything by scheduling across calls since we
340 // don't need to worry about register pressure.
341 if (MI.isCall() || TII->isSchedulingBoundary(MI, &MBB, Fn)) {
342 Scheduler.enterRegion(&MBB, I, Current, CurrentCount - Count);
343 Scheduler.setEndIndex(CurrentCount);
344 Scheduler.schedule();
345 Scheduler.exitRegion();
346 Scheduler.EmitSchedule();
347 Current = &MI;
348 CurrentCount = Count;
349 Scheduler.Observe(MI, CurrentCount);
351 I = MI;
352 if (MI.isBundle())
353 Count -= MI.getBundleSize();
355 assert(Count == 0 && "Instruction count mismatch!");
356 assert((MBB.begin() == Current || CurrentCount != 0) &&
357 "Instruction count mismatch!");
358 Scheduler.enterRegion(&MBB, MBB.begin(), Current, CurrentCount);
359 Scheduler.setEndIndex(CurrentCount);
360 Scheduler.schedule();
361 Scheduler.exitRegion();
362 Scheduler.EmitSchedule();
364 // Clean up register live-range state.
365 Scheduler.finishBlock();
367 // Update register kills
368 Scheduler.fixupKills(MBB);
371 return true;
374 /// StartBlock - Initialize register live-range state for scheduling in
375 /// this block.
377 void SchedulePostRATDList::startBlock(MachineBasicBlock *BB) {
378 // Call the superclass.
379 ScheduleDAGInstrs::startBlock(BB);
381 // Reset the hazard recognizer and anti-dep breaker.
382 HazardRec->Reset();
383 if (AntiDepBreak)
384 AntiDepBreak->StartBlock(BB);
387 /// Schedule - Schedule the instruction range using list scheduling.
389 void SchedulePostRATDList::schedule() {
390 // Build the scheduling graph.
391 buildSchedGraph(AA);
393 if (AntiDepBreak) {
394 unsigned Broken =
395 AntiDepBreak->BreakAntiDependencies(SUnits, RegionBegin, RegionEnd,
396 EndIndex, DbgValues);
398 if (Broken != 0) {
399 // We made changes. Update the dependency graph.
400 // Theoretically we could update the graph in place:
401 // When a live range is changed to use a different register, remove
402 // the def's anti-dependence *and* output-dependence edges due to
403 // that register, and add new anti-dependence and output-dependence
404 // edges based on the next live range of the register.
405 ScheduleDAG::clearDAG();
406 buildSchedGraph(AA);
408 NumFixedAnti += Broken;
412 postprocessDAG();
414 LLVM_DEBUG(dbgs() << "********** List Scheduling **********\n");
415 LLVM_DEBUG(dump());
417 AvailableQueue.initNodes(SUnits);
418 ListScheduleTopDown();
419 AvailableQueue.releaseState();
422 /// Observe - Update liveness information to account for the current
423 /// instruction, which will not be scheduled.
425 void SchedulePostRATDList::Observe(MachineInstr &MI, unsigned Count) {
426 if (AntiDepBreak)
427 AntiDepBreak->Observe(MI, Count, EndIndex);
430 /// FinishBlock - Clean up register live-range state.
432 void SchedulePostRATDList::finishBlock() {
433 if (AntiDepBreak)
434 AntiDepBreak->FinishBlock();
436 // Call the superclass.
437 ScheduleDAGInstrs::finishBlock();
440 /// Apply each ScheduleDAGMutation step in order.
441 void SchedulePostRATDList::postprocessDAG() {
442 for (auto &M : Mutations)
443 M->apply(this);
446 //===----------------------------------------------------------------------===//
447 // Top-Down Scheduling
448 //===----------------------------------------------------------------------===//
450 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
451 /// the PendingQueue if the count reaches zero.
452 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
453 SUnit *SuccSU = SuccEdge->getSUnit();
455 if (SuccEdge->isWeak()) {
456 --SuccSU->WeakPredsLeft;
457 return;
459 #ifndef NDEBUG
460 if (SuccSU->NumPredsLeft == 0) {
461 dbgs() << "*** Scheduling failed! ***\n";
462 dumpNode(*SuccSU);
463 dbgs() << " has been released too many times!\n";
464 llvm_unreachable(nullptr);
466 #endif
467 --SuccSU->NumPredsLeft;
469 // Standard scheduler algorithms will recompute the depth of the successor
470 // here as such:
471 // SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
473 // However, we lazily compute node depth instead. Note that
474 // ScheduleNodeTopDown has already updated the depth of this node which causes
475 // all descendents to be marked dirty. Setting the successor depth explicitly
476 // here would cause depth to be recomputed for all its ancestors. If the
477 // successor is not yet ready (because of a transitively redundant edge) then
478 // this causes depth computation to be quadratic in the size of the DAG.
480 // If all the node's predecessors are scheduled, this node is ready
481 // to be scheduled. Ignore the special ExitSU node.
482 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
483 PendingQueue.push_back(SuccSU);
486 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
487 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
488 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
489 I != E; ++I) {
490 ReleaseSucc(SU, &*I);
494 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
495 /// count of its successors. If a successor pending count is zero, add it to
496 /// the Available queue.
497 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
498 LLVM_DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
499 LLVM_DEBUG(dumpNode(*SU));
501 Sequence.push_back(SU);
502 assert(CurCycle >= SU->getDepth() &&
503 "Node scheduled above its depth!");
504 SU->setDepthToAtLeast(CurCycle);
506 ReleaseSuccessors(SU);
507 SU->isScheduled = true;
508 AvailableQueue.scheduledNode(SU);
511 /// emitNoop - Add a noop to the current instruction sequence.
512 void SchedulePostRATDList::emitNoop(unsigned CurCycle) {
513 LLVM_DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
514 HazardRec->EmitNoop();
515 Sequence.push_back(nullptr); // NULL here means noop
516 ++NumNoops;
519 /// ListScheduleTopDown - The main loop of list scheduling for top-down
520 /// schedulers.
521 void SchedulePostRATDList::ListScheduleTopDown() {
522 unsigned CurCycle = 0;
524 // We're scheduling top-down but we're visiting the regions in
525 // bottom-up order, so we don't know the hazards at the start of a
526 // region. So assume no hazards (this should usually be ok as most
527 // blocks are a single region).
528 HazardRec->Reset();
530 // Release any successors of the special Entry node.
531 ReleaseSuccessors(&EntrySU);
533 // Add all leaves to Available queue.
534 for (SUnit &SUnit : SUnits) {
535 // It is available if it has no predecessors.
536 if (!SUnit.NumPredsLeft && !SUnit.isAvailable) {
537 AvailableQueue.push(&SUnit);
538 SUnit.isAvailable = true;
542 // In any cycle where we can't schedule any instructions, we must
543 // stall or emit a noop, depending on the target.
544 bool CycleHasInsts = false;
546 // While Available queue is not empty, grab the node with the highest
547 // priority. If it is not ready put it back. Schedule the node.
548 std::vector<SUnit*> NotReady;
549 Sequence.reserve(SUnits.size());
550 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
551 // Check to see if any of the pending instructions are ready to issue. If
552 // so, add them to the available queue.
553 unsigned MinDepth = ~0u;
554 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
555 if (PendingQueue[i]->getDepth() <= CurCycle) {
556 AvailableQueue.push(PendingQueue[i]);
557 PendingQueue[i]->isAvailable = true;
558 PendingQueue[i] = PendingQueue.back();
559 PendingQueue.pop_back();
560 --i; --e;
561 } else if (PendingQueue[i]->getDepth() < MinDepth)
562 MinDepth = PendingQueue[i]->getDepth();
565 LLVM_DEBUG(dbgs() << "\n*** Examining Available\n";
566 AvailableQueue.dump(this));
568 SUnit *FoundSUnit = nullptr, *NotPreferredSUnit = nullptr;
569 bool HasNoopHazards = false;
570 while (!AvailableQueue.empty()) {
571 SUnit *CurSUnit = AvailableQueue.pop();
573 ScheduleHazardRecognizer::HazardType HT =
574 HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
575 if (HT == ScheduleHazardRecognizer::NoHazard) {
576 if (HazardRec->ShouldPreferAnother(CurSUnit)) {
577 if (!NotPreferredSUnit) {
578 // If this is the first non-preferred node for this cycle, then
579 // record it and continue searching for a preferred node. If this
580 // is not the first non-preferred node, then treat it as though
581 // there had been a hazard.
582 NotPreferredSUnit = CurSUnit;
583 continue;
585 } else {
586 FoundSUnit = CurSUnit;
587 break;
591 // Remember if this is a noop hazard.
592 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
594 NotReady.push_back(CurSUnit);
597 // If we have a non-preferred node, push it back onto the available list.
598 // If we did not find a preferred node, then schedule this first
599 // non-preferred node.
600 if (NotPreferredSUnit) {
601 if (!FoundSUnit) {
602 LLVM_DEBUG(
603 dbgs() << "*** Will schedule a non-preferred instruction...\n");
604 FoundSUnit = NotPreferredSUnit;
605 } else {
606 AvailableQueue.push(NotPreferredSUnit);
609 NotPreferredSUnit = nullptr;
612 // Add the nodes that aren't ready back onto the available list.
613 if (!NotReady.empty()) {
614 AvailableQueue.push_all(NotReady);
615 NotReady.clear();
618 // If we found a node to schedule...
619 if (FoundSUnit) {
620 // If we need to emit noops prior to this instruction, then do so.
621 unsigned NumPreNoops = HazardRec->PreEmitNoops(FoundSUnit);
622 for (unsigned i = 0; i != NumPreNoops; ++i)
623 emitNoop(CurCycle);
625 // ... schedule the node...
626 ScheduleNodeTopDown(FoundSUnit, CurCycle);
627 HazardRec->EmitInstruction(FoundSUnit);
628 CycleHasInsts = true;
629 if (HazardRec->atIssueLimit()) {
630 LLVM_DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle
631 << '\n');
632 HazardRec->AdvanceCycle();
633 ++CurCycle;
634 CycleHasInsts = false;
636 } else {
637 if (CycleHasInsts) {
638 LLVM_DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
639 HazardRec->AdvanceCycle();
640 } else if (!HasNoopHazards) {
641 // Otherwise, we have a pipeline stall, but no other problem,
642 // just advance the current cycle and try again.
643 LLVM_DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
644 HazardRec->AdvanceCycle();
645 ++NumStalls;
646 } else {
647 // Otherwise, we have no instructions to issue and we have instructions
648 // that will fault if we don't do this right. This is the case for
649 // processors without pipeline interlocks and other cases.
650 emitNoop(CurCycle);
653 ++CurCycle;
654 CycleHasInsts = false;
658 #ifndef NDEBUG
659 unsigned ScheduledNodes = VerifyScheduledDAG(/*isBottomUp=*/false);
660 unsigned Noops = llvm::count(Sequence, nullptr);
661 assert(Sequence.size() - Noops == ScheduledNodes &&
662 "The number of nodes scheduled doesn't match the expected number!");
663 #endif // NDEBUG
666 // EmitSchedule - Emit the machine code in scheduled order.
667 void SchedulePostRATDList::EmitSchedule() {
668 RegionBegin = RegionEnd;
670 // If first instruction was a DBG_VALUE then put it back.
671 if (FirstDbgValue)
672 BB->splice(RegionEnd, BB, FirstDbgValue);
674 // Then re-insert them according to the given schedule.
675 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
676 if (SUnit *SU = Sequence[i])
677 BB->splice(RegionEnd, BB, SU->getInstr());
678 else
679 // Null SUnit* is a noop.
680 TII->insertNoop(*BB, RegionEnd);
682 // Update the Begin iterator, as the first instruction in the block
683 // may have been scheduled later.
684 if (i == 0)
685 RegionBegin = std::prev(RegionEnd);
688 // Reinsert any remaining debug_values.
689 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
690 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
691 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
692 MachineInstr *DbgValue = P.first;
693 MachineBasicBlock::iterator OrigPrivMI = P.second;
694 BB->splice(++OrigPrivMI, BB, DbgValue);
696 DbgValues.clear();
697 FirstDbgValue = nullptr;