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 "ExactHazardRecognizer.h"
23 #include "SimpleHazardRecognizer.h"
24 #include "ScheduleDAGInstrs.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/LatencyPriorityQueue.h"
27 #include "llvm/CodeGen/SchedulerRegistry.h"
28 #include "llvm/CodeGen/MachineDominators.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetRegisterInfo.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/ADT/Statistic.h"
44 STATISTIC(NumNoops, "Number of noops inserted");
45 STATISTIC(NumStalls, "Number of pipeline stalls");
48 EnableAntiDepBreaking("break-anti-dependencies",
49 cl::desc("Break post-RA scheduling anti-dependencies"),
50 cl::init(true), cl::Hidden);
53 EnablePostRAHazardAvoidance("avoid-hazards",
54 cl::desc("Enable exact hazard avoidance"),
55 cl::init(false), cl::Hidden);
58 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
61 PostRAScheduler() : MachineFunctionPass(&ID) {}
63 void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.addRequired<MachineDominatorTree>();
66 AU.addPreserved<MachineDominatorTree>();
67 AU.addRequired<MachineLoopInfo>();
68 AU.addPreserved<MachineLoopInfo>();
69 MachineFunctionPass::getAnalysisUsage(AU);
72 const char *getPassName() const {
73 return "Post RA top-down list latency scheduler";
76 bool runOnMachineFunction(MachineFunction &Fn);
78 char PostRAScheduler::ID = 0;
80 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
81 /// AvailableQueue - The priority queue to use for the available SUnits.
83 LatencyPriorityQueue AvailableQueue;
85 /// PendingQueue - This contains all of the instructions whose operands have
86 /// been issued, but their results are not ready yet (due to the latency of
87 /// the operation). Once the operands becomes available, the instruction is
88 /// added to the AvailableQueue.
89 std::vector<SUnit*> PendingQueue;
91 /// Topo - A topological ordering for SUnits.
92 ScheduleDAGTopologicalSort Topo;
94 /// AllocatableSet - The set of allocatable registers.
95 /// We'll be ignoring anti-dependencies on non-allocatable registers,
96 /// because they may not be safe to break.
97 const BitVector AllocatableSet;
99 /// HazardRec - The hazard recognizer to use.
100 ScheduleHazardRecognizer *HazardRec;
102 /// Classes - For live regs that are only used in one register class in a
103 /// live range, the register class. If the register is not live, the
104 /// corresponding value is null. If the register is live but used in
105 /// multiple register classes, the corresponding value is -1 casted to a
107 const TargetRegisterClass *
108 Classes[TargetRegisterInfo::FirstVirtualRegister];
110 /// RegRegs - Map registers to all their references within a live range.
111 std::multimap<unsigned, MachineOperand *> RegRefs;
113 /// The index of the most recent kill (proceding bottom-up), or ~0u if
114 /// the register is not live.
115 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
117 /// The index of the most recent complete def (proceding bottom up), or ~0u
118 /// if the register is live.
119 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
122 SchedulePostRATDList(MachineFunction &MF,
123 const MachineLoopInfo &MLI,
124 const MachineDominatorTree &MDT,
125 ScheduleHazardRecognizer *HR)
126 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
127 AllocatableSet(TRI->getAllocatableSet(MF)),
130 ~SchedulePostRATDList() {
134 /// StartBlock - Initialize register live-range state for scheduling in
137 void StartBlock(MachineBasicBlock *BB);
139 /// Schedule - Schedule the instruction range using list scheduling.
143 /// Observe - Update liveness information to account for the current
144 /// instruction, which will not be scheduled.
146 void Observe(MachineInstr *MI, unsigned Count);
148 /// FinishBlock - Clean up register live-range state.
153 void PrescanInstruction(MachineInstr *MI);
154 void ScanInstruction(MachineInstr *MI, unsigned Count);
155 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
156 void ReleaseSuccessors(SUnit *SU);
157 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
158 void ListScheduleTopDown();
159 bool BreakAntiDependencies();
163 /// isSchedulingBoundary - Test if the given instruction should be
164 /// considered a scheduling boundary. This primarily includes labels
167 static bool isSchedulingBoundary(const MachineInstr *MI,
168 const MachineFunction &MF) {
169 // Terminators and labels can't be scheduled around.
170 if (MI->getDesc().isTerminator() || MI->isLabel())
173 // Don't attempt to schedule around any instruction that modifies
174 // a stack-oriented pointer, as it's unlikely to be profitable. This
175 // saves compile time, because it doesn't require every single
176 // stack slot reference to depend on the instruction that does the
178 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
179 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
185 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
186 DOUT << "PostRAScheduler\n";
188 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
189 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
190 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
191 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
192 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
193 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
195 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
197 // Loop over all of the basic blocks
198 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
199 MBB != MBBe; ++MBB) {
200 // Initialize register live-range state for scheduling in this block.
201 Scheduler.StartBlock(MBB);
203 // Schedule each sequence of instructions not interrupted by a label
204 // or anything else that effectively needs to shut down scheduling.
205 MachineBasicBlock::iterator Current = MBB->end();
206 unsigned Count = MBB->size(), CurrentCount = Count;
207 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
208 MachineInstr *MI = prior(I);
209 if (isSchedulingBoundary(MI, Fn)) {
210 Scheduler.Run(MBB, I, Current, CurrentCount);
211 Scheduler.EmitSchedule();
213 CurrentCount = Count - 1;
214 Scheduler.Observe(MI, CurrentCount);
219 assert(Count == 0 && "Instruction count mismatch!");
220 assert((MBB->begin() == Current || CurrentCount != 0) &&
221 "Instruction count mismatch!");
222 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
223 Scheduler.EmitSchedule();
225 // Clean up register live-range state.
226 Scheduler.FinishBlock();
232 /// StartBlock - Initialize register live-range state for scheduling in
235 void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
236 // Call the superclass.
237 ScheduleDAGInstrs::StartBlock(BB);
239 // Reset the hazard recognizer.
242 // Clear out the register class data.
243 std::fill(Classes, array_endof(Classes),
244 static_cast<const TargetRegisterClass *>(0));
246 // Initialize the indices to indicate that no registers are live.
247 std::fill(KillIndices, array_endof(KillIndices), ~0u);
248 std::fill(DefIndices, array_endof(DefIndices), BB->size());
250 // Determine the live-out physregs for this block.
251 if (!BB->empty() && BB->back().getDesc().isReturn())
252 // In a return block, examine the function live-out regs.
253 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
254 E = MRI.liveout_end(); I != E; ++I) {
256 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
257 KillIndices[Reg] = BB->size();
258 DefIndices[Reg] = ~0u;
259 // Repeat, for all aliases.
260 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
261 unsigned AliasReg = *Alias;
262 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
263 KillIndices[AliasReg] = BB->size();
264 DefIndices[AliasReg] = ~0u;
268 // In a non-return block, examine the live-in regs of all successors.
269 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
270 SE = BB->succ_end(); SI != SE; ++SI)
271 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
272 E = (*SI)->livein_end(); I != E; ++I) {
274 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
275 KillIndices[Reg] = BB->size();
276 DefIndices[Reg] = ~0u;
277 // Repeat, for all aliases.
278 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
279 unsigned AliasReg = *Alias;
280 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
281 KillIndices[AliasReg] = BB->size();
282 DefIndices[AliasReg] = ~0u;
286 // Consider callee-saved registers as live-out, since we're running after
287 // prologue/epilogue insertion so there's no way to add additional
290 // TODO: If the callee saves and restores these, then we can potentially
291 // use them between the save and the restore. To do that, we could scan
292 // the exit blocks to see which of these registers are defined.
293 // Alternatively, callee-saved registers that aren't saved and restored
294 // could be marked live-in in every block.
295 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
297 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
298 KillIndices[Reg] = BB->size();
299 DefIndices[Reg] = ~0u;
300 // Repeat, for all aliases.
301 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
302 unsigned AliasReg = *Alias;
303 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
304 KillIndices[AliasReg] = BB->size();
305 DefIndices[AliasReg] = ~0u;
310 /// Schedule - Schedule the instruction range using list scheduling.
312 void SchedulePostRATDList::Schedule() {
313 DOUT << "********** List Scheduling **********\n";
315 // Build the scheduling graph.
318 if (EnableAntiDepBreaking) {
319 if (BreakAntiDependencies()) {
320 // We made changes. Update the dependency graph.
321 // Theoretically we could update the graph in place:
322 // When a live range is changed to use a different register, remove
323 // the def's anti-dependence *and* output-dependence edges due to
324 // that register, and add new anti-dependence and output-dependence
325 // edges based on the next live range of the register.
333 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
334 SUnits[su].dumpAll(this));
336 AvailableQueue.initNodes(SUnits);
338 ListScheduleTopDown();
340 AvailableQueue.releaseState();
343 /// Observe - Update liveness information to account for the current
344 /// instruction, which will not be scheduled.
346 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
347 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
349 // Any register which was defined within the previous scheduling region
350 // may have been rescheduled and its lifetime may overlap with registers
351 // in ways not reflected in our current liveness state. For each such
352 // register, adjust the liveness state to be conservatively correct.
353 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
354 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
355 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
356 // Mark this register to be non-renamable.
357 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
358 // Move the def index to the end of the previous region, to reflect
359 // that the def could theoretically have been scheduled at the end.
360 DefIndices[Reg] = InsertPosIndex;
363 PrescanInstruction(MI);
364 ScanInstruction(MI, Count);
367 /// FinishBlock - Clean up register live-range state.
369 void SchedulePostRATDList::FinishBlock() {
372 // Call the superclass.
373 ScheduleDAGInstrs::FinishBlock();
376 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
378 static SDep *CriticalPathStep(SUnit *SU) {
380 unsigned NextDepth = 0;
381 // Find the predecessor edge with the greatest depth.
382 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
384 SUnit *PredSU = P->getSUnit();
385 unsigned PredLatency = P->getLatency();
386 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
387 // In the case of a latency tie, prefer an anti-dependency edge over
388 // other types of edges.
389 if (NextDepth < PredTotalLatency ||
390 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
391 NextDepth = PredTotalLatency;
398 void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
399 // Scan the register operands for this instruction and update
400 // Classes and RegRefs.
401 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
402 MachineOperand &MO = MI->getOperand(i);
403 if (!MO.isReg()) continue;
404 unsigned Reg = MO.getReg();
405 if (Reg == 0) continue;
406 const TargetRegisterClass *NewRC = 0;
408 if (i < MI->getDesc().getNumOperands())
409 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
411 // For now, only allow the register to be changed if its register
412 // class is consistent across all uses.
413 if (!Classes[Reg] && NewRC)
414 Classes[Reg] = NewRC;
415 else if (!NewRC || Classes[Reg] != NewRC)
416 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
418 // Now check for aliases.
419 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
420 // If an alias of the reg is used during the live range, give up.
421 // Note that this allows us to skip checking if AntiDepReg
422 // overlaps with any of the aliases, among other things.
423 unsigned AliasReg = *Alias;
424 if (Classes[AliasReg]) {
425 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
426 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
430 // If we're still willing to consider this register, note the reference.
431 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
432 RegRefs.insert(std::make_pair(Reg, &MO));
436 void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
439 // Proceding upwards, registers that are defed but not used in this
440 // instruction are now dead.
441 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
442 MachineOperand &MO = MI->getOperand(i);
443 if (!MO.isReg()) continue;
444 unsigned Reg = MO.getReg();
445 if (Reg == 0) continue;
446 if (!MO.isDef()) continue;
447 // Ignore two-addr defs.
448 if (MI->isRegTiedToUseOperand(i)) continue;
450 DefIndices[Reg] = Count;
451 KillIndices[Reg] = ~0u;
452 assert(((KillIndices[Reg] == ~0u) !=
453 (DefIndices[Reg] == ~0u)) &&
454 "Kill and Def maps aren't consistent for Reg!");
457 // Repeat, for all subregs.
458 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
460 unsigned SubregReg = *Subreg;
461 DefIndices[SubregReg] = Count;
462 KillIndices[SubregReg] = ~0u;
463 Classes[SubregReg] = 0;
464 RegRefs.erase(SubregReg);
466 // Conservatively mark super-registers as unusable.
467 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
469 unsigned SuperReg = *Super;
470 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
473 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
474 MachineOperand &MO = MI->getOperand(i);
475 if (!MO.isReg()) continue;
476 unsigned Reg = MO.getReg();
477 if (Reg == 0) continue;
478 if (!MO.isUse()) continue;
480 const TargetRegisterClass *NewRC = 0;
481 if (i < MI->getDesc().getNumOperands())
482 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
484 // For now, only allow the register to be changed if its register
485 // class is consistent across all uses.
486 if (!Classes[Reg] && NewRC)
487 Classes[Reg] = NewRC;
488 else if (!NewRC || Classes[Reg] != NewRC)
489 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
491 RegRefs.insert(std::make_pair(Reg, &MO));
493 // It wasn't previously live but now it is, this is a kill.
494 if (KillIndices[Reg] == ~0u) {
495 KillIndices[Reg] = Count;
496 DefIndices[Reg] = ~0u;
497 assert(((KillIndices[Reg] == ~0u) !=
498 (DefIndices[Reg] == ~0u)) &&
499 "Kill and Def maps aren't consistent for Reg!");
501 // Repeat, for all aliases.
502 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
503 unsigned AliasReg = *Alias;
504 if (KillIndices[AliasReg] == ~0u) {
505 KillIndices[AliasReg] = Count;
506 DefIndices[AliasReg] = ~0u;
512 /// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
513 /// of the ScheduleDAG and break them by renaming registers.
515 bool SchedulePostRATDList::BreakAntiDependencies() {
516 // The code below assumes that there is at least one instruction,
517 // so just duck out immediately if the block is empty.
518 if (SUnits.empty()) return false;
520 // Find the node at the bottom of the critical path.
522 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
523 SUnit *SU = &SUnits[i];
524 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
528 DOUT << "Critical path has total latency "
529 << (Max->getDepth() + Max->Latency) << "\n";
531 // Track progress along the critical path through the SUnit graph as we walk
533 SUnit *CriticalPathSU = Max;
534 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
536 // Consider this pattern:
545 // There are three anti-dependencies here, and without special care,
546 // we'd break all of them using the same register:
555 // because at each anti-dependence, B is the first register that
556 // isn't A which is free. This re-introduces anti-dependencies
557 // at all but one of the original anti-dependencies that we were
558 // trying to break. To avoid this, keep track of the most recent
559 // register that each register was replaced with, avoid avoid
560 // using it to repair an anti-dependence on the same register.
561 // This lets us produce this:
570 // This still has an anti-dependence on B, but at least it isn't on the
571 // original critical path.
573 // TODO: If we tracked more than one register here, we could potentially
574 // fix that remaining critical edge too. This is a little more involved,
575 // because unlike the most recent register, less recent registers should
576 // still be considered, though only if no other registers are available.
577 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
579 // Attempt to break anti-dependence edges on the critical path. Walk the
580 // instructions from the bottom up, tracking information about liveness
581 // as we go to help determine which registers are available.
582 bool Changed = false;
583 unsigned Count = InsertPosIndex - 1;
584 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
586 MachineInstr *MI = --I;
588 // After regalloc, IMPLICIT_DEF instructions aren't safe to treat as
589 // dependence-breaking. In the case of an INSERT_SUBREG, the IMPLICIT_DEF
590 // is left behind appearing to clobber the super-register, while the
591 // subregister needs to remain live. So we just ignore them.
592 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
595 // Check if this instruction has a dependence on the critical path that
596 // is an anti-dependence that we may be able to break. If it is, set
597 // AntiDepReg to the non-zero register associated with the anti-dependence.
599 // We limit our attention to the critical path as a heuristic to avoid
600 // breaking anti-dependence edges that aren't going to significantly
601 // impact the overall schedule. There are a limited number of registers
602 // and we want to save them for the important edges.
604 // TODO: Instructions with multiple defs could have multiple
605 // anti-dependencies. The current code here only knows how to break one
606 // edge per instruction. Note that we'd have to be able to break all of
607 // the anti-dependencies in an instruction in order to be effective.
608 unsigned AntiDepReg = 0;
609 if (MI == CriticalPathMI) {
610 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
611 SUnit *NextSU = Edge->getSUnit();
613 // Only consider anti-dependence edges.
614 if (Edge->getKind() == SDep::Anti) {
615 AntiDepReg = Edge->getReg();
616 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
617 // Don't break anti-dependencies on non-allocatable registers.
618 if (!AllocatableSet.test(AntiDepReg))
621 // If the SUnit has other dependencies on the SUnit that it
622 // anti-depends on, don't bother breaking the anti-dependency
623 // since those edges would prevent such units from being
624 // scheduled past each other regardless.
626 // Also, if there are dependencies on other SUnits with the
627 // same register as the anti-dependency, don't attempt to
629 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
630 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
631 if (P->getSUnit() == NextSU ?
632 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
633 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
639 CriticalPathSU = NextSU;
640 CriticalPathMI = CriticalPathSU->getInstr();
642 // We've reached the end of the critical path.
648 PrescanInstruction(MI);
650 // If this instruction has a use of AntiDepReg, breaking it
652 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
653 MachineOperand &MO = MI->getOperand(i);
654 if (!MO.isReg()) continue;
655 unsigned Reg = MO.getReg();
656 if (Reg == 0) continue;
657 if (MO.isUse() && AntiDepReg == Reg) {
663 // Determine AntiDepReg's register class, if it is live and is
664 // consistently used within a single class.
665 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
666 assert((AntiDepReg == 0 || RC != NULL) &&
667 "Register should be live if it's causing an anti-dependence!");
668 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
671 // Look for a suitable register to use to break the anti-depenence.
673 // TODO: Instead of picking the first free register, consider which might
675 if (AntiDepReg != 0) {
676 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
677 RE = RC->allocation_order_end(MF); R != RE; ++R) {
678 unsigned NewReg = *R;
679 // Don't replace a register with itself.
680 if (NewReg == AntiDepReg) continue;
681 // Don't replace a register with one that was recently used to repair
682 // an anti-dependence with this AntiDepReg, because that would
683 // re-introduce that anti-dependence.
684 if (NewReg == LastNewReg[AntiDepReg]) continue;
685 // If NewReg is dead and NewReg's most recent def is not before
686 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
687 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
688 "Kill and Def maps aren't consistent for AntiDepReg!");
689 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
690 "Kill and Def maps aren't consistent for NewReg!");
691 if (KillIndices[NewReg] == ~0u &&
692 Classes[NewReg] != reinterpret_cast<TargetRegisterClass *>(-1) &&
693 KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
694 DOUT << "Breaking anti-dependence edge on "
695 << TRI->getName(AntiDepReg)
696 << " with " << RegRefs.count(AntiDepReg) << " references"
697 << " using " << TRI->getName(NewReg) << "!\n";
699 // Update the references to the old register to refer to the new
701 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
702 std::multimap<unsigned, MachineOperand *>::iterator>
703 Range = RegRefs.equal_range(AntiDepReg);
704 for (std::multimap<unsigned, MachineOperand *>::iterator
705 Q = Range.first, QE = Range.second; Q != QE; ++Q)
706 Q->second->setReg(NewReg);
708 // We just went back in time and modified history; the
709 // liveness information for the anti-depenence reg is now
710 // inconsistent. Set the state as if it were dead.
711 Classes[NewReg] = Classes[AntiDepReg];
712 DefIndices[NewReg] = DefIndices[AntiDepReg];
713 KillIndices[NewReg] = KillIndices[AntiDepReg];
714 assert(((KillIndices[NewReg] == ~0u) !=
715 (DefIndices[NewReg] == ~0u)) &&
716 "Kill and Def maps aren't consistent for NewReg!");
718 Classes[AntiDepReg] = 0;
719 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
720 KillIndices[AntiDepReg] = ~0u;
721 assert(((KillIndices[AntiDepReg] == ~0u) !=
722 (DefIndices[AntiDepReg] == ~0u)) &&
723 "Kill and Def maps aren't consistent for AntiDepReg!");
725 RegRefs.erase(AntiDepReg);
727 LastNewReg[AntiDepReg] = NewReg;
733 ScanInstruction(MI, Count);
739 //===----------------------------------------------------------------------===//
740 // Top-Down Scheduling
741 //===----------------------------------------------------------------------===//
743 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
744 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
745 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
746 SUnit *SuccSU = SuccEdge->getSUnit();
747 --SuccSU->NumPredsLeft;
750 if (SuccSU->NumPredsLeft < 0) {
751 cerr << "*** Scheduling failed! ***\n";
753 cerr << " has been released too many times!\n";
758 // Compute how many cycles it will be before this actually becomes
759 // available. This is the max of the start time of all predecessors plus
761 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
763 // If all the node's predecessors are scheduled, this node is ready
764 // to be scheduled. Ignore the special ExitSU node.
765 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
766 PendingQueue.push_back(SuccSU);
769 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
770 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
771 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
773 ReleaseSucc(SU, &*I);
776 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
777 /// count of its successors. If a successor pending count is zero, add it to
778 /// the Available queue.
779 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
780 DOUT << "*** Scheduling [" << CurCycle << "]: ";
781 DEBUG(SU->dump(this));
783 Sequence.push_back(SU);
784 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
785 SU->setDepthToAtLeast(CurCycle);
787 ReleaseSuccessors(SU);
788 SU->isScheduled = true;
789 AvailableQueue.ScheduledNode(SU);
792 /// ListScheduleTopDown - The main loop of list scheduling for top-down
794 void SchedulePostRATDList::ListScheduleTopDown() {
795 unsigned CurCycle = 0;
797 // Release any successors of the special Entry node.
798 ReleaseSuccessors(&EntrySU);
800 // All leaves to Available queue.
801 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
802 // It is available if it has no predecessors.
803 if (SUnits[i].Preds.empty()) {
804 AvailableQueue.push(&SUnits[i]);
805 SUnits[i].isAvailable = true;
809 // While Available queue is not empty, grab the node with the highest
810 // priority. If it is not ready put it back. Schedule the node.
811 std::vector<SUnit*> NotReady;
812 Sequence.reserve(SUnits.size());
813 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
814 // Check to see if any of the pending instructions are ready to issue. If
815 // so, add them to the available queue.
816 unsigned MinDepth = ~0u;
817 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
818 if (PendingQueue[i]->getDepth() <= CurCycle) {
819 AvailableQueue.push(PendingQueue[i]);
820 PendingQueue[i]->isAvailable = true;
821 PendingQueue[i] = PendingQueue.back();
822 PendingQueue.pop_back();
824 } else if (PendingQueue[i]->getDepth() < MinDepth)
825 MinDepth = PendingQueue[i]->getDepth();
828 SUnit *FoundSUnit = 0;
830 bool HasNoopHazards = false;
831 while (!AvailableQueue.empty()) {
832 SUnit *CurSUnit = AvailableQueue.pop();
834 ScheduleHazardRecognizer::HazardType HT =
835 HazardRec->getHazardType(CurSUnit);
836 if (HT == ScheduleHazardRecognizer::NoHazard) {
837 FoundSUnit = CurSUnit;
841 // Remember if this is a noop hazard.
842 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
844 NotReady.push_back(CurSUnit);
847 // Add the nodes that aren't ready back onto the available list.
848 if (!NotReady.empty()) {
849 AvailableQueue.push_all(NotReady);
853 // If we found a node to schedule, do it now.
855 ScheduleNodeTopDown(FoundSUnit, CurCycle);
856 HazardRec->EmitInstruction(FoundSUnit);
858 // If we are using the target-specific hazards, then don't
859 // advance the cycle time just because we schedule a node. If
860 // the target allows it we can schedule multiple nodes in the
862 if (!EnablePostRAHazardAvoidance) {
863 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
866 } else if (!HasNoopHazards) {
867 // Otherwise, we have a pipeline stall, but no other problem, just advance
868 // the current cycle and try again.
869 DOUT << "*** Advancing cycle, no work to do\n";
870 HazardRec->AdvanceCycle();
874 // Otherwise, we have no instructions to issue and we have instructions
875 // that will fault if we don't do this right. This is the case for
876 // processors without pipeline interlocks and other cases.
877 DOUT << "*** Emitting noop\n";
878 HazardRec->EmitNoop();
879 Sequence.push_back(0); // NULL here means noop
886 VerifySchedule(/*isBottomUp=*/false);
890 //===----------------------------------------------------------------------===//
891 // Public Constructor Functions
892 //===----------------------------------------------------------------------===//
894 FunctionPass *llvm::createPostRAScheduler() {
895 return new PostRAScheduler();