post-ra-sched: Replace a std::set of regs with a bitvector.
[oota-llvm.git] / lib / CodeGen / PostRASchedulerList.cpp
1 //===----- SchedulePostRAList.cpp - list scheduler ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements a top-down list scheduler, using standard algorithms.
11 // The basic approach uses a priority queue of available nodes to schedule.
12 // One at a time, nodes are taken from the priority queue (thus in priority
13 // order), checked for legality to schedule, and emitted if legal.
14 //
15 // Nodes may not be legal to schedule either due to structural hazards (e.g.
16 // pipeline or resource constraints) or because an input to the instruction has
17 // not completed execution.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #define DEBUG_TYPE "post-RA-sched"
22 #include "AntiDepBreaker.h"
23 #include "AggressiveAntiDepBreaker.h"
24 #include "CriticalAntiDepBreaker.h"
25 #include "RegisterClassInfo.h"
26 #include "ScheduleDAGInstrs.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/LatencyPriorityQueue.h"
29 #include "llvm/CodeGen/SchedulerRegistry.h"
30 #include "llvm/CodeGen/MachineDominators.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineLoopInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/ADT/BitVector.h"
47 #include "llvm/ADT/Statistic.h"
48 using namespace llvm;
49
50 STATISTIC(NumNoops, "Number of noops inserted");
51 STATISTIC(NumStalls, "Number of pipeline stalls");
52 STATISTIC(NumFixedAnti, "Number of fixed anti-dependencies");
53
54 // Post-RA scheduling is enabled with
55 // TargetSubtargetInfo.enablePostRAScheduler(). This flag can be used to
56 // override the target.
57 static cl::opt<bool>
58 EnablePostRAScheduler("post-RA-scheduler",
59                        cl::desc("Enable scheduling after register allocation"),
60                        cl::init(false), cl::Hidden);
61 static cl::opt<std::string>
62 EnableAntiDepBreaking("break-anti-dependencies",
63                       cl::desc("Break post-RA scheduling anti-dependencies: "
64                                "\"critical\", \"all\", or \"none\""),
65                       cl::init("none"), cl::Hidden);
66
67 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
68 static cl::opt<int>
69 DebugDiv("postra-sched-debugdiv",
70                       cl::desc("Debug control MBBs that are scheduled"),
71                       cl::init(0), cl::Hidden);
72 static cl::opt<int>
73 DebugMod("postra-sched-debugmod",
74                       cl::desc("Debug control MBBs that are scheduled"),
75                       cl::init(0), cl::Hidden);
76
77 AntiDepBreaker::~AntiDepBreaker() { }
78
79 namespace {
80   class PostRAScheduler : public MachineFunctionPass {
81     AliasAnalysis *AA;
82     const TargetInstrInfo *TII;
83     RegisterClassInfo RegClassInfo;
84
85   public:
86     static char ID;
87     PostRAScheduler() : MachineFunctionPass(ID) {}
88
89     void getAnalysisUsage(AnalysisUsage &AU) const {
90       AU.setPreservesCFG();
91       AU.addRequired<AliasAnalysis>();
92       AU.addRequired<TargetPassConfig>();
93       AU.addRequired<MachineDominatorTree>();
94       AU.addPreserved<MachineDominatorTree>();
95       AU.addRequired<MachineLoopInfo>();
96       AU.addPreserved<MachineLoopInfo>();
97       MachineFunctionPass::getAnalysisUsage(AU);
98     }
99
100     bool runOnMachineFunction(MachineFunction &Fn);
101   };
102   char PostRAScheduler::ID = 0;
103
104   class SchedulePostRATDList : public ScheduleDAGInstrs {
105     /// AvailableQueue - The priority queue to use for the available SUnits.
106     ///
107     LatencyPriorityQueue AvailableQueue;
108
109     /// PendingQueue - This contains all of the instructions whose operands have
110     /// been issued, but their results are not ready yet (due to the latency of
111     /// the operation).  Once the operands becomes available, the instruction is
112     /// added to the AvailableQueue.
113     std::vector<SUnit*> PendingQueue;
114
115     /// Topo - A topological ordering for SUnits.
116     ScheduleDAGTopologicalSort Topo;
117
118     /// HazardRec - The hazard recognizer to use.
119     ScheduleHazardRecognizer *HazardRec;
120
121     /// AntiDepBreak - Anti-dependence breaking object, or NULL if none
122     AntiDepBreaker *AntiDepBreak;
123
124     /// AA - AliasAnalysis for making memory reference queries.
125     AliasAnalysis *AA;
126
127     /// KillIndices - The index of the most recent kill (proceding bottom-up),
128     /// or ~0u if the register is not live.
129     std::vector<unsigned> KillIndices;
130
131   public:
132     SchedulePostRATDList(
133       MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
134       AliasAnalysis *AA, const RegisterClassInfo&,
135       TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
136       SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs);
137
138     ~SchedulePostRATDList();
139
140     /// StartBlock - Initialize register live-range state for scheduling in
141     /// this block.
142     ///
143     void StartBlock(MachineBasicBlock *BB);
144
145     /// Schedule - Schedule the instruction range using list scheduling.
146     ///
147     void Schedule();
148
149     /// Observe - Update liveness information to account for the current
150     /// instruction, which will not be scheduled.
151     ///
152     void Observe(MachineInstr *MI, unsigned Count);
153
154     /// FinishBlock - Clean up register live-range state.
155     ///
156     void FinishBlock();
157
158     /// FixupKills - Fix register kill flags that have been made
159     /// invalid due to scheduling
160     ///
161     void FixupKills(MachineBasicBlock *MBB);
162
163   private:
164     void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
165     void ReleaseSuccessors(SUnit *SU);
166     void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
167     void ListScheduleTopDown();
168     void StartBlockForKills(MachineBasicBlock *BB);
169
170     // ToggleKillFlag - Toggle a register operand kill flag. Other
171     // adjustments may be made to the instruction if necessary. Return
172     // true if the operand has been deleted, false if not.
173     bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
174   };
175 }
176
177 char &llvm::PostRASchedulerID = PostRAScheduler::ID;
178
179 INITIALIZE_PASS(PostRAScheduler, "post-RA-sched",
180                 "Post RA top-down list latency scheduler", false, false)
181
182 SchedulePostRATDList::SchedulePostRATDList(
183   MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
184   AliasAnalysis *AA, const RegisterClassInfo &RCI,
185   TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
186   SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs)
187   : ScheduleDAGInstrs(MF, MLI, MDT, /*IsPostRA=*/true), Topo(SUnits), AA(AA),
188     KillIndices(TRI->getNumRegs())
189 {
190   const TargetMachine &TM = MF.getTarget();
191   const InstrItineraryData *InstrItins = TM.getInstrItineraryData();
192   HazardRec =
193     TM.getInstrInfo()->CreateTargetPostRAHazardRecognizer(InstrItins, this);
194   AntiDepBreak =
195     ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL) ?
196      (AntiDepBreaker *)new AggressiveAntiDepBreaker(MF, RCI, CriticalPathRCs) :
197      ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL) ?
198       (AntiDepBreaker *)new CriticalAntiDepBreaker(MF, RCI) : NULL));
199 }
200
201 SchedulePostRATDList::~SchedulePostRATDList() {
202   delete HazardRec;
203   delete AntiDepBreak;
204 }
205
206 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
207   TII = Fn.getTarget().getInstrInfo();
208   MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
209   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
210   AliasAnalysis *AA = &getAnalysis<AliasAnalysis>();
211   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
212
213   RegClassInfo.runOnMachineFunction(Fn);
214
215   // Check for explicit enable/disable of post-ra scheduling.
216   TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =
217     TargetSubtargetInfo::ANTIDEP_NONE;
218   SmallVector<const TargetRegisterClass*, 4> CriticalPathRCs;
219   if (EnablePostRAScheduler.getPosition() > 0) {
220     if (!EnablePostRAScheduler)
221       return false;
222   } else {
223     // Check that post-RA scheduling is enabled for this target.
224     // This may upgrade the AntiDepMode.
225     const TargetSubtargetInfo &ST = Fn.getTarget().getSubtarget<TargetSubtargetInfo>();
226     if (!ST.enablePostRAScheduler(PassConfig->getOptLevel(), AntiDepMode,
227                                   CriticalPathRCs))
228       return false;
229   }
230
231   // Check for antidep breaking override...
232   if (EnableAntiDepBreaking.getPosition() > 0) {
233     AntiDepMode = (EnableAntiDepBreaking == "all")
234       ? TargetSubtargetInfo::ANTIDEP_ALL
235       : ((EnableAntiDepBreaking == "critical")
236          ? TargetSubtargetInfo::ANTIDEP_CRITICAL
237          : TargetSubtargetInfo::ANTIDEP_NONE);
238   }
239
240   DEBUG(dbgs() << "PostRAScheduler\n");
241
242   SchedulePostRATDList Scheduler(Fn, MLI, MDT, AA, RegClassInfo, AntiDepMode,
243                                  CriticalPathRCs);
244
245   // Loop over all of the basic blocks
246   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
247        MBB != MBBe; ++MBB) {
248 #ifndef NDEBUG
249     // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
250     if (DebugDiv > 0) {
251       static int bbcnt = 0;
252       if (bbcnt++ % DebugDiv != DebugMod)
253         continue;
254       dbgs() << "*** DEBUG scheduling " << Fn.getFunction()->getName()
255              << ":BB#" << MBB->getNumber() << " ***\n";
256     }
257 #endif
258
259     // Initialize register live-range state for scheduling in this block.
260     Scheduler.StartBlock(MBB);
261
262     // Schedule each sequence of instructions not interrupted by a label
263     // or anything else that effectively needs to shut down scheduling.
264     MachineBasicBlock::iterator Current = MBB->end();
265     unsigned Count = MBB->size(), CurrentCount = Count;
266     for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
267       MachineInstr *MI = llvm::prior(I);
268       // Calls are not scheduling boundaries before register allocation, but
269       // post-ra we don't gain anything by scheduling across calls since we
270       // don't need to worry about register pressure.
271       if (MI->isCall() || TII->isSchedulingBoundary(MI, MBB, Fn)) {
272         Scheduler.Run(MBB, I, Current, CurrentCount);
273         Scheduler.EmitSchedule();
274         Current = MI;
275         CurrentCount = Count - 1;
276         Scheduler.Observe(MI, CurrentCount);
277       }
278       I = MI;
279       --Count;
280       if (MI->isBundle())
281         Count -= MI->getBundleSize();
282     }
283     assert(Count == 0 && "Instruction count mismatch!");
284     assert((MBB->begin() == Current || CurrentCount != 0) &&
285            "Instruction count mismatch!");
286     Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
287     Scheduler.EmitSchedule();
288
289     // Clean up register live-range state.
290     Scheduler.FinishBlock();
291
292     // Update register kills
293     Scheduler.FixupKills(MBB);
294   }
295
296   return true;
297 }
298
299 /// StartBlock - Initialize register live-range state for scheduling in
300 /// this block.
301 ///
302 void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
303   // Call the superclass.
304   ScheduleDAGInstrs::StartBlock(BB);
305
306   // Reset the hazard recognizer and anti-dep breaker.
307   HazardRec->Reset();
308   if (AntiDepBreak != NULL)
309     AntiDepBreak->StartBlock(BB);
310 }
311
312 /// Schedule - Schedule the instruction range using list scheduling.
313 ///
314 void SchedulePostRATDList::Schedule() {
315   // Build the scheduling graph.
316   BuildSchedGraph(AA);
317
318   if (AntiDepBreak != NULL) {
319     unsigned Broken =
320       AntiDepBreak->BreakAntiDependencies(SUnits, Begin, InsertPos,
321                                           InsertPosIndex, DbgValues);
322
323     if (Broken != 0) {
324       // We made changes. Update the dependency graph.
325       // Theoretically we could update the graph in place:
326       // When a live range is changed to use a different register, remove
327       // the def's anti-dependence *and* output-dependence edges due to
328       // that register, and add new anti-dependence and output-dependence
329       // edges based on the next live range of the register.
330       SUnits.clear();
331       Sequence.clear();
332       EntrySU = SUnit();
333       ExitSU = SUnit();
334       BuildSchedGraph(AA);
335
336       NumFixedAnti += Broken;
337     }
338   }
339
340   DEBUG(dbgs() << "********** List Scheduling **********\n");
341   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
342           SUnits[su].dumpAll(this));
343
344   AvailableQueue.initNodes(SUnits);
345   ListScheduleTopDown();
346   AvailableQueue.releaseState();
347 }
348
349 /// Observe - Update liveness information to account for the current
350 /// instruction, which will not be scheduled.
351 ///
352 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
353   if (AntiDepBreak != NULL)
354     AntiDepBreak->Observe(MI, Count, InsertPosIndex);
355 }
356
357 /// FinishBlock - Clean up register live-range state.
358 ///
359 void SchedulePostRATDList::FinishBlock() {
360   if (AntiDepBreak != NULL)
361     AntiDepBreak->FinishBlock();
362
363   // Call the superclass.
364   ScheduleDAGInstrs::FinishBlock();
365 }
366
367 /// StartBlockForKills - Initialize register live-range state for updating kills
368 ///
369 void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
370   // Initialize the indices to indicate that no registers are live.
371   for (unsigned i = 0; i < TRI->getNumRegs(); ++i)
372     KillIndices[i] = ~0u;
373
374   // Determine the live-out physregs for this block.
375   if (!BB->empty() && BB->back().isReturn()) {
376     // In a return block, examine the function live-out regs.
377     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
378            E = MRI.liveout_end(); I != E; ++I) {
379       unsigned Reg = *I;
380       KillIndices[Reg] = BB->size();
381       // Repeat, for all subregs.
382       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
383            *Subreg; ++Subreg) {
384         KillIndices[*Subreg] = BB->size();
385       }
386     }
387   }
388   else {
389     // In a non-return block, examine the live-in regs of all successors.
390     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
391            SE = BB->succ_end(); SI != SE; ++SI) {
392       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
393              E = (*SI)->livein_end(); I != E; ++I) {
394         unsigned Reg = *I;
395         KillIndices[Reg] = BB->size();
396         // Repeat, for all subregs.
397         for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
398              *Subreg; ++Subreg) {
399           KillIndices[*Subreg] = BB->size();
400         }
401       }
402     }
403   }
404 }
405
406 bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
407                                           MachineOperand &MO) {
408   // Setting kill flag...
409   if (!MO.isKill()) {
410     MO.setIsKill(true);
411     return false;
412   }
413
414   // If MO itself is live, clear the kill flag...
415   if (KillIndices[MO.getReg()] != ~0u) {
416     MO.setIsKill(false);
417     return false;
418   }
419
420   // If any subreg of MO is live, then create an imp-def for that
421   // subreg and keep MO marked as killed.
422   MO.setIsKill(false);
423   bool AllDead = true;
424   const unsigned SuperReg = MO.getReg();
425   for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
426        *Subreg; ++Subreg) {
427     if (KillIndices[*Subreg] != ~0u) {
428       MI->addOperand(MachineOperand::CreateReg(*Subreg,
429                                                true  /*IsDef*/,
430                                                true  /*IsImp*/,
431                                                false /*IsKill*/,
432                                                false /*IsDead*/));
433       AllDead = false;
434     }
435   }
436
437   if(AllDead)
438     MO.setIsKill(true);
439   return false;
440 }
441
442 /// FixupKills - Fix the register kill flags, they may have been made
443 /// incorrect by instruction reordering.
444 ///
445 void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
446   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
447
448   BitVector killedRegs(TRI->getNumRegs());
449   BitVector ReservedRegs = TRI->getReservedRegs(MF);
450
451   StartBlockForKills(MBB);
452
453   // Examine block from end to start...
454   unsigned Count = MBB->size();
455   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
456        I != E; --Count) {
457     MachineInstr *MI = --I;
458     if (MI->isDebugValue())
459       continue;
460
461     // Update liveness.  Registers that are defed but not used in this
462     // instruction are now dead. Mark register and all subregs as they
463     // are completely defined.
464     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
465       MachineOperand &MO = MI->getOperand(i);
466       if (MO.isRegMask())
467         for (unsigned i = 0, e = TRI->getNumRegs(); i != e; ++i)
468           if (MO.clobbersPhysReg(i))
469             KillIndices[i] = ~0u;
470       if (!MO.isReg()) continue;
471       unsigned Reg = MO.getReg();
472       if (Reg == 0) continue;
473       if (!MO.isDef()) continue;
474       // Ignore two-addr defs.
475       if (MI->isRegTiedToUseOperand(i)) continue;
476
477       KillIndices[Reg] = ~0u;
478
479       // Repeat for all subregs.
480       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
481            *Subreg; ++Subreg) {
482         KillIndices[*Subreg] = ~0u;
483       }
484     }
485
486     // Examine all used registers and set/clear kill flag. When a
487     // register is used multiple times we only set the kill flag on
488     // the first use.
489     killedRegs.reset();
490     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
491       MachineOperand &MO = MI->getOperand(i);
492       if (!MO.isReg() || !MO.isUse()) continue;
493       unsigned Reg = MO.getReg();
494       if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
495
496       bool kill = false;
497       if (!killedRegs.test(Reg)) {
498         kill = true;
499         // A register is not killed if any subregs are live...
500         for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
501              *Subreg; ++Subreg) {
502           if (KillIndices[*Subreg] != ~0u) {
503             kill = false;
504             break;
505           }
506         }
507
508         // If subreg is not live, then register is killed if it became
509         // live in this instruction
510         if (kill)
511           kill = (KillIndices[Reg] == ~0u);
512       }
513
514       if (MO.isKill() != kill) {
515         DEBUG(dbgs() << "Fixing " << MO << " in ");
516         // Warning: ToggleKillFlag may invalidate MO.
517         ToggleKillFlag(MI, MO);
518         DEBUG(MI->dump());
519       }
520
521       killedRegs.set(Reg);
522     }
523
524     // Mark any used register (that is not using undef) and subregs as
525     // now live...
526     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
527       MachineOperand &MO = MI->getOperand(i);
528       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
529       unsigned Reg = MO.getReg();
530       if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
531
532       KillIndices[Reg] = Count;
533
534       for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
535            *Subreg; ++Subreg) {
536         KillIndices[*Subreg] = Count;
537       }
538     }
539   }
540 }
541
542 //===----------------------------------------------------------------------===//
543 //  Top-Down Scheduling
544 //===----------------------------------------------------------------------===//
545
546 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
547 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
548 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
549   SUnit *SuccSU = SuccEdge->getSUnit();
550
551 #ifndef NDEBUG
552   if (SuccSU->NumPredsLeft == 0) {
553     dbgs() << "*** Scheduling failed! ***\n";
554     SuccSU->dump(this);
555     dbgs() << " has been released too many times!\n";
556     llvm_unreachable(0);
557   }
558 #endif
559   --SuccSU->NumPredsLeft;
560
561   // Standard scheduler algorithms will recompute the depth of the successor
562   // here as such:
563   //   SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
564   //
565   // However, we lazily compute node depth instead. Note that
566   // ScheduleNodeTopDown has already updated the depth of this node which causes
567   // all descendents to be marked dirty. Setting the successor depth explicitly
568   // here would cause depth to be recomputed for all its ancestors. If the
569   // successor is not yet ready (because of a transitively redundant edge) then
570   // this causes depth computation to be quadratic in the size of the DAG.
571
572   // If all the node's predecessors are scheduled, this node is ready
573   // to be scheduled. Ignore the special ExitSU node.
574   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
575     PendingQueue.push_back(SuccSU);
576 }
577
578 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
579 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
580   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
581        I != E; ++I) {
582     ReleaseSucc(SU, &*I);
583   }
584 }
585
586 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
587 /// count of its successors. If a successor pending count is zero, add it to
588 /// the Available queue.
589 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
590   DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
591   DEBUG(SU->dump(this));
592
593   Sequence.push_back(SU);
594   assert(CurCycle >= SU->getDepth() &&
595          "Node scheduled above its depth!");
596   SU->setDepthToAtLeast(CurCycle);
597
598   ReleaseSuccessors(SU);
599   SU->isScheduled = true;
600   AvailableQueue.ScheduledNode(SU);
601 }
602
603 /// ListScheduleTopDown - The main loop of list scheduling for top-down
604 /// schedulers.
605 void SchedulePostRATDList::ListScheduleTopDown() {
606   unsigned CurCycle = 0;
607
608   // We're scheduling top-down but we're visiting the regions in
609   // bottom-up order, so we don't know the hazards at the start of a
610   // region. So assume no hazards (this should usually be ok as most
611   // blocks are a single region).
612   HazardRec->Reset();
613
614   // Release any successors of the special Entry node.
615   ReleaseSuccessors(&EntrySU);
616
617   // Add all leaves to Available queue.
618   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
619     // It is available if it has no predecessors.
620     bool available = SUnits[i].Preds.empty();
621     if (available) {
622       AvailableQueue.push(&SUnits[i]);
623       SUnits[i].isAvailable = true;
624     }
625   }
626
627   // In any cycle where we can't schedule any instructions, we must
628   // stall or emit a noop, depending on the target.
629   bool CycleHasInsts = false;
630
631   // While Available queue is not empty, grab the node with the highest
632   // priority. If it is not ready put it back.  Schedule the node.
633   std::vector<SUnit*> NotReady;
634   Sequence.reserve(SUnits.size());
635   while (!AvailableQueue.empty() || !PendingQueue.empty()) {
636     // Check to see if any of the pending instructions are ready to issue.  If
637     // so, add them to the available queue.
638     unsigned MinDepth = ~0u;
639     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
640       if (PendingQueue[i]->getDepth() <= CurCycle) {
641         AvailableQueue.push(PendingQueue[i]);
642         PendingQueue[i]->isAvailable = true;
643         PendingQueue[i] = PendingQueue.back();
644         PendingQueue.pop_back();
645         --i; --e;
646       } else if (PendingQueue[i]->getDepth() < MinDepth)
647         MinDepth = PendingQueue[i]->getDepth();
648     }
649
650     DEBUG(dbgs() << "\n*** Examining Available\n"; AvailableQueue.dump(this));
651
652     SUnit *FoundSUnit = 0;
653     bool HasNoopHazards = false;
654     while (!AvailableQueue.empty()) {
655       SUnit *CurSUnit = AvailableQueue.pop();
656
657       ScheduleHazardRecognizer::HazardType HT =
658         HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
659       if (HT == ScheduleHazardRecognizer::NoHazard) {
660         FoundSUnit = CurSUnit;
661         break;
662       }
663
664       // Remember if this is a noop hazard.
665       HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
666
667       NotReady.push_back(CurSUnit);
668     }
669
670     // Add the nodes that aren't ready back onto the available list.
671     if (!NotReady.empty()) {
672       AvailableQueue.push_all(NotReady);
673       NotReady.clear();
674     }
675
676     // If we found a node to schedule...
677     if (FoundSUnit) {
678       // ... schedule the node...
679       ScheduleNodeTopDown(FoundSUnit, CurCycle);
680       HazardRec->EmitInstruction(FoundSUnit);
681       CycleHasInsts = true;
682       if (HazardRec->atIssueLimit()) {
683         DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle << '\n');
684         HazardRec->AdvanceCycle();
685         ++CurCycle;
686         CycleHasInsts = false;
687       }
688     } else {
689       if (CycleHasInsts) {
690         DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
691         HazardRec->AdvanceCycle();
692       } else if (!HasNoopHazards) {
693         // Otherwise, we have a pipeline stall, but no other problem,
694         // just advance the current cycle and try again.
695         DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
696         HazardRec->AdvanceCycle();
697         ++NumStalls;
698       } else {
699         // Otherwise, we have no instructions to issue and we have instructions
700         // that will fault if we don't do this right.  This is the case for
701         // processors without pipeline interlocks and other cases.
702         DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
703         HazardRec->EmitNoop();
704         Sequence.push_back(0);   // NULL here means noop
705         ++NumNoops;
706       }
707
708       ++CurCycle;
709       CycleHasInsts = false;
710     }
711   }
712
713 #ifndef NDEBUG
714   VerifySchedule(/*isBottomUp=*/false);
715 #endif
716 }