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