misched preparation: modularize schedule emission.
[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     /// LiveRegs - true if the register is live.
128     BitVector LiveRegs;
129
130   public:
131     SchedulePostRATDList(
132       MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
133       AliasAnalysis *AA, const RegisterClassInfo&,
134       TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
135       SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs);
136
137     ~SchedulePostRATDList();
138
139     /// StartBlock - Initialize register live-range state for scheduling in
140     /// this block.
141     ///
142     void StartBlock(MachineBasicBlock *BB);
143
144     /// Schedule - Schedule the instruction range using list scheduling.
145     ///
146     void Schedule();
147
148     void EmitSchedule();
149
150     /// Observe - Update liveness information to account for the current
151     /// instruction, which will not be scheduled.
152     ///
153     void Observe(MachineInstr *MI, unsigned Count);
154
155     /// FinishBlock - Clean up register live-range state.
156     ///
157     void FinishBlock();
158
159     /// FixupKills - Fix register kill flags that have been made
160     /// invalid due to scheduling
161     ///
162     void FixupKills(MachineBasicBlock *MBB);
163
164   private:
165     void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
166     void ReleaseSuccessors(SUnit *SU);
167     void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
168     void ListScheduleTopDown();
169     void StartBlockForKills(MachineBasicBlock *BB);
170
171     // ToggleKillFlag - Toggle a register operand kill flag. Other
172     // adjustments may be made to the instruction if necessary. Return
173     // true if the operand has been deleted, false if not.
174     bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
175
176     void dumpSchedule() const;
177   };
178 }
179
180 char &llvm::PostRASchedulerID = PostRAScheduler::ID;
181
182 INITIALIZE_PASS(PostRAScheduler, "post-RA-sched",
183                 "Post RA top-down list latency scheduler", false, false)
184
185 SchedulePostRATDList::SchedulePostRATDList(
186   MachineFunction &MF, MachineLoopInfo &MLI, MachineDominatorTree &MDT,
187   AliasAnalysis *AA, const RegisterClassInfo &RCI,
188   TargetSubtargetInfo::AntiDepBreakMode AntiDepMode,
189   SmallVectorImpl<const TargetRegisterClass*> &CriticalPathRCs)
190   : ScheduleDAGInstrs(MF, MLI, MDT, /*IsPostRA=*/true), Topo(SUnits), AA(AA),
191     LiveRegs(TRI->getNumRegs())
192 {
193   const TargetMachine &TM = MF.getTarget();
194   const InstrItineraryData *InstrItins = TM.getInstrItineraryData();
195   HazardRec =
196     TM.getInstrInfo()->CreateTargetPostRAHazardRecognizer(InstrItins, this);
197   AntiDepBreak =
198     ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_ALL) ?
199      (AntiDepBreaker *)new AggressiveAntiDepBreaker(MF, RCI, CriticalPathRCs) :
200      ((AntiDepMode == TargetSubtargetInfo::ANTIDEP_CRITICAL) ?
201       (AntiDepBreaker *)new CriticalAntiDepBreaker(MF, RCI) : NULL));
202 }
203
204 SchedulePostRATDList::~SchedulePostRATDList() {
205   delete HazardRec;
206   delete AntiDepBreak;
207 }
208
209 /// dumpSchedule - dump the scheduled Sequence.
210 void SchedulePostRATDList::dumpSchedule() const {
211   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
212     if (SUnit *SU = Sequence[i])
213       SU->dump(this);
214     else
215       dbgs() << "**** NOOP ****\n";
216   }
217 }
218
219 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
220   TII = Fn.getTarget().getInstrInfo();
221   MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
222   MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
223   AliasAnalysis *AA = &getAnalysis<AliasAnalysis>();
224   TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
225
226   RegClassInfo.runOnMachineFunction(Fn);
227
228   // Check for explicit enable/disable of post-ra scheduling.
229   TargetSubtargetInfo::AntiDepBreakMode AntiDepMode =
230     TargetSubtargetInfo::ANTIDEP_NONE;
231   SmallVector<const TargetRegisterClass*, 4> CriticalPathRCs;
232   if (EnablePostRAScheduler.getPosition() > 0) {
233     if (!EnablePostRAScheduler)
234       return false;
235   } else {
236     // Check that post-RA scheduling is enabled for this target.
237     // This may upgrade the AntiDepMode.
238     const TargetSubtargetInfo &ST = Fn.getTarget().getSubtarget<TargetSubtargetInfo>();
239     if (!ST.enablePostRAScheduler(PassConfig->getOptLevel(), AntiDepMode,
240                                   CriticalPathRCs))
241       return false;
242   }
243
244   // Check for antidep breaking override...
245   if (EnableAntiDepBreaking.getPosition() > 0) {
246     AntiDepMode = (EnableAntiDepBreaking == "all")
247       ? TargetSubtargetInfo::ANTIDEP_ALL
248       : ((EnableAntiDepBreaking == "critical")
249          ? TargetSubtargetInfo::ANTIDEP_CRITICAL
250          : TargetSubtargetInfo::ANTIDEP_NONE);
251   }
252
253   DEBUG(dbgs() << "PostRAScheduler\n");
254
255   SchedulePostRATDList Scheduler(Fn, MLI, MDT, AA, RegClassInfo, AntiDepMode,
256                                  CriticalPathRCs);
257
258   // Loop over all of the basic blocks
259   for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
260        MBB != MBBe; ++MBB) {
261 #ifndef NDEBUG
262     // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
263     if (DebugDiv > 0) {
264       static int bbcnt = 0;
265       if (bbcnt++ % DebugDiv != DebugMod)
266         continue;
267       dbgs() << "*** DEBUG scheduling " << Fn.getFunction()->getName()
268              << ":BB#" << MBB->getNumber() << " ***\n";
269     }
270 #endif
271
272     // Initialize register live-range state for scheduling in this block.
273     Scheduler.StartBlock(MBB);
274
275     // Schedule each sequence of instructions not interrupted by a label
276     // or anything else that effectively needs to shut down scheduling.
277     MachineBasicBlock::iterator Current = MBB->end();
278     unsigned Count = MBB->size(), CurrentCount = Count;
279     for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
280       MachineInstr *MI = llvm::prior(I);
281       // Calls are not scheduling boundaries before register allocation, but
282       // post-ra we don't gain anything by scheduling across calls since we
283       // don't need to worry about register pressure.
284       if (MI->isCall() || TII->isSchedulingBoundary(MI, MBB, Fn)) {
285         Scheduler.Run(MBB, I, Current, CurrentCount);
286         Scheduler.EmitSchedule();
287         Current = MI;
288         CurrentCount = Count - 1;
289         Scheduler.Observe(MI, CurrentCount);
290       }
291       I = MI;
292       --Count;
293       if (MI->isBundle())
294         Count -= MI->getBundleSize();
295     }
296     assert(Count == 0 && "Instruction count mismatch!");
297     assert((MBB->begin() == Current || CurrentCount != 0) &&
298            "Instruction count mismatch!");
299     Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
300     Scheduler.EmitSchedule();
301
302     // Clean up register live-range state.
303     Scheduler.FinishBlock();
304
305     // Update register kills
306     Scheduler.FixupKills(MBB);
307   }
308
309   return true;
310 }
311
312 /// StartBlock - Initialize register live-range state for scheduling in
313 /// this block.
314 ///
315 void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
316   // Call the superclass.
317   ScheduleDAGInstrs::StartBlock(BB);
318
319   // Reset the hazard recognizer and anti-dep breaker.
320   HazardRec->Reset();
321   if (AntiDepBreak != NULL)
322     AntiDepBreak->StartBlock(BB);
323 }
324
325 /// Schedule - Schedule the instruction range using list scheduling.
326 ///
327 void SchedulePostRATDList::Schedule() {
328   // Build the scheduling graph.
329   BuildSchedGraph(AA);
330
331   if (AntiDepBreak != NULL) {
332     unsigned Broken =
333       AntiDepBreak->BreakAntiDependencies(SUnits, Begin, InsertPos,
334                                           InsertPosIndex, DbgValues);
335
336     if (Broken != 0) {
337       // We made changes. Update the dependency graph.
338       // Theoretically we could update the graph in place:
339       // When a live range is changed to use a different register, remove
340       // the def's anti-dependence *and* output-dependence edges due to
341       // that register, and add new anti-dependence and output-dependence
342       // edges based on the next live range of the register.
343       SUnits.clear();
344       Sequence.clear();
345       EntrySU = SUnit();
346       ExitSU = SUnit();
347       BuildSchedGraph(AA);
348
349       NumFixedAnti += Broken;
350     }
351   }
352
353   DEBUG(dbgs() << "********** List Scheduling **********\n");
354   DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
355           SUnits[su].dumpAll(this));
356
357   AvailableQueue.initNodes(SUnits);
358   ListScheduleTopDown();
359   AvailableQueue.releaseState();
360
361   DEBUG({
362       dbgs() << "*** Final schedule ***\n";
363       dumpSchedule();
364       dbgs() << '\n';
365     });
366 }
367
368 /// Observe - Update liveness information to account for the current
369 /// instruction, which will not be scheduled.
370 ///
371 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
372   if (AntiDepBreak != NULL)
373     AntiDepBreak->Observe(MI, Count, InsertPosIndex);
374 }
375
376 /// FinishBlock - Clean up register live-range state.
377 ///
378 void SchedulePostRATDList::FinishBlock() {
379   if (AntiDepBreak != NULL)
380     AntiDepBreak->FinishBlock();
381
382   // Call the superclass.
383   ScheduleDAGInstrs::FinishBlock();
384 }
385
386 /// StartBlockForKills - Initialize register live-range state for updating kills
387 ///
388 void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
389   // Start with no live registers.
390   LiveRegs.reset();
391
392   // Determine the live-out physregs for this block.
393   if (!BB->empty() && BB->back().isReturn()) {
394     // In a return block, examine the function live-out regs.
395     for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
396            E = MRI.liveout_end(); I != E; ++I) {
397       unsigned Reg = *I;
398       LiveRegs.set(Reg);
399       // Repeat, for all subregs.
400       for (const uint16_t *Subreg = TRI->getSubRegisters(Reg);
401            *Subreg; ++Subreg)
402         LiveRegs.set(*Subreg);
403     }
404   }
405   else {
406     // In a non-return block, examine the live-in regs of all successors.
407     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
408            SE = BB->succ_end(); SI != SE; ++SI) {
409       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
410              E = (*SI)->livein_end(); I != E; ++I) {
411         unsigned Reg = *I;
412         LiveRegs.set(Reg);
413         // Repeat, for all subregs.
414         for (const uint16_t *Subreg = TRI->getSubRegisters(Reg);
415              *Subreg; ++Subreg)
416           LiveRegs.set(*Subreg);
417       }
418     }
419   }
420 }
421
422 bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
423                                           MachineOperand &MO) {
424   // Setting kill flag...
425   if (!MO.isKill()) {
426     MO.setIsKill(true);
427     return false;
428   }
429
430   // If MO itself is live, clear the kill flag...
431   if (LiveRegs.test(MO.getReg())) {
432     MO.setIsKill(false);
433     return false;
434   }
435
436   // If any subreg of MO is live, then create an imp-def for that
437   // subreg and keep MO marked as killed.
438   MO.setIsKill(false);
439   bool AllDead = true;
440   const unsigned SuperReg = MO.getReg();
441   for (const uint16_t *Subreg = TRI->getSubRegisters(SuperReg);
442        *Subreg; ++Subreg) {
443     if (LiveRegs.test(*Subreg)) {
444       MI->addOperand(MachineOperand::CreateReg(*Subreg,
445                                                true  /*IsDef*/,
446                                                true  /*IsImp*/,
447                                                false /*IsKill*/,
448                                                false /*IsDead*/));
449       AllDead = false;
450     }
451   }
452
453   if(AllDead)
454     MO.setIsKill(true);
455   return false;
456 }
457
458 /// FixupKills - Fix the register kill flags, they may have been made
459 /// incorrect by instruction reordering.
460 ///
461 void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
462   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
463
464   BitVector killedRegs(TRI->getNumRegs());
465   BitVector ReservedRegs = TRI->getReservedRegs(MF);
466
467   StartBlockForKills(MBB);
468
469   // Examine block from end to start...
470   unsigned Count = MBB->size();
471   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
472        I != E; --Count) {
473     MachineInstr *MI = --I;
474     if (MI->isDebugValue())
475       continue;
476
477     // Update liveness.  Registers that are defed but not used in this
478     // instruction are now dead. Mark register and all subregs as they
479     // are completely defined.
480     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
481       MachineOperand &MO = MI->getOperand(i);
482       if (MO.isRegMask())
483         LiveRegs.clearBitsNotInMask(MO.getRegMask());
484       if (!MO.isReg()) continue;
485       unsigned Reg = MO.getReg();
486       if (Reg == 0) continue;
487       if (!MO.isDef()) continue;
488       // Ignore two-addr defs.
489       if (MI->isRegTiedToUseOperand(i)) continue;
490
491       LiveRegs.reset(Reg);
492
493       // Repeat for all subregs.
494       for (const uint16_t *Subreg = TRI->getSubRegisters(Reg);
495            *Subreg; ++Subreg)
496         LiveRegs.reset(*Subreg);
497     }
498
499     // Examine all used registers and set/clear kill flag. When a
500     // register is used multiple times we only set the kill flag on
501     // the first use.
502     killedRegs.reset();
503     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
504       MachineOperand &MO = MI->getOperand(i);
505       if (!MO.isReg() || !MO.isUse()) continue;
506       unsigned Reg = MO.getReg();
507       if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
508
509       bool kill = false;
510       if (!killedRegs.test(Reg)) {
511         kill = true;
512         // A register is not killed if any subregs are live...
513         for (const uint16_t *Subreg = TRI->getSubRegisters(Reg);
514              *Subreg; ++Subreg) {
515           if (LiveRegs.test(*Subreg)) {
516             kill = false;
517             break;
518           }
519         }
520
521         // If subreg is not live, then register is killed if it became
522         // live in this instruction
523         if (kill)
524           kill = !LiveRegs.test(Reg);
525       }
526
527       if (MO.isKill() != kill) {
528         DEBUG(dbgs() << "Fixing " << MO << " in ");
529         // Warning: ToggleKillFlag may invalidate MO.
530         ToggleKillFlag(MI, MO);
531         DEBUG(MI->dump());
532       }
533
534       killedRegs.set(Reg);
535     }
536
537     // Mark any used register (that is not using undef) and subregs as
538     // now live...
539     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
540       MachineOperand &MO = MI->getOperand(i);
541       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
542       unsigned Reg = MO.getReg();
543       if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
544
545       LiveRegs.set(Reg);
546
547       for (const uint16_t *Subreg = TRI->getSubRegisters(Reg);
548            *Subreg; ++Subreg)
549         LiveRegs.set(*Subreg);
550     }
551   }
552 }
553
554 //===----------------------------------------------------------------------===//
555 //  Top-Down Scheduling
556 //===----------------------------------------------------------------------===//
557
558 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
559 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
560 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
561   SUnit *SuccSU = SuccEdge->getSUnit();
562
563 #ifndef NDEBUG
564   if (SuccSU->NumPredsLeft == 0) {
565     dbgs() << "*** Scheduling failed! ***\n";
566     SuccSU->dump(this);
567     dbgs() << " has been released too many times!\n";
568     llvm_unreachable(0);
569   }
570 #endif
571   --SuccSU->NumPredsLeft;
572
573   // Standard scheduler algorithms will recompute the depth of the successor
574   // here as such:
575   //   SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
576   //
577   // However, we lazily compute node depth instead. Note that
578   // ScheduleNodeTopDown has already updated the depth of this node which causes
579   // all descendents to be marked dirty. Setting the successor depth explicitly
580   // here would cause depth to be recomputed for all its ancestors. If the
581   // successor is not yet ready (because of a transitively redundant edge) then
582   // this causes depth computation to be quadratic in the size of the DAG.
583
584   // If all the node's predecessors are scheduled, this node is ready
585   // to be scheduled. Ignore the special ExitSU node.
586   if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
587     PendingQueue.push_back(SuccSU);
588 }
589
590 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
591 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
592   for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
593        I != E; ++I) {
594     ReleaseSucc(SU, &*I);
595   }
596 }
597
598 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
599 /// count of its successors. If a successor pending count is zero, add it to
600 /// the Available queue.
601 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
602   DEBUG(dbgs() << "*** Scheduling [" << CurCycle << "]: ");
603   DEBUG(SU->dump(this));
604
605   Sequence.push_back(SU);
606   assert(CurCycle >= SU->getDepth() &&
607          "Node scheduled above its depth!");
608   SU->setDepthToAtLeast(CurCycle);
609
610   ReleaseSuccessors(SU);
611   SU->isScheduled = true;
612   AvailableQueue.ScheduledNode(SU);
613 }
614
615 /// ListScheduleTopDown - The main loop of list scheduling for top-down
616 /// schedulers.
617 void SchedulePostRATDList::ListScheduleTopDown() {
618   unsigned CurCycle = 0;
619
620   // We're scheduling top-down but we're visiting the regions in
621   // bottom-up order, so we don't know the hazards at the start of a
622   // region. So assume no hazards (this should usually be ok as most
623   // blocks are a single region).
624   HazardRec->Reset();
625
626   // Release any successors of the special Entry node.
627   ReleaseSuccessors(&EntrySU);
628
629   // Add all leaves to Available queue.
630   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
631     // It is available if it has no predecessors.
632     bool available = SUnits[i].Preds.empty();
633     if (available) {
634       AvailableQueue.push(&SUnits[i]);
635       SUnits[i].isAvailable = true;
636     }
637   }
638
639   // In any cycle where we can't schedule any instructions, we must
640   // stall or emit a noop, depending on the target.
641   bool CycleHasInsts = false;
642
643   // While Available queue is not empty, grab the node with the highest
644   // priority. If it is not ready put it back.  Schedule the node.
645   std::vector<SUnit*> NotReady;
646   Sequence.reserve(SUnits.size());
647   while (!AvailableQueue.empty() || !PendingQueue.empty()) {
648     // Check to see if any of the pending instructions are ready to issue.  If
649     // so, add them to the available queue.
650     unsigned MinDepth = ~0u;
651     for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
652       if (PendingQueue[i]->getDepth() <= CurCycle) {
653         AvailableQueue.push(PendingQueue[i]);
654         PendingQueue[i]->isAvailable = true;
655         PendingQueue[i] = PendingQueue.back();
656         PendingQueue.pop_back();
657         --i; --e;
658       } else if (PendingQueue[i]->getDepth() < MinDepth)
659         MinDepth = PendingQueue[i]->getDepth();
660     }
661
662     DEBUG(dbgs() << "\n*** Examining Available\n"; AvailableQueue.dump(this));
663
664     SUnit *FoundSUnit = 0;
665     bool HasNoopHazards = false;
666     while (!AvailableQueue.empty()) {
667       SUnit *CurSUnit = AvailableQueue.pop();
668
669       ScheduleHazardRecognizer::HazardType HT =
670         HazardRec->getHazardType(CurSUnit, 0/*no stalls*/);
671       if (HT == ScheduleHazardRecognizer::NoHazard) {
672         FoundSUnit = CurSUnit;
673         break;
674       }
675
676       // Remember if this is a noop hazard.
677       HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
678
679       NotReady.push_back(CurSUnit);
680     }
681
682     // Add the nodes that aren't ready back onto the available list.
683     if (!NotReady.empty()) {
684       AvailableQueue.push_all(NotReady);
685       NotReady.clear();
686     }
687
688     // If we found a node to schedule...
689     if (FoundSUnit) {
690       // ... schedule the node...
691       ScheduleNodeTopDown(FoundSUnit, CurCycle);
692       HazardRec->EmitInstruction(FoundSUnit);
693       CycleHasInsts = true;
694       if (HazardRec->atIssueLimit()) {
695         DEBUG(dbgs() << "*** Max instructions per cycle " << CurCycle << '\n');
696         HazardRec->AdvanceCycle();
697         ++CurCycle;
698         CycleHasInsts = false;
699       }
700     } else {
701       if (CycleHasInsts) {
702         DEBUG(dbgs() << "*** Finished cycle " << CurCycle << '\n');
703         HazardRec->AdvanceCycle();
704       } else if (!HasNoopHazards) {
705         // Otherwise, we have a pipeline stall, but no other problem,
706         // just advance the current cycle and try again.
707         DEBUG(dbgs() << "*** Stall in cycle " << CurCycle << '\n');
708         HazardRec->AdvanceCycle();
709         ++NumStalls;
710       } else {
711         // Otherwise, we have no instructions to issue and we have instructions
712         // that will fault if we don't do this right.  This is the case for
713         // processors without pipeline interlocks and other cases.
714         DEBUG(dbgs() << "*** Emitting noop in cycle " << CurCycle << '\n');
715         HazardRec->EmitNoop();
716         Sequence.push_back(0);   // NULL here means noop
717         ++NumNoops;
718       }
719
720       ++CurCycle;
721       CycleHasInsts = false;
722     }
723   }
724
725 #ifndef NDEBUG
726   unsigned ScheduledNodes = VerifyScheduledDAG(/*isBottomUp=*/false);
727   unsigned Noops = 0;
728   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
729     if (!Sequence[i])
730       ++Noops;
731   assert(Sequence.size() - Noops == ScheduledNodes &&
732          "The number of nodes scheduled doesn't match the expected number!");
733 #endif // NDEBUG
734 }
735
736 // EmitSchedule - Emit the machine code in scheduled order.
737 void SchedulePostRATDList::EmitSchedule() {
738   Begin = InsertPos;
739
740   // If first instruction was a DBG_VALUE then put it back.
741   if (FirstDbgValue)
742     BB->splice(InsertPos, BB, FirstDbgValue);
743
744   // Then re-insert them according to the given schedule.
745   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
746     if (SUnit *SU = Sequence[i])
747       BB->splice(InsertPos, BB, SU->getInstr());
748     else
749       // Null SUnit* is a noop.
750       TII->insertNoop(*BB, InsertPos);
751
752     // Update the Begin iterator, as the first instruction in the block
753     // may have been scheduled later.
754     if (i == 0)
755       Begin = prior(InsertPos);
756   }
757
758   // Reinsert any remaining debug_values.
759   for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
760          DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
761     std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
762     MachineInstr *DbgValue = P.first;
763     MachineBasicBlock::iterator OrigPrivMI = P.second;
764     BB->splice(++OrigPrivMI, BB, DbgValue);
765   }
766   DbgValues.clear();
767   FirstDbgValue = NULL;
768 }