1 //===----- SchedulePostRAList.cpp - list scheduler ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
19 //===----------------------------------------------------------------------===//
21 #define DEBUG_TYPE "post-RA-sched"
22 #include "ScheduleDAGInstrs.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/LatencyPriorityQueue.h"
25 #include "llvm/CodeGen/SchedulerRegistry.h"
26 #include "llvm/CodeGen/MachineDominators.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/ADT/Statistic.h"
40 STATISTIC(NumNoops, "Number of noops inserted");
41 STATISTIC(NumStalls, "Number of pipeline stalls");
44 EnableAntiDepBreaking("break-anti-dependencies",
45 cl::desc("Break post-RA scheduling anti-dependencies"),
46 cl::init(true), cl::Hidden);
49 EnablePostRAHazardAvoidance("avoid-hazards",
50 cl::desc("Enable simple hazard-avoidance"),
51 cl::init(true), cl::Hidden);
54 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
57 PostRAScheduler() : MachineFunctionPass(&ID) {}
59 void getAnalysisUsage(AnalysisUsage &AU) const {
60 AU.addRequired<MachineDominatorTree>();
61 AU.addPreserved<MachineDominatorTree>();
62 AU.addRequired<MachineLoopInfo>();
63 AU.addPreserved<MachineLoopInfo>();
64 MachineFunctionPass::getAnalysisUsage(AU);
67 const char *getPassName() const {
68 return "Post RA top-down list latency scheduler";
71 bool runOnMachineFunction(MachineFunction &Fn);
73 char PostRAScheduler::ID = 0;
75 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
76 /// AvailableQueue - The priority queue to use for the available SUnits.
78 LatencyPriorityQueue AvailableQueue;
80 /// PendingQueue - This contains all of the instructions whose operands have
81 /// been issued, but their results are not ready yet (due to the latency of
82 /// the operation). Once the operands becomes available, the instruction is
83 /// added to the AvailableQueue.
84 std::vector<SUnit*> PendingQueue;
86 /// Topo - A topological ordering for SUnits.
87 ScheduleDAGTopologicalSort Topo;
89 /// AllocatableSet - The set of allocatable registers.
90 /// We'll be ignoring anti-dependencies on non-allocatable registers,
91 /// because they may not be safe to break.
92 const BitVector AllocatableSet;
94 /// HazardRec - The hazard recognizer to use.
95 ScheduleHazardRecognizer *HazardRec;
97 /// Classes - For live regs that are only used in one register class in a
98 /// live range, the register class. If the register is not live, the
99 /// corresponding value is null. If the register is live but used in
100 /// multiple register classes, the corresponding value is -1 casted to a
102 const TargetRegisterClass *
103 Classes[TargetRegisterInfo::FirstVirtualRegister];
105 /// RegRegs - Map registers to all their references within a live range.
106 std::multimap<unsigned, MachineOperand *> RegRefs;
108 /// The index of the most recent kill (proceding bottom-up), or ~0u if
109 /// the register is not live.
110 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
112 /// The index of the most recent complete def (proceding bottom up), or ~0u
113 /// if the register is live.
114 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
117 SchedulePostRATDList(MachineFunction &MF,
118 const MachineLoopInfo &MLI,
119 const MachineDominatorTree &MDT,
120 ScheduleHazardRecognizer *HR)
121 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
122 AllocatableSet(TRI->getAllocatableSet(MF)),
125 ~SchedulePostRATDList() {
129 /// StartBlock - Initialize register live-range state for scheduling in
132 void StartBlock(MachineBasicBlock *BB);
134 /// Schedule - Schedule the instruction range using list scheduling.
138 /// Observe - Update liveness information to account for the current
139 /// instruction, which will not be scheduled.
141 void Observe(MachineInstr *MI);
143 /// FinishBlock - Clean up register live-range state.
148 void PrescanInstruction(MachineInstr *MI);
149 void ScanInstruction(MachineInstr *MI, unsigned Count);
150 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
151 void ReleaseSuccessors(SUnit *SU);
152 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
153 void ListScheduleTopDown();
154 bool BreakAntiDependencies();
157 /// SimpleHazardRecognizer - A *very* simple hazard recognizer. It uses
158 /// a coarse classification and attempts to avoid that instructions of
159 /// a given class aren't grouped too densely together.
160 class SimpleHazardRecognizer : public ScheduleHazardRecognizer {
161 /// Class - A simple classification for SUnits.
166 /// Window - The Class values of the most recently issued
170 /// getClass - Classify the given SUnit.
171 Class getClass(const SUnit *SU) {
172 const MachineInstr *MI = SU->getInstr();
173 const TargetInstrDesc &TID = MI->getDesc();
181 /// Step - Rotate the existing entries in Window and insert the
182 /// given class value in position as the most recent.
184 std::copy(Window+1, array_endof(Window), Window);
185 Window[array_lengthof(Window)-1] = C;
189 SimpleHazardRecognizer() : Window() {}
191 virtual HazardType getHazardType(SUnit *SU) {
192 Class C = getClass(SU);
196 for (unsigned i = 0; i != array_lengthof(Window); ++i)
199 if (Score > array_lengthof(Window) * 2)
204 virtual void EmitInstruction(SUnit *SU) {
208 virtual void AdvanceCycle() {
214 /// isSchedulingBoundary - Test if the given instruction should be
215 /// considered a scheduling boundary. This primarily includes labels
218 static bool isSchedulingBoundary(const MachineInstr *MI,
219 const MachineFunction &MF) {
220 // Terminators and labels can't be scheduled around.
221 if (MI->getDesc().isTerminator() || MI->isLabel())
227 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
228 DOUT << "PostRAScheduler\n";
230 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
231 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
232 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
233 new SimpleHazardRecognizer :
234 new ScheduleHazardRecognizer();
236 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
238 // Loop over all of the basic blocks
239 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
240 MBB != MBBe; ++MBB) {
241 // Initialize register live-range state for scheduling in this block.
242 Scheduler.StartBlock(MBB);
244 // Schedule each sequence of instructions not interrupted by a label
245 // or anything else that effectively needs to shut down scheduling.
246 MachineBasicBlock::iterator Current = MBB->end();
247 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
248 MachineInstr *MI = prior(I);
249 if (isSchedulingBoundary(MI, Fn)) {
251 Scheduler.Run(0, MBB, I, Current);
252 Scheduler.EmitSchedule();
254 Scheduler.Observe(MI);
259 Scheduler.Run(0, MBB, MBB->begin(), Current);
260 Scheduler.EmitSchedule();
262 // Clean up register live-range state.
263 Scheduler.FinishBlock();
269 /// StartBlock - Initialize register live-range state for scheduling in
272 void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
273 // Call the superclass.
274 ScheduleDAGInstrs::StartBlock(BB);
276 // Clear out the register class data.
277 std::fill(Classes, array_endof(Classes),
278 static_cast<const TargetRegisterClass *>(0));
280 // Initialize the indices to indicate that no registers are live.
281 std::fill(KillIndices, array_endof(KillIndices), ~0u);
282 std::fill(DefIndices, array_endof(DefIndices), BB->size());
284 // Determine the live-out physregs for this block.
285 if (!BB->empty() && BB->back().getDesc().isReturn())
286 // In a return block, examine the function live-out regs.
287 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
288 E = MRI.liveout_end(); I != E; ++I) {
290 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
291 KillIndices[Reg] = BB->size();
292 DefIndices[Reg] = ~0u;
293 // Repeat, for all aliases.
294 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
295 unsigned AliasReg = *Alias;
296 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
297 KillIndices[AliasReg] = BB->size();
298 DefIndices[AliasReg] = ~0u;
302 // In a non-return block, examine the live-in regs of all successors.
303 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
304 SE = BB->succ_end(); SI != SE; ++SI)
305 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
306 E = (*SI)->livein_end(); I != E; ++I) {
308 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
309 KillIndices[Reg] = BB->size();
310 DefIndices[Reg] = ~0u;
311 // Repeat, for all aliases.
312 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
313 unsigned AliasReg = *Alias;
314 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
315 KillIndices[AliasReg] = BB->size();
316 DefIndices[AliasReg] = ~0u;
320 // Consider callee-saved registers as live-out, since we're running after
321 // prologue/epilogue insertion so there's no way to add additional
324 // TODO: If the callee saves and restores these, then we can potentially
325 // use them between the save and the restore. To do that, we could scan
326 // the exit blocks to see which of these registers are defined.
327 // Alternatively, callee-saved registers that aren't saved and restored
328 // could be marked live-in in every block.
329 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
331 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
332 KillIndices[Reg] = BB->size();
333 DefIndices[Reg] = ~0u;
334 // Repeat, for all aliases.
335 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
336 unsigned AliasReg = *Alias;
337 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
338 KillIndices[AliasReg] = BB->size();
339 DefIndices[AliasReg] = ~0u;
344 /// Schedule - Schedule the instruction range using list scheduling.
346 void SchedulePostRATDList::Schedule() {
347 DOUT << "********** List Scheduling **********\n";
349 // Build the scheduling graph.
352 if (EnableAntiDepBreaking) {
353 if (BreakAntiDependencies()) {
354 // We made changes. Update the dependency graph.
355 // Theoretically we could update the graph in place:
356 // When a live range is changed to use a different register, remove
357 // the def's anti-dependence *and* output-dependence edges due to
358 // that register, and add new anti-dependence and output-dependence
359 // edges based on the next live range of the register.
367 AvailableQueue.initNodes(SUnits);
369 ListScheduleTopDown();
371 AvailableQueue.releaseState();
374 /// Observe - Update liveness information to account for the current
375 /// instruction, which will not be scheduled.
377 void SchedulePostRATDList::Observe(MachineInstr *MI) {
378 PrescanInstruction(MI);
379 ScanInstruction(MI, 0);
382 /// FinishBlock - Clean up register live-range state.
384 void SchedulePostRATDList::FinishBlock() {
387 // Call the superclass.
388 ScheduleDAGInstrs::FinishBlock();
391 /// getInstrOperandRegClass - Return register class of the operand of an
392 /// instruction of the specified TargetInstrDesc.
393 static const TargetRegisterClass*
394 getInstrOperandRegClass(const TargetRegisterInfo *TRI,
395 const TargetInstrDesc &II, unsigned Op) {
396 if (Op >= II.getNumOperands())
398 if (II.OpInfo[Op].isLookupPtrRegClass())
399 return TRI->getPointerRegClass();
400 return TRI->getRegClass(II.OpInfo[Op].RegClass);
403 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
405 static SDep *CriticalPathStep(SUnit *SU) {
407 unsigned NextDepth = 0;
408 // Find the predecessor edge with the greatest depth.
409 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
411 SUnit *PredSU = P->getSUnit();
412 unsigned PredLatency = P->getLatency();
413 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
414 // In the case of a latency tie, prefer an anti-dependency edge over
415 // other types of edges.
416 if (NextDepth < PredTotalLatency ||
417 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
418 NextDepth = PredTotalLatency;
425 void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
426 // Scan the register operands for this instruction and update
427 // Classes and RegRefs.
428 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
429 MachineOperand &MO = MI->getOperand(i);
430 if (!MO.isReg()) continue;
431 unsigned Reg = MO.getReg();
432 if (Reg == 0) continue;
433 const TargetRegisterClass *NewRC =
434 getInstrOperandRegClass(TRI, MI->getDesc(), i);
436 // For now, only allow the register to be changed if its register
437 // class is consistent across all uses.
438 if (!Classes[Reg] && NewRC)
439 Classes[Reg] = NewRC;
440 else if (!NewRC || Classes[Reg] != NewRC)
441 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
443 // Now check for aliases.
444 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
445 // If an alias of the reg is used during the live range, give up.
446 // Note that this allows us to skip checking if AntiDepReg
447 // overlaps with any of the aliases, among other things.
448 unsigned AliasReg = *Alias;
449 if (Classes[AliasReg]) {
450 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
451 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
455 // If we're still willing to consider this register, note the reference.
456 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
457 RegRefs.insert(std::make_pair(Reg, &MO));
461 void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
464 // Proceding upwards, registers that are defed but not used in this
465 // instruction are now dead.
466 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
467 MachineOperand &MO = MI->getOperand(i);
468 if (!MO.isReg()) continue;
469 unsigned Reg = MO.getReg();
470 if (Reg == 0) continue;
471 if (!MO.isDef()) continue;
472 // Ignore two-addr defs.
473 if (MI->isRegReDefinedByTwoAddr(i)) continue;
475 DefIndices[Reg] = Count;
476 KillIndices[Reg] = ~0u;
479 // Repeat, for all subregs.
480 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
482 unsigned SubregReg = *Subreg;
483 DefIndices[SubregReg] = Count;
484 KillIndices[SubregReg] = ~0u;
485 Classes[SubregReg] = 0;
486 RegRefs.erase(SubregReg);
488 // Conservatively mark super-registers as unusable.
489 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
491 unsigned SuperReg = *Super;
492 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
495 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
496 MachineOperand &MO = MI->getOperand(i);
497 if (!MO.isReg()) continue;
498 unsigned Reg = MO.getReg();
499 if (Reg == 0) continue;
500 if (!MO.isUse()) continue;
502 const TargetRegisterClass *NewRC =
503 getInstrOperandRegClass(TRI, MI->getDesc(), i);
505 // For now, only allow the register to be changed if its register
506 // class is consistent across all uses.
507 if (!Classes[Reg] && NewRC)
508 Classes[Reg] = NewRC;
509 else if (!NewRC || Classes[Reg] != NewRC)
510 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
512 RegRefs.insert(std::make_pair(Reg, &MO));
514 // It wasn't previously live but now it is, this is a kill.
515 if (KillIndices[Reg] == ~0u) {
516 KillIndices[Reg] = Count;
517 DefIndices[Reg] = ~0u;
519 // Repeat, for all aliases.
520 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
521 unsigned AliasReg = *Alias;
522 if (KillIndices[AliasReg] == ~0u) {
523 KillIndices[AliasReg] = Count;
524 DefIndices[AliasReg] = ~0u;
530 /// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
531 /// of the ScheduleDAG and break them by renaming registers.
533 bool SchedulePostRATDList::BreakAntiDependencies() {
534 // The code below assumes that there is at least one instruction,
535 // so just duck out immediately if the block is empty.
536 if (SUnits.empty()) return false;
538 // Find the node at the bottom of the critical path.
540 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
541 SUnit *SU = &SUnits[i];
542 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
546 DOUT << "Critical path has total latency "
547 << (Max->getDepth() + Max->Latency) << "\n";
549 // Track progress along the critical path through the SUnit graph as we walk
551 SUnit *CriticalPathSU = Max;
552 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
554 // Consider this pattern:
563 // There are three anti-dependencies here, and without special care,
564 // we'd break all of them using the same register:
573 // because at each anti-dependence, B is the first register that
574 // isn't A which is free. This re-introduces anti-dependencies
575 // at all but one of the original anti-dependencies that we were
576 // trying to break. To avoid this, keep track of the most recent
577 // register that each register was replaced with, avoid avoid
578 // using it to repair an anti-dependence on the same register.
579 // This lets us produce this:
588 // This still has an anti-dependence on B, but at least it isn't on the
589 // original critical path.
591 // TODO: If we tracked more than one register here, we could potentially
592 // fix that remaining critical edge too. This is a little more involved,
593 // because unlike the most recent register, less recent registers should
594 // still be considered, though only if no other registers are available.
595 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
597 // Attempt to break anti-dependence edges on the critical path. Walk the
598 // instructions from the bottom up, tracking information about liveness
599 // as we go to help determine which registers are available.
600 bool Changed = false;
601 unsigned Count = SUnits.size() - 1;
602 for (MachineBasicBlock::iterator I = End, E = Begin;
604 MachineInstr *MI = --I;
606 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
607 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
608 // is left behind appearing to clobber the super-register, while the
609 // subregister needs to remain live. So we just ignore them.
610 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
613 // Check if this instruction has a dependence on the critical path that
614 // is an anti-dependence that we may be able to break. If it is, set
615 // AntiDepReg to the non-zero register associated with the anti-dependence.
617 // We limit our attention to the critical path as a heuristic to avoid
618 // breaking anti-dependence edges that aren't going to significantly
619 // impact the overall schedule. There are a limited number of registers
620 // and we want to save them for the important edges.
622 // TODO: Instructions with multiple defs could have multiple
623 // anti-dependencies. The current code here only knows how to break one
624 // edge per instruction. Note that we'd have to be able to break all of
625 // the anti-dependencies in an instruction in order to be effective.
626 unsigned AntiDepReg = 0;
627 if (MI == CriticalPathMI) {
628 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
629 SUnit *NextSU = Edge->getSUnit();
631 // Only consider anti-dependence edges.
632 if (Edge->getKind() == SDep::Anti) {
633 AntiDepReg = Edge->getReg();
634 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
635 // Don't break anti-dependencies on non-allocatable registers.
636 if (!AllocatableSet.test(AntiDepReg))
639 // If the SUnit has other dependencies on the SUnit that it
640 // anti-depends on, don't bother breaking the anti-dependency
641 // since those edges would prevent such units from being
642 // scheduled past each other regardless.
644 // Also, if there are dependencies on other SUnits with the
645 // same register as the anti-dependency, don't attempt to
647 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
648 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
649 if (P->getSUnit() == NextSU ?
650 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
651 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
657 CriticalPathSU = NextSU;
658 CriticalPathMI = CriticalPathSU->getInstr();
660 // We've reached the end of the critical path.
666 PrescanInstruction(MI);
668 // If this instruction has a use of AntiDepReg, breaking it
670 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
671 MachineOperand &MO = MI->getOperand(i);
672 if (!MO.isReg()) continue;
673 unsigned Reg = MO.getReg();
674 if (Reg == 0) continue;
675 if (MO.isUse() && AntiDepReg == Reg) {
681 // Determine AntiDepReg's register class, if it is live and is
682 // consistently used within a single class.
683 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
684 assert((AntiDepReg == 0 || RC != NULL) &&
685 "Register should be live if it's causing an anti-dependence!");
686 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
689 // Look for a suitable register to use to break the anti-depenence.
691 // TODO: Instead of picking the first free register, consider which might
693 if (AntiDepReg != 0) {
694 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
695 RE = RC->allocation_order_end(MF); R != RE; ++R) {
696 unsigned NewReg = *R;
697 // Don't replace a register with itself.
698 if (NewReg == AntiDepReg) continue;
699 // Don't replace a register with one that was recently used to repair
700 // an anti-dependence with this AntiDepReg, because that would
701 // re-introduce that anti-dependence.
702 if (NewReg == LastNewReg[AntiDepReg]) continue;
703 // If NewReg is dead and NewReg's most recent def is not before
704 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
705 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
706 "Kill and Def maps aren't consistent for AntiDepReg!");
707 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
708 "Kill and Def maps aren't consistent for NewReg!");
709 if (KillIndices[NewReg] == ~0u &&
710 Classes[NewReg] != reinterpret_cast<TargetRegisterClass *>(-1) &&
711 KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
712 DOUT << "Breaking anti-dependence edge on "
713 << TRI->getName(AntiDepReg)
714 << " with " << RegRefs.count(AntiDepReg) << " references"
715 << " using " << TRI->getName(NewReg) << "!\n";
717 // Update the references to the old register to refer to the new
719 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
720 std::multimap<unsigned, MachineOperand *>::iterator>
721 Range = RegRefs.equal_range(AntiDepReg);
722 for (std::multimap<unsigned, MachineOperand *>::iterator
723 Q = Range.first, QE = Range.second; Q != QE; ++Q)
724 Q->second->setReg(NewReg);
726 // We just went back in time and modified history; the
727 // liveness information for the anti-depenence reg is now
728 // inconsistent. Set the state as if it were dead.
729 Classes[NewReg] = Classes[AntiDepReg];
730 DefIndices[NewReg] = DefIndices[AntiDepReg];
731 KillIndices[NewReg] = KillIndices[AntiDepReg];
733 Classes[AntiDepReg] = 0;
734 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
735 KillIndices[AntiDepReg] = ~0u;
737 RegRefs.erase(AntiDepReg);
739 LastNewReg[AntiDepReg] = NewReg;
745 ScanInstruction(MI, Count);
747 assert(Count == ~0u && "Count mismatch!");
752 //===----------------------------------------------------------------------===//
753 // Top-Down Scheduling
754 //===----------------------------------------------------------------------===//
756 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
757 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
758 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
759 SUnit *SuccSU = SuccEdge->getSUnit();
760 --SuccSU->NumPredsLeft;
763 if (SuccSU->NumPredsLeft < 0) {
764 cerr << "*** Scheduling failed! ***\n";
766 cerr << " has been released too many times!\n";
771 // Compute how many cycles it will be before this actually becomes
772 // available. This is the max of the start time of all predecessors plus
774 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
776 // If all the node's predecessors are scheduled, this node is ready
777 // to be scheduled. Ignore the special ExitSU node.
778 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
779 PendingQueue.push_back(SuccSU);
782 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
783 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
784 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
786 ReleaseSucc(SU, &*I);
789 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
790 /// count of its successors. If a successor pending count is zero, add it to
791 /// the Available queue.
792 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
793 DOUT << "*** Scheduling [" << CurCycle << "]: ";
794 DEBUG(SU->dump(this));
796 Sequence.push_back(SU);
797 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
798 SU->setDepthToAtLeast(CurCycle);
800 ReleaseSuccessors(SU);
801 SU->isScheduled = true;
802 AvailableQueue.ScheduledNode(SU);
805 /// ListScheduleTopDown - The main loop of list scheduling for top-down
807 void SchedulePostRATDList::ListScheduleTopDown() {
808 unsigned CurCycle = 0;
810 // Release any successors of the special Entry node.
811 ReleaseSuccessors(&EntrySU);
813 // All leaves to Available queue.
814 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
815 // It is available if it has no predecessors.
816 if (SUnits[i].Preds.empty()) {
817 AvailableQueue.push(&SUnits[i]);
818 SUnits[i].isAvailable = true;
822 // While Available queue is not empty, grab the node with the highest
823 // priority. If it is not ready put it back. Schedule the node.
824 std::vector<SUnit*> NotReady;
825 Sequence.reserve(SUnits.size());
826 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
827 // Check to see if any of the pending instructions are ready to issue. If
828 // so, add them to the available queue.
829 unsigned MinDepth = ~0u;
830 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
831 if (PendingQueue[i]->getDepth() <= CurCycle) {
832 AvailableQueue.push(PendingQueue[i]);
833 PendingQueue[i]->isAvailable = true;
834 PendingQueue[i] = PendingQueue.back();
835 PendingQueue.pop_back();
837 } else if (PendingQueue[i]->getDepth() < MinDepth)
838 MinDepth = PendingQueue[i]->getDepth();
841 // If there are no instructions available, don't try to issue anything, and
842 // don't advance the hazard recognizer.
843 if (AvailableQueue.empty()) {
844 CurCycle = MinDepth != ~0u ? MinDepth : CurCycle + 1;
848 SUnit *FoundSUnit = 0;
850 bool HasNoopHazards = false;
851 while (!AvailableQueue.empty()) {
852 SUnit *CurSUnit = AvailableQueue.pop();
854 ScheduleHazardRecognizer::HazardType HT =
855 HazardRec->getHazardType(CurSUnit);
856 if (HT == ScheduleHazardRecognizer::NoHazard) {
857 FoundSUnit = CurSUnit;
861 // Remember if this is a noop hazard.
862 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
864 NotReady.push_back(CurSUnit);
867 // Add the nodes that aren't ready back onto the available list.
868 if (!NotReady.empty()) {
869 AvailableQueue.push_all(NotReady);
873 // If we found a node to schedule, do it now.
875 ScheduleNodeTopDown(FoundSUnit, CurCycle);
876 HazardRec->EmitInstruction(FoundSUnit);
878 // If this is a pseudo-op node, we don't want to increment the current
880 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
882 } else if (!HasNoopHazards) {
883 // Otherwise, we have a pipeline stall, but no other problem, just advance
884 // the current cycle and try again.
885 DOUT << "*** Advancing cycle, no work to do\n";
886 HazardRec->AdvanceCycle();
890 // Otherwise, we have no instructions to issue and we have instructions
891 // that will fault if we don't do this right. This is the case for
892 // processors without pipeline interlocks and other cases.
893 DOUT << "*** Emitting noop\n";
894 HazardRec->EmitNoop();
895 Sequence.push_back(0); // NULL here means noop
902 VerifySchedule(/*isBottomUp=*/false);
906 //===----------------------------------------------------------------------===//
907 // Public Constructor Functions
908 //===----------------------------------------------------------------------===//
910 FunctionPass *llvm::createPostRAScheduler() {
911 return new PostRAScheduler();