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.
13 //
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.
17 //
18 //===----------------------------------------------------------------------===//
19
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;
45
46 #define DEBUG_TYPE "post-RA-sched"
47
48 STATISTIC(NumNoops, "Number of noops inserted");
49 STATISTIC(NumStalls, "Number of pipeline stalls");
50 STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
51
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);
64
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);
74
~AntiDepBreaker()75 AntiDepBreaker::~AntiDepBreaker() { }
76
77 namespace {
78 class PostRAScheduler : public MachineFunctionPass {
79 const TargetInstrInfo *TII = nullptr;
80 RegisterClassInfo RegClassInfo;
81
82 public:
83 static char ID;
PostRAScheduler()84 PostRAScheduler() : MachineFunctionPass(ID) {}
85
getAnalysisUsage(AnalysisUsage & AU) const86 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);
95 }
96
getRequiredProperties() const97 MachineFunctionProperties getRequiredProperties() const override {
98 return MachineFunctionProperties().set(
99 MachineFunctionProperties::Property::NoVRegs);
100 }
101
102 bool runOnMachineFunction(MachineFunction &Fn) override;
103
104 private:
105 bool enablePostRAScheduler(
106 const TargetSubtargetInfo &ST, CodeGenOpt::Level OptLevel,
107 TargetSubtargetInfo::AntiDepBreakMode &Mode,
108 TargetSubtargetInfo::RegClassVector &CriticalPathRCs) const;
109 };
110 char PostRAScheduler::ID = 0;
111
112 class SchedulePostRATDList : public ScheduleDAGInstrs {
113 /// AvailableQueue - The priority queue to use for the available SUnits.
114 ///
115 LatencyPriorityQueue AvailableQueue;
116
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;
122
123 /// HazardRec - The hazard recognizer to use.
124 ScheduleHazardRecognizer *HazardRec;
125
126 /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
127 AntiDepBreaker *AntiDepBreak;
128
129 /// AA - AliasAnalysis for making memory reference queries.
130 AliasAnalysis *AA;
131
132 /// The schedule. Null SUnit*'s represent noop instructions.
133 std::vector<SUnit*> Sequence;
134
135 /// Ordered list of DAG postprocessing steps.
136 std::vector<std::unique_ptr<ScheduleDAGMutation>> Mutations;
137
138 /// The index in BB of RegionEnd.
139 ///
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;
143
144 public:
145 SchedulePostRATDList(
146 MachineFunction &MF, MachineLoopInfo &MLI, AliasAnalysis *AA,
147 const RegisterClassInfo &,
148 TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
149 SmallVectorImpl<const TargetRegisterClass *> &CriticalPathRCs);
150
151 ~SchedulePostRATDList() override;
152
153 /// startBlock - Initialize register live-range state for scheduling in
154 /// this block.
155 ///
156 void startBlock(MachineBasicBlock *BB) override;
157
158 // Set the index of RegionEnd within the current BB.
setEndIndex(unsigned EndIdx)159 void setEndIndex(unsigned EndIdx) { EndIndex = EndIdx; }
160
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;
166
167 /// Notify that the scheduler has finished scheduling the current region.
168 void exitRegion() override;
169
170 /// Schedule - Schedule the instruction range using list scheduling.
171 ///
172 void schedule() override;
173
174 void EmitSchedule();
175
176 /// Observe - Update liveness information to account for the current
177 /// instruction, which will not be scheduled.
178 ///
179 void Observe(MachineInstr &MI, unsigned Count);
180
181 /// finishBlock - Clean up register live-range state.
182 ///
183 void finishBlock() override;
184
185 private:
186 /// Apply each ScheduleDAGMutation step in order.
187 void postprocessDAG();
188
189 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
190 void ReleaseSuccessors(SUnit *SU);
191 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
192 void ListScheduleTopDown();
193
194 void dumpSchedule() const;
195 void emitNoop(unsigned CurCycle);
196 };
197 }
198
199 char &llvm::PostRASchedulerID = PostRAScheduler::ID;
200
201 INITIALIZE_PASS(PostRAScheduler, DEBUG_TYPE,
202 "Post RA top-down list latency scheduler", false, false)
203
SchedulePostRATDList(MachineFunction & MF,MachineLoopInfo & MLI,AliasAnalysis * AA,const RegisterClassInfo & RCI,TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,SmallVectorImpl<const TargetRegisterClass * > & CriticalPathRCs)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), EndIndex(0) {
210
211 const InstrItineraryData *InstrItins =
212 MF.getSubtarget().getInstrItineraryData();
213 HazardRec =
214 MF.getSubtarget().getInstrInfo()->CreateTargetPostRAHazardRecognizer(
215 InstrItins, this);
216 MF.getSubtarget().getPostRAMutations(Mutations);
217
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));
226 }
227
~SchedulePostRATDList()228 SchedulePostRATDList::~SchedulePostRATDList() {
229 delete HazardRec;
230 delete AntiDepBreak;
231 }
232
233 /// Initialize state associated with the next scheduling region.
enterRegion(MachineBasicBlock * bb,MachineBasicBlock::iterator begin,MachineBasicBlock::iterator end,unsigned regioninstrs)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();
240 }
241
242 /// Print the schedule before exiting the region.
exitRegion()243 void SchedulePostRATDList::exitRegion() {
244 LLVM_DEBUG({
245 dbgs() << "*** Final schedule ***\n";
246 dumpSchedule();
247 dbgs() << '\n';
248 });
249 ScheduleDAGInstrs::exitRegion();
250 }
251
252 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
253 /// dumpSchedule - dump the scheduled Sequence.
dumpSchedule() const254 LLVM_DUMP_METHOD void SchedulePostRATDList::dumpSchedule() const {
255 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
256 if (SUnit *SU = Sequence[i])
257 dumpNode(*SU);
258 else
259 dbgs() << "**** NOOP ****\n";
260 }
261 }
262 #endif
263
enablePostRAScheduler(const TargetSubtargetInfo & ST,CodeGenOpt::Level OptLevel,TargetSubtargetInfo::AntiDepBreakMode & Mode,TargetSubtargetInfo::RegClassVector & CriticalPathRCs) const264 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);
271
272 // Check for explicit enable/disable of post-ra scheduling.
273 if (EnablePostRAScheduler.getPosition() > 0)
274 return EnablePostRAScheduler;
275
276 return ST.enablePostRAScheduler() &&
277 OptLevel >= ST.getOptLevelToEnablePostRAScheduler();
278 }
279
runOnMachineFunction(MachineFunction & Fn)280 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
281 if (skipFunction(Fn.getFunction()))
282 return false;
283
284 TII = Fn.getSubtarget().getInstrInfo();
285 MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
286 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
287 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
288
289 RegClassInfo.runOnMachineFunction(Fn);
290
291 TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =
292 TargetSubtargetInfo::ANTIDEP_NONE;
293 SmallVector<const TargetRegisterClass*, 4> CriticalPathRCs;
294
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;
300
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);
308 }
309
310 LLVM_DEBUG(dbgs() << "PostRAScheduler\n");
311
312 SchedulePostRATDList Scheduler(Fn, MLI, AA, RegClassInfo, AntiDepMode,
313 CriticalPathRCs);
314
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";
325 }
326 #endif
327
328 // Initialize register live-range state for scheduling in this block.
329 Scheduler.startBlock(&MBB);
330
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);
350 }
351 I = MI;
352 // TODO: this should be upstreamed. What is the test case that broke?
353 if (MI.isBundled())
354 Count -= MI.getBundleSize();
355 }
356 assert(Count == 0 && "Instruction count mismatch!");
357 assert((MBB.begin() == Current || CurrentCount != 0) &&
358 "Instruction count mismatch!");
359 Scheduler.enterRegion(&MBB, MBB.begin(), Current, CurrentCount);
360 Scheduler.setEndIndex(CurrentCount);
361 Scheduler.schedule();
362 Scheduler.exitRegion();
363 Scheduler.EmitSchedule();
364
365 // Clean up register live-range state.
366 Scheduler.finishBlock();
367
368 // Update register kills
369 Scheduler.fixupKills(MBB);
370 }
371
372 return true;
373 }
374
375 /// StartBlock - Initialize register live-range state for scheduling in
376 /// this block.
377 ///
startBlock(MachineBasicBlock * BB)378 void SchedulePostRATDList::startBlock(MachineBasicBlock *BB) {
379 // Call the superclass.
380 ScheduleDAGInstrs::startBlock(BB);
381
382 // Reset the hazard recognizer and anti-dep breaker.
383 HazardRec->Reset();
384 if (AntiDepBreak)
385 AntiDepBreak->StartBlock(BB);
386 }
387
388 /// Schedule - Schedule the instruction range using list scheduling.
389 ///
schedule()390 void SchedulePostRATDList::schedule() {
391 // Build the scheduling graph.
392 buildSchedGraph(AA);
393
394 if (AntiDepBreak) {
395 unsigned Broken =
396 AntiDepBreak->BreakAntiDependencies(SUnits, RegionBegin, RegionEnd,
397 EndIndex, DbgValues);
398
399 if (Broken != 0) {
400 // We made changes. Update the dependency graph.
401 // Theoretically we could update the graph in place:
402 // When a live range is changed to use a different register, remove
403 // the def's anti-dependence *and* output-dependence edges due to
404 // that register, and add new anti-dependence and output-dependence
405 // edges based on the next live range of the register.
406 ScheduleDAG::clearDAG();
407 buildSchedGraph(AA);
408
409 NumFixedAnti += Broken;
410 }
411 }
412
413 postprocessDAG();
414
415 LLVM_DEBUG(dbgs() << "********** List Scheduling **********\n");
416 LLVM_DEBUG(dump());
417
418 AvailableQueue.initNodes(SUnits);
419 ListScheduleTopDown();
420 AvailableQueue.releaseState();
421 }
422
423 /// Observe - Update liveness information to account for the current
424 /// instruction, which will not be scheduled.
425 ///
Observe(MachineInstr & MI,unsigned Count)426 void SchedulePostRATDList::Observe(MachineInstr &MI, unsigned Count) {
427 if (AntiDepBreak)
428 AntiDepBreak->Observe(MI, Count, EndIndex);
429 }
430
431 /// FinishBlock - Clean up register live-range state.
432 ///
finishBlock()433 void SchedulePostRATDList::finishBlock() {
434 if (AntiDepBreak)
435 AntiDepBreak->FinishBlock();
436
437 // Call the superclass.
438 ScheduleDAGInstrs::finishBlock();
439 }
440
441 /// Apply each ScheduleDAGMutation step in order.
postprocessDAG()442 void SchedulePostRATDList::postprocessDAG() {
443 for (auto &M : Mutations)
444 M->apply(this);
445 }
446
447 //===----------------------------------------------------------------------===//
448 // Top-Down Scheduling
449 //===----------------------------------------------------------------------===//
450
451 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
452 /// the PendingQueue if the count reaches zero.
ReleaseSucc(SUnit * SU,SDep * SuccEdge)453 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
454 SUnit *SuccSU = SuccEdge->getSUnit();
455
456 if (SuccEdge->isWeak()) {
457 --SuccSU->WeakPredsLeft;
458 return;
459 }
460 #ifndef NDEBUG
461 if (SuccSU->NumPredsLeft == 0) {
462 dbgs() << "*** Scheduling failed! ***\n";
463 dumpNode(*SuccSU);
464 dbgs() << " has been released too many times!\n";
465 llvm_unreachable(nullptr);
466 }
467 #endif
468 --SuccSU->NumPredsLeft;
469
470 // Standard scheduler algorithms will recompute the depth of the successor
471 // here as such:
472 // SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
473 //
474 // However, we lazily compute node depth instead. Note that
475 // ScheduleNodeTopDown has already updated the depth of this node which causes
476 // all descendents to be marked dirty. Setting the successor depth explicitly
477 // here would cause depth to be recomputed for all its ancestors. If the
478 // successor is not yet ready (because of a transitively redundant edge) then
479 // this causes depth computation to be quadratic in the size of the DAG.
480
481 // If all the node's predecessors are scheduled, this node is ready
482 // to be scheduled. Ignore the special ExitSU node.
483 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
484 PendingQueue.push_back(SuccSU);
485 }
486
487 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
ReleaseSuccessors(SUnit * SU)488 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
489 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
490 I != E; ++I) {
491 ReleaseSucc(SU, &*I);
492 }
493 }
494
495 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
496 /// count of its successors. If a successor pending count is zero, add it to
497 /// the Available queue.
ScheduleNodeTopDown(SUnit * SU,unsigned CurCycle)498 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
499 LLVM_DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
500 LLVM_DEBUG(dumpNode(*SU));
501
502 Sequence.push_back(SU);
503 assert(CurCycle >= SU->getDepth() &&
504 "Node scheduled above its depth!");
505 SU->setDepthToAtLeast(CurCycle);
506
507 ReleaseSuccessors(SU);
508 SU->isScheduled = true;
509 AvailableQueue.scheduledNode(SU);
510 }
511
512 /// emitNoop - Add a noop to the current instruction sequence.
emitNoop(unsigned CurCycle)513 void SchedulePostRATDList::emitNoop(unsigned CurCycle) {
514 LLVM_DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
515 HazardRec->EmitNoop();
516 Sequence.push_back(nullptr); // NULL here means noop
517 ++NumNoops;
518 }
519
520 /// ListScheduleTopDown - The main loop of list scheduling for top-down
521 /// schedulers.
ListScheduleTopDown()522 void SchedulePostRATDList::ListScheduleTopDown() {
523 unsigned CurCycle = 0;
524
525 // We're scheduling top-down but we're visiting the regions in
526 // bottom-up order, so we don't know the hazards at the start of a
527 // region. So assume no hazards (this should usually be ok as most
528 // blocks are a single region).
529 HazardRec->Reset();
530
531 // Release any successors of the special Entry node.
532 ReleaseSuccessors(&EntrySU);
533
534 // Add all leaves to Available queue.
535 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
536 // It is available if it has no predecessors.
537 if (!SUnits[i].NumPredsLeft && !SUnits[i].isAvailable) {
538 AvailableQueue.push(&SUnits[i]);
539 SUnits[i].isAvailable = true;
540 }
541 }
542
543 // In any cycle where we can't schedule any instructions, we must
544 // stall or emit a noop, depending on the target.
545 bool CycleHasInsts = false;
546
547 // While Available queue is not empty, grab the node with the highest
548 // priority. If it is not ready put it back. Schedule the node.
549 std::vector<SUnit*> NotReady;
550 Sequence.reserve(SUnits.size());
551 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
552 // Check to see if any of the pending instructions are ready to issue. If
553 // so, add them to the available queue.
554 unsigned MinDepth = ~0u;
555 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
556 if (PendingQueue[i]->getDepth() <= CurCycle) {
557 AvailableQueue.push(PendingQueue[i]);
558 PendingQueue[i]->isAvailable = true;
559 PendingQueue[i] = PendingQueue.back();
560 PendingQueue.pop_back();
561 --i; --e;
562 } else if (PendingQueue[i]->getDepth() < MinDepth)
563 MinDepth = PendingQueue[i]->getDepth();
564 }
565
566 LLVM_DEBUG(dbgs() << "\n*** Examining Available\n";
567 AvailableQueue.dump(this));
568
569 SUnit *FoundSUnit = nullptr, *NotPreferredSUnit = nullptr;
570 bool HasNoopHazards = false;
571 while (!AvailableQueue.empty()) {
572 SUnit *CurSUnit = AvailableQueue.pop();
573
574 ScheduleHazardRecognizer::HazardType HT =
575 HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
576 if (HT == ScheduleHazardRecognizer::NoHazard) {
577 if (HazardRec->ShouldPreferAnother(CurSUnit)) {
578 if (!NotPreferredSUnit) {
579 // If this is the first non-preferred node for this cycle, then
580 // record it and continue searching for a preferred node. If this
581 // is not the first non-preferred node, then treat it as though
582 // there had been a hazard.
583 NotPreferredSUnit = CurSUnit;
584 continue;
585 }
586 } else {
587 FoundSUnit = CurSUnit;
588 break;
589 }
590 }
591
592 // Remember if this is a noop hazard.
593 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
594
595 NotReady.push_back(CurSUnit);
596 }
597
598 // If we have a non-preferred node, push it back onto the available list.
599 // If we did not find a preferred node, then schedule this first
600 // non-preferred node.
601 if (NotPreferredSUnit) {
602 if (!FoundSUnit) {
603 LLVM_DEBUG(
604 dbgs() << "*** Will schedule a non-preferred instruction...\n");
605 FoundSUnit = NotPreferredSUnit;
606 } else {
607 AvailableQueue.push(NotPreferredSUnit);
608 }
609
610 NotPreferredSUnit = nullptr;
611 }
612
613 // Add the nodes that aren't ready back onto the available list.
614 if (!NotReady.empty()) {
615 AvailableQueue.push_all(NotReady);
616 NotReady.clear();
617 }
618
619 // If we found a node to schedule...
620 if (FoundSUnit) {
621 // If we need to emit noops prior to this instruction, then do so.
622 unsigned NumPreNoops = HazardRec->PreEmitNoops(FoundSUnit);
623 for (unsigned i = 0; i != NumPreNoops; ++i)
624 emitNoop(CurCycle);
625
626 // ... schedule the node...
627 ScheduleNodeTopDown(FoundSUnit, CurCycle);
628 HazardRec->EmitInstruction(FoundSUnit);
629 CycleHasInsts = true;
630 if (HazardRec->atIssueLimit()) {
631 LLVM_DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle
632 << '\n');
633 HazardRec->AdvanceCycle();
634 ++CurCycle;
635 CycleHasInsts = false;
636 }
637 } else {
638 if (CycleHasInsts) {
639 LLVM_DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
640 HazardRec->AdvanceCycle();
641 } else if (!HasNoopHazards) {
642 // Otherwise, we have a pipeline stall, but no other problem,
643 // just advance the current cycle and try again.
644 LLVM_DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
645 HazardRec->AdvanceCycle();
646 ++NumStalls;
647 } else {
648 // Otherwise, we have no instructions to issue and we have instructions
649 // that will fault if we don't do this right. This is the case for
650 // processors without pipeline interlocks and other cases.
651 emitNoop(CurCycle);
652 }
653
654 ++CurCycle;
655 CycleHasInsts = false;
656 }
657 }
658
659 #ifndef NDEBUG
660 unsigned ScheduledNodes = VerifyScheduledDAG(/*isBottomUp=*/false);
661 unsigned Noops = 0;
662 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
663 if (!Sequence[i])
664 ++Noops;
665 assert(Sequence.size() - Noops == ScheduledNodes &&
666 "The number of nodes scheduled doesn't match the expected number!");
667 #endif // NDEBUG
668 }
669
670 // EmitSchedule - Emit the machine code in scheduled order.
EmitSchedule()671 void SchedulePostRATDList::EmitSchedule() {
672 RegionBegin = RegionEnd;
673
674 // If first instruction was a DBG_VALUE then put it back.
675 if (FirstDbgValue)
676 BB->splice(RegionEnd, BB, FirstDbgValue);
677
678 // Then re-insert them according to the given schedule.
679 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
680 if (SUnit *SU = Sequence[i])
681 BB->splice(RegionEnd, BB, SU->getInstr());
682 else
683 // Null SUnit* is a noop.
684 TII->insertNoop(*BB, RegionEnd);
685
686 // Update the Begin iterator, as the first instruction in the block
687 // may have been scheduled later.
688 if (i == 0)
689 RegionBegin = std::prev(RegionEnd);
690 }
691
692 // Reinsert any remaining debug_values.
693 for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
694 DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
695 std::pair<MachineInstr *, MachineInstr *> P = *std::prev(DI);
696 MachineInstr *DbgValue = P.first;
697 MachineBasicBlock::iterator OrigPrivMI = P.second;
698 BB->splice(++OrigPrivMI, BB, DbgValue);
699 }
700 DbgValues.clear();
701 FirstDbgValue = nullptr;
702 }
703