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/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunctionPass.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtarget.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/ADT/Statistic.h"
48 STATISTIC(NumNoops, "Number of noops inserted");
49 STATISTIC(NumStalls, "Number of pipeline stalls");
52 EnableAntiDepBreaking("break-anti-dependencies",
53 cl::desc("Break post-RA scheduling anti-dependencies"),
54 cl::init(true), cl::Hidden);
57 EnablePostRAHazardAvoidance("avoid-hazards",
58 cl::desc("Enable exact hazard avoidance"),
59 cl::init(true), cl::Hidden);
61 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
63 DebugDiv("postra-sched-debugdiv",
64 cl::desc("Debug control MBBs that are scheduled"),
65 cl::init(0), cl::Hidden);
67 DebugMod("postra-sched-debugmod",
68 cl::desc("Debug control MBBs that are scheduled"),
69 cl::init(0), cl::Hidden);
72 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
75 PostRAScheduler() : MachineFunctionPass(&ID) {}
77 void getAnalysisUsage(AnalysisUsage &AU) const {
79 AU.addRequired<MachineDominatorTree>();
80 AU.addPreserved<MachineDominatorTree>();
81 AU.addRequired<MachineLoopInfo>();
82 AU.addPreserved<MachineLoopInfo>();
83 MachineFunctionPass::getAnalysisUsage(AU);
86 const char *getPassName() const {
87 return "Post RA top-down list latency scheduler";
90 bool runOnMachineFunction(MachineFunction &Fn);
92 char PostRAScheduler::ID = 0;
94 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
95 /// AvailableQueue - The priority queue to use for the available SUnits.
97 LatencyPriorityQueue AvailableQueue;
99 /// PendingQueue - This contains all of the instructions whose operands have
100 /// been issued, but their results are not ready yet (due to the latency of
101 /// the operation). Once the operands becomes available, the instruction is
102 /// added to the AvailableQueue.
103 std::vector<SUnit*> PendingQueue;
105 /// Topo - A topological ordering for SUnits.
106 ScheduleDAGTopologicalSort Topo;
108 /// AllocatableSet - The set of allocatable registers.
109 /// We'll be ignoring anti-dependencies on non-allocatable registers,
110 /// because they may not be safe to break.
111 const BitVector AllocatableSet;
113 /// HazardRec - The hazard recognizer to use.
114 ScheduleHazardRecognizer *HazardRec;
116 /// Classes - For live regs that are only used in one register class in a
117 /// live range, the register class. If the register is not live, the
118 /// corresponding value is null. If the register is live but used in
119 /// multiple register classes, the corresponding value is -1 casted to a
121 const TargetRegisterClass *
122 Classes[TargetRegisterInfo::FirstVirtualRegister];
124 /// RegRegs - Map registers to all their references within a live range.
125 std::multimap<unsigned, MachineOperand *> RegRefs;
127 /// KillIndices - The index of the most recent kill (proceding bottom-up),
128 /// or ~0u if the register is not live.
129 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
131 /// DefIndices - The index of the most recent complete def (proceding bottom
132 /// up), or ~0u if the register is live.
133 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
135 /// KeepRegs - A set of registers which are live and cannot be changed to
136 /// break anti-dependencies.
137 SmallSet<unsigned, 4> KeepRegs;
140 SchedulePostRATDList(MachineFunction &MF,
141 const MachineLoopInfo &MLI,
142 const MachineDominatorTree &MDT,
143 ScheduleHazardRecognizer *HR)
144 : ScheduleDAGInstrs(MF, MLI, MDT), Topo(SUnits),
145 AllocatableSet(TRI->getAllocatableSet(MF)),
148 ~SchedulePostRATDList() {
152 /// StartBlock - Initialize register live-range state for scheduling in
155 void StartBlock(MachineBasicBlock *BB);
157 /// Schedule - Schedule the instruction range using list scheduling.
161 /// FixupKills - Fix register kill flags that have been made
162 /// invalid due to scheduling
164 void FixupKills(MachineBasicBlock *MBB);
166 /// Observe - Update liveness information to account for the current
167 /// instruction, which will not be scheduled.
169 void Observe(MachineInstr *MI, unsigned Count);
171 /// FinishBlock - Clean up register live-range state.
176 void PrescanInstruction(MachineInstr *MI);
177 void ScanInstruction(MachineInstr *MI, unsigned Count);
178 void ReleaseSucc(SUnit *SU, SDep *SuccEdge);
179 void ReleaseSuccessors(SUnit *SU);
180 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
181 void ListScheduleTopDown();
182 bool BreakAntiDependencies();
183 unsigned findSuitableFreeRegister(unsigned AntiDepReg,
185 const TargetRegisterClass *);
186 void StartBlockForKills(MachineBasicBlock *BB);
188 // ToggleKillFlag - Toggle a register operand kill flag. Other
189 // adjustments may be made to the instruction if necessary. Return
190 // true if the operand has been deleted, false if not.
191 bool ToggleKillFlag(MachineInstr *MI, MachineOperand &MO);
195 /// isSchedulingBoundary - Test if the given instruction should be
196 /// considered a scheduling boundary. This primarily includes labels
199 static bool isSchedulingBoundary(const MachineInstr *MI,
200 const MachineFunction &MF) {
201 // Terminators and labels can't be scheduled around.
202 if (MI->getDesc().isTerminator() || MI->isLabel())
205 // Don't attempt to schedule around any instruction that modifies
206 // a stack-oriented pointer, as it's unlikely to be profitable. This
207 // saves compile time, because it doesn't require every single
208 // stack slot reference to depend on the instruction that does the
210 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
211 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore()))
217 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
218 // Check that post-RA scheduling is enabled for this function
219 const TargetSubtarget &ST = Fn.getTarget().getSubtarget<TargetSubtarget>();
220 if (!ST.enablePostRAScheduler())
223 DEBUG(errs() << "PostRAScheduler\n");
225 const MachineLoopInfo &MLI = getAnalysis<MachineLoopInfo>();
226 const MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
227 const InstrItineraryData &InstrItins = Fn.getTarget().getInstrItineraryData();
228 ScheduleHazardRecognizer *HR = EnablePostRAHazardAvoidance ?
229 (ScheduleHazardRecognizer *)new ExactHazardRecognizer(InstrItins) :
230 (ScheduleHazardRecognizer *)new SimpleHazardRecognizer();
232 SchedulePostRATDList Scheduler(Fn, MLI, MDT, HR);
234 // Loop over all of the basic blocks
235 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
236 MBB != MBBe; ++MBB) {
238 // If DebugDiv > 0 then only schedule MBB with (ID % DebugDiv) == DebugMod
240 static int bbcnt = 0;
241 if (bbcnt++ % DebugDiv != DebugMod)
243 errs() << "*** DEBUG scheduling " << Fn.getFunction()->getNameStr() <<
244 ":MBB ID#" << MBB->getNumber() << " ***\n";
248 // Initialize register live-range state for scheduling in this block.
249 Scheduler.StartBlock(MBB);
251 // Schedule each sequence of instructions not interrupted by a label
252 // or anything else that effectively needs to shut down scheduling.
253 MachineBasicBlock::iterator Current = MBB->end();
254 unsigned Count = MBB->size(), CurrentCount = Count;
255 for (MachineBasicBlock::iterator I = Current; I != MBB->begin(); ) {
256 MachineInstr *MI = prior(I);
257 if (isSchedulingBoundary(MI, Fn)) {
258 Scheduler.Run(MBB, I, Current, CurrentCount);
259 Scheduler.EmitSchedule(0);
261 CurrentCount = Count - 1;
262 Scheduler.Observe(MI, CurrentCount);
267 assert(Count == 0 && "Instruction count mismatch!");
268 assert((MBB->begin() == Current || CurrentCount != 0) &&
269 "Instruction count mismatch!");
270 Scheduler.Run(MBB, MBB->begin(), Current, CurrentCount);
271 Scheduler.EmitSchedule(0);
273 // Clean up register live-range state.
274 Scheduler.FinishBlock();
276 // Update register kills
277 Scheduler.FixupKills(MBB);
283 /// StartBlock - Initialize register live-range state for scheduling in
286 void SchedulePostRATDList::StartBlock(MachineBasicBlock *BB) {
287 // Call the superclass.
288 ScheduleDAGInstrs::StartBlock(BB);
290 // Reset the hazard recognizer.
293 // Clear out the register class data.
294 std::fill(Classes, array_endof(Classes),
295 static_cast<const TargetRegisterClass *>(0));
297 // Initialize the indices to indicate that no registers are live.
298 std::fill(KillIndices, array_endof(KillIndices), ~0u);
299 std::fill(DefIndices, array_endof(DefIndices), BB->size());
301 // Clear "do not change" set.
304 // Determine the live-out physregs for this block.
305 if (!BB->empty() && BB->back().getDesc().isReturn()) {
306 // In a return block, examine the function live-out regs.
307 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
308 E = MRI.liveout_end(); I != E; ++I) {
310 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
311 KillIndices[Reg] = BB->size();
312 DefIndices[Reg] = ~0u;
313 // Repeat, for all aliases.
314 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
315 unsigned AliasReg = *Alias;
316 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
317 KillIndices[AliasReg] = BB->size();
318 DefIndices[AliasReg] = ~0u;
322 // In a non-return block, examine the live-in regs of all successors.
323 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
324 SE = BB->succ_end(); SI != SE; ++SI)
325 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
326 E = (*SI)->livein_end(); I != E; ++I) {
328 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
329 KillIndices[Reg] = BB->size();
330 DefIndices[Reg] = ~0u;
331 // Repeat, for all aliases.
332 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
333 unsigned AliasReg = *Alias;
334 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
335 KillIndices[AliasReg] = BB->size();
336 DefIndices[AliasReg] = ~0u;
340 // Also mark as live-out any callee-saved registers that were not
341 // saved in the prolog.
342 const MachineFrameInfo *MFI = MF.getFrameInfo();
343 BitVector Pristine = MFI->getPristineRegs(BB);
344 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
346 if (!Pristine.test(Reg)) continue;
347 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
348 KillIndices[Reg] = BB->size();
349 DefIndices[Reg] = ~0u;
350 // Repeat, for all aliases.
351 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
352 unsigned AliasReg = *Alias;
353 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
354 KillIndices[AliasReg] = BB->size();
355 DefIndices[AliasReg] = ~0u;
361 /// Schedule - Schedule the instruction range using list scheduling.
363 void SchedulePostRATDList::Schedule() {
364 DEBUG(errs() << "********** List Scheduling **********\n");
366 // Build the scheduling graph.
369 if (EnableAntiDepBreaking) {
370 if (BreakAntiDependencies()) {
371 // We made changes. Update the dependency graph.
372 // Theoretically we could update the graph in place:
373 // When a live range is changed to use a different register, remove
374 // the def's anti-dependence *and* output-dependence edges due to
375 // that register, and add new anti-dependence and output-dependence
376 // edges based on the next live range of the register.
384 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
385 SUnits[su].dumpAll(this));
387 AvailableQueue.initNodes(SUnits);
389 ListScheduleTopDown();
391 AvailableQueue.releaseState();
394 /// Observe - Update liveness information to account for the current
395 /// instruction, which will not be scheduled.
397 void SchedulePostRATDList::Observe(MachineInstr *MI, unsigned Count) {
398 assert(Count < InsertPosIndex && "Instruction index out of expected range!");
400 // Any register which was defined within the previous scheduling region
401 // may have been rescheduled and its lifetime may overlap with registers
402 // in ways not reflected in our current liveness state. For each such
403 // register, adjust the liveness state to be conservatively correct.
404 for (unsigned Reg = 0; Reg != TargetRegisterInfo::FirstVirtualRegister; ++Reg)
405 if (DefIndices[Reg] < InsertPosIndex && DefIndices[Reg] >= Count) {
406 assert(KillIndices[Reg] == ~0u && "Clobbered register is live!");
407 // Mark this register to be non-renamable.
408 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
409 // Move the def index to the end of the previous region, to reflect
410 // that the def could theoretically have been scheduled at the end.
411 DefIndices[Reg] = InsertPosIndex;
414 PrescanInstruction(MI);
415 ScanInstruction(MI, Count);
418 /// FinishBlock - Clean up register live-range state.
420 void SchedulePostRATDList::FinishBlock() {
423 // Call the superclass.
424 ScheduleDAGInstrs::FinishBlock();
427 /// CriticalPathStep - Return the next SUnit after SU on the bottom-up
429 static SDep *CriticalPathStep(SUnit *SU) {
431 unsigned NextDepth = 0;
432 // Find the predecessor edge with the greatest depth.
433 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
435 SUnit *PredSU = P->getSUnit();
436 unsigned PredLatency = P->getLatency();
437 unsigned PredTotalLatency = PredSU->getDepth() + PredLatency;
438 // In the case of a latency tie, prefer an anti-dependency edge over
439 // other types of edges.
440 if (NextDepth < PredTotalLatency ||
441 (NextDepth == PredTotalLatency && P->getKind() == SDep::Anti)) {
442 NextDepth = PredTotalLatency;
449 void SchedulePostRATDList::PrescanInstruction(MachineInstr *MI) {
450 // Scan the register operands for this instruction and update
451 // Classes and RegRefs.
452 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
453 MachineOperand &MO = MI->getOperand(i);
454 if (!MO.isReg()) continue;
455 unsigned Reg = MO.getReg();
456 if (Reg == 0) continue;
457 const TargetRegisterClass *NewRC = 0;
459 if (i < MI->getDesc().getNumOperands())
460 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
462 // For now, only allow the register to be changed if its register
463 // class is consistent across all uses.
464 if (!Classes[Reg] && NewRC)
465 Classes[Reg] = NewRC;
466 else if (!NewRC || Classes[Reg] != NewRC)
467 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
469 // Now check for aliases.
470 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
471 // If an alias of the reg is used during the live range, give up.
472 // Note that this allows us to skip checking if AntiDepReg
473 // overlaps with any of the aliases, among other things.
474 unsigned AliasReg = *Alias;
475 if (Classes[AliasReg]) {
476 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
477 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
481 // If we're still willing to consider this register, note the reference.
482 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
483 RegRefs.insert(std::make_pair(Reg, &MO));
485 // It's not safe to change register allocation for source operands of
486 // that have special allocation requirements.
487 if (MO.isUse() && MI->getDesc().hasExtraSrcRegAllocReq()) {
488 if (KeepRegs.insert(Reg)) {
489 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
491 KeepRegs.insert(*Subreg);
497 void SchedulePostRATDList::ScanInstruction(MachineInstr *MI,
500 // Proceding upwards, registers that are defed but not used in this
501 // instruction are now dead.
502 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
503 MachineOperand &MO = MI->getOperand(i);
504 if (!MO.isReg()) continue;
505 unsigned Reg = MO.getReg();
506 if (Reg == 0) continue;
507 if (!MO.isDef()) continue;
508 // Ignore two-addr defs.
509 if (MI->isRegTiedToUseOperand(i)) continue;
511 DefIndices[Reg] = Count;
512 KillIndices[Reg] = ~0u;
513 assert(((KillIndices[Reg] == ~0u) !=
514 (DefIndices[Reg] == ~0u)) &&
515 "Kill and Def maps aren't consistent for Reg!");
519 // Repeat, for all subregs.
520 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
522 unsigned SubregReg = *Subreg;
523 DefIndices[SubregReg] = Count;
524 KillIndices[SubregReg] = ~0u;
525 KeepRegs.erase(SubregReg);
526 Classes[SubregReg] = 0;
527 RegRefs.erase(SubregReg);
529 // Conservatively mark super-registers as unusable.
530 for (const unsigned *Super = TRI->getSuperRegisters(Reg);
532 unsigned SuperReg = *Super;
533 Classes[SuperReg] = reinterpret_cast<TargetRegisterClass *>(-1);
536 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
537 MachineOperand &MO = MI->getOperand(i);
538 if (!MO.isReg()) continue;
539 unsigned Reg = MO.getReg();
540 if (Reg == 0) continue;
541 if (!MO.isUse()) continue;
543 const TargetRegisterClass *NewRC = 0;
544 if (i < MI->getDesc().getNumOperands())
545 NewRC = MI->getDesc().OpInfo[i].getRegClass(TRI);
547 // For now, only allow the register to be changed if its register
548 // class is consistent across all uses.
549 if (!Classes[Reg] && NewRC)
550 Classes[Reg] = NewRC;
551 else if (!NewRC || Classes[Reg] != NewRC)
552 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
554 RegRefs.insert(std::make_pair(Reg, &MO));
556 // It wasn't previously live but now it is, this is a kill.
557 if (KillIndices[Reg] == ~0u) {
558 KillIndices[Reg] = Count;
559 DefIndices[Reg] = ~0u;
560 assert(((KillIndices[Reg] == ~0u) !=
561 (DefIndices[Reg] == ~0u)) &&
562 "Kill and Def maps aren't consistent for Reg!");
564 // Repeat, for all aliases.
565 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
566 unsigned AliasReg = *Alias;
567 if (KillIndices[AliasReg] == ~0u) {
568 KillIndices[AliasReg] = Count;
569 DefIndices[AliasReg] = ~0u;
576 SchedulePostRATDList::findSuitableFreeRegister(unsigned AntiDepReg,
578 const TargetRegisterClass *RC) {
579 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(MF),
580 RE = RC->allocation_order_end(MF); R != RE; ++R) {
581 unsigned NewReg = *R;
582 // Don't replace a register with itself.
583 if (NewReg == AntiDepReg) continue;
584 // Don't replace a register with one that was recently used to repair
585 // an anti-dependence with this AntiDepReg, because that would
586 // re-introduce that anti-dependence.
587 if (NewReg == LastNewReg) continue;
588 // If NewReg is dead and NewReg's most recent def is not before
589 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
590 assert(((KillIndices[AntiDepReg] == ~0u) != (DefIndices[AntiDepReg] == ~0u)) &&
591 "Kill and Def maps aren't consistent for AntiDepReg!");
592 assert(((KillIndices[NewReg] == ~0u) != (DefIndices[NewReg] == ~0u)) &&
593 "Kill and Def maps aren't consistent for NewReg!");
594 if (KillIndices[NewReg] != ~0u ||
595 Classes[NewReg] == reinterpret_cast<TargetRegisterClass *>(-1) ||
596 KillIndices[AntiDepReg] > DefIndices[NewReg])
601 // No registers are free and available!
605 /// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
606 /// of the ScheduleDAG and break them by renaming registers.
608 bool SchedulePostRATDList::BreakAntiDependencies() {
609 // The code below assumes that there is at least one instruction,
610 // so just duck out immediately if the block is empty.
611 if (SUnits.empty()) return false;
613 // Find the node at the bottom of the critical path.
615 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
616 SUnit *SU = &SUnits[i];
617 if (!Max || SU->getDepth() + SU->Latency > Max->getDepth() + Max->Latency)
621 DEBUG(errs() << "Critical path has total latency "
622 << (Max->getDepth() + Max->Latency) << "\n");
624 // Track progress along the critical path through the SUnit graph as we walk
626 SUnit *CriticalPathSU = Max;
627 MachineInstr *CriticalPathMI = CriticalPathSU->getInstr();
629 // Consider this pattern:
638 // There are three anti-dependencies here, and without special care,
639 // we'd break all of them using the same register:
648 // because at each anti-dependence, B is the first register that
649 // isn't A which is free. This re-introduces anti-dependencies
650 // at all but one of the original anti-dependencies that we were
651 // trying to break. To avoid this, keep track of the most recent
652 // register that each register was replaced with, avoid
653 // using it to repair an anti-dependence on the same register.
654 // This lets us produce this:
663 // This still has an anti-dependence on B, but at least it isn't on the
664 // original critical path.
666 // TODO: If we tracked more than one register here, we could potentially
667 // fix that remaining critical edge too. This is a little more involved,
668 // because unlike the most recent register, less recent registers should
669 // still be considered, though only if no other registers are available.
670 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
672 // Attempt to break anti-dependence edges on the critical path. Walk the
673 // instructions from the bottom up, tracking information about liveness
674 // as we go to help determine which registers are available.
675 bool Changed = false;
676 unsigned Count = InsertPosIndex - 1;
677 for (MachineBasicBlock::iterator I = InsertPos, E = Begin;
679 MachineInstr *MI = --I;
681 // Check if this instruction has a dependence on the critical path that
682 // is an anti-dependence that we may be able to break. If it is, set
683 // AntiDepReg to the non-zero register associated with the anti-dependence.
685 // We limit our attention to the critical path as a heuristic to avoid
686 // breaking anti-dependence edges that aren't going to significantly
687 // impact the overall schedule. There are a limited number of registers
688 // and we want to save them for the important edges.
690 // TODO: Instructions with multiple defs could have multiple
691 // anti-dependencies. The current code here only knows how to break one
692 // edge per instruction. Note that we'd have to be able to break all of
693 // the anti-dependencies in an instruction in order to be effective.
694 unsigned AntiDepReg = 0;
695 if (MI == CriticalPathMI) {
696 if (SDep *Edge = CriticalPathStep(CriticalPathSU)) {
697 SUnit *NextSU = Edge->getSUnit();
699 // Only consider anti-dependence edges.
700 if (Edge->getKind() == SDep::Anti) {
701 AntiDepReg = Edge->getReg();
702 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
703 if (!AllocatableSet.test(AntiDepReg))
704 // Don't break anti-dependencies on non-allocatable registers.
706 else if (KeepRegs.count(AntiDepReg))
707 // Don't break anti-dependencies if an use down below requires
708 // this exact register.
711 // If the SUnit has other dependencies on the SUnit that it
712 // anti-depends on, don't bother breaking the anti-dependency
713 // since those edges would prevent such units from being
714 // scheduled past each other regardless.
716 // Also, if there are dependencies on other SUnits with the
717 // same register as the anti-dependency, don't attempt to
719 for (SUnit::pred_iterator P = CriticalPathSU->Preds.begin(),
720 PE = CriticalPathSU->Preds.end(); P != PE; ++P)
721 if (P->getSUnit() == NextSU ?
722 (P->getKind() != SDep::Anti || P->getReg() != AntiDepReg) :
723 (P->getKind() == SDep::Data && P->getReg() == AntiDepReg)) {
729 CriticalPathSU = NextSU;
730 CriticalPathMI = CriticalPathSU->getInstr();
732 // We've reached the end of the critical path.
738 PrescanInstruction(MI);
740 if (MI->getDesc().hasExtraDefRegAllocReq())
741 // If this instruction's defs have special allocation requirement, don't
742 // break this anti-dependency.
744 else if (AntiDepReg) {
745 // If this instruction has a use of AntiDepReg, breaking it
747 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
748 MachineOperand &MO = MI->getOperand(i);
749 if (!MO.isReg()) continue;
750 unsigned Reg = MO.getReg();
751 if (Reg == 0) continue;
752 if (MO.isUse() && AntiDepReg == Reg) {
759 // Determine AntiDepReg's register class, if it is live and is
760 // consistently used within a single class.
761 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
762 assert((AntiDepReg == 0 || RC != NULL) &&
763 "Register should be live if it's causing an anti-dependence!");
764 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
767 // Look for a suitable register to use to break the anti-depenence.
769 // TODO: Instead of picking the first free register, consider which might
771 if (AntiDepReg != 0) {
772 if (unsigned NewReg = findSuitableFreeRegister(AntiDepReg,
773 LastNewReg[AntiDepReg],
775 DEBUG(errs() << "Breaking anti-dependence edge on "
776 << TRI->getName(AntiDepReg)
777 << " with " << RegRefs.count(AntiDepReg) << " references"
778 << " using " << TRI->getName(NewReg) << "!\n");
780 // Update the references to the old register to refer to the new
782 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
783 std::multimap<unsigned, MachineOperand *>::iterator>
784 Range = RegRefs.equal_range(AntiDepReg);
785 for (std::multimap<unsigned, MachineOperand *>::iterator
786 Q = Range.first, QE = Range.second; Q != QE; ++Q)
787 Q->second->setReg(NewReg);
789 // We just went back in time and modified history; the
790 // liveness information for the anti-depenence reg is now
791 // inconsistent. Set the state as if it were dead.
792 Classes[NewReg] = Classes[AntiDepReg];
793 DefIndices[NewReg] = DefIndices[AntiDepReg];
794 KillIndices[NewReg] = KillIndices[AntiDepReg];
795 assert(((KillIndices[NewReg] == ~0u) !=
796 (DefIndices[NewReg] == ~0u)) &&
797 "Kill and Def maps aren't consistent for NewReg!");
799 Classes[AntiDepReg] = 0;
800 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
801 KillIndices[AntiDepReg] = ~0u;
802 assert(((KillIndices[AntiDepReg] == ~0u) !=
803 (DefIndices[AntiDepReg] == ~0u)) &&
804 "Kill and Def maps aren't consistent for AntiDepReg!");
806 RegRefs.erase(AntiDepReg);
808 LastNewReg[AntiDepReg] = NewReg;
812 ScanInstruction(MI, Count);
818 /// StartBlockForKills - Initialize register live-range state for updating kills
820 void SchedulePostRATDList::StartBlockForKills(MachineBasicBlock *BB) {
821 // Initialize the indices to indicate that no registers are live.
822 std::fill(KillIndices, array_endof(KillIndices), ~0u);
824 // Determine the live-out physregs for this block.
825 if (!BB->empty() && BB->back().getDesc().isReturn()) {
826 // In a return block, examine the function live-out regs.
827 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
828 E = MRI.liveout_end(); I != E; ++I) {
830 KillIndices[Reg] = BB->size();
831 // Repeat, for all subregs.
832 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
834 KillIndices[*Subreg] = BB->size();
839 // In a non-return block, examine the live-in regs of all successors.
840 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
841 SE = BB->succ_end(); SI != SE; ++SI) {
842 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
843 E = (*SI)->livein_end(); I != E; ++I) {
845 KillIndices[Reg] = BB->size();
846 // Repeat, for all subregs.
847 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
849 KillIndices[*Subreg] = BB->size();
856 bool SchedulePostRATDList::ToggleKillFlag(MachineInstr *MI,
857 MachineOperand &MO) {
858 // Setting kill flag...
864 // If MO itself is live, clear the kill flag...
865 if (KillIndices[MO.getReg()] != ~0u) {
870 // If any subreg of MO is live, then create an imp-def for that
871 // subreg and keep MO marked as killed.
873 const unsigned SuperReg = MO.getReg();
874 for (const unsigned *Subreg = TRI->getSubRegisters(SuperReg);
876 if (KillIndices[*Subreg] != ~0u) {
877 MI->addOperand(MachineOperand::CreateReg(*Subreg,
886 MO.setIsKill(AllDead);
890 /// FixupKills - Fix the register kill flags, they may have been made
891 /// incorrect by instruction reordering.
893 void SchedulePostRATDList::FixupKills(MachineBasicBlock *MBB) {
894 DEBUG(errs() << "Fixup kills for BB ID#" << MBB->getNumber() << '\n');
896 std::set<unsigned> killedRegs;
897 BitVector ReservedRegs = TRI->getReservedRegs(MF);
899 StartBlockForKills(MBB);
901 // Examine block from end to start...
902 unsigned Count = MBB->size();
903 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
905 MachineInstr *MI = --I;
907 // Update liveness. Registers that are defed but not used in this
908 // instruction are now dead. Mark register and all subregs as they
909 // are completely defined.
910 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
911 MachineOperand &MO = MI->getOperand(i);
912 if (!MO.isReg()) continue;
913 unsigned Reg = MO.getReg();
914 if (Reg == 0) continue;
915 if (!MO.isDef()) continue;
916 // Ignore two-addr defs.
917 if (MI->isRegTiedToUseOperand(i)) continue;
919 KillIndices[Reg] = ~0u;
921 // Repeat for all subregs.
922 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
924 KillIndices[*Subreg] = ~0u;
928 // Examine all used registers and set/clear kill flag. When a
929 // register is used multiple times we only set the kill flag on
932 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
933 MachineOperand &MO = MI->getOperand(i);
934 if (!MO.isReg() || !MO.isUse()) continue;
935 unsigned Reg = MO.getReg();
936 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
939 if (killedRegs.find(Reg) == killedRegs.end()) {
941 // A register is not killed if any subregs are live...
942 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
944 if (KillIndices[*Subreg] != ~0u) {
950 // If subreg is not live, then register is killed if it became
951 // live in this instruction
953 kill = (KillIndices[Reg] == ~0u);
956 if (MO.isKill() != kill) {
957 bool removed = ToggleKillFlag(MI, MO);
959 DEBUG(errs() << "Fixed <removed> in ");
961 DEBUG(errs() << "Fixed " << MO << " in ");
966 killedRegs.insert(Reg);
969 // Mark any used register (that is not using undef) and subregs as
971 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
972 MachineOperand &MO = MI->getOperand(i);
973 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
974 unsigned Reg = MO.getReg();
975 if ((Reg == 0) || ReservedRegs.test(Reg)) continue;
977 KillIndices[Reg] = Count;
979 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
981 KillIndices[*Subreg] = Count;
987 //===----------------------------------------------------------------------===//
988 // Top-Down Scheduling
989 //===----------------------------------------------------------------------===//
991 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
992 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
993 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SDep *SuccEdge) {
994 SUnit *SuccSU = SuccEdge->getSUnit();
997 if (SuccSU->NumPredsLeft == 0) {
998 errs() << "*** Scheduling failed! ***\n";
1000 errs() << " has been released too many times!\n";
1001 llvm_unreachable(0);
1004 --SuccSU->NumPredsLeft;
1006 // Compute how many cycles it will be before this actually becomes
1007 // available. This is the max of the start time of all predecessors plus
1009 SuccSU->setDepthToAtLeast(SU->getDepth() + SuccEdge->getLatency());
1011 // If all the node's predecessors are scheduled, this node is ready
1012 // to be scheduled. Ignore the special ExitSU node.
1013 if (SuccSU->NumPredsLeft == 0 && SuccSU != &ExitSU)
1014 PendingQueue.push_back(SuccSU);
1017 /// ReleaseSuccessors - Call ReleaseSucc on each of SU's successors.
1018 void SchedulePostRATDList::ReleaseSuccessors(SUnit *SU) {
1019 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1021 ReleaseSucc(SU, &*I);
1024 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1025 /// count of its successors. If a successor pending count is zero, add it to
1026 /// the Available queue.
1027 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
1028 DEBUG(errs() << "*** Scheduling [" << CurCycle << "]: ");
1029 DEBUG(SU->dump(this));
1031 Sequence.push_back(SU);
1032 assert(CurCycle >= SU->getDepth() && "Node scheduled above its depth!");
1033 SU->setDepthToAtLeast(CurCycle);
1035 ReleaseSuccessors(SU);
1036 SU->isScheduled = true;
1037 AvailableQueue.ScheduledNode(SU);
1040 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1042 void SchedulePostRATDList::ListScheduleTopDown() {
1043 unsigned CurCycle = 0;
1045 // Release any successors of the special Entry node.
1046 ReleaseSuccessors(&EntrySU);
1048 // All leaves to Available queue.
1049 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1050 // It is available if it has no predecessors.
1051 if (SUnits[i].Preds.empty()) {
1052 AvailableQueue.push(&SUnits[i]);
1053 SUnits[i].isAvailable = true;
1057 // In any cycle where we can't schedule any instructions, we must
1058 // stall or emit a noop, depending on the target.
1059 bool CycleHasInsts = false;
1061 // While Available queue is not empty, grab the node with the highest
1062 // priority. If it is not ready put it back. Schedule the node.
1063 std::vector<SUnit*> NotReady;
1064 Sequence.reserve(SUnits.size());
1065 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
1066 // Check to see if any of the pending instructions are ready to issue. If
1067 // so, add them to the available queue.
1068 unsigned MinDepth = ~0u;
1069 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
1070 if (PendingQueue[i]->getDepth() <= CurCycle) {
1071 AvailableQueue.push(PendingQueue[i]);
1072 PendingQueue[i]->isAvailable = true;
1073 PendingQueue[i] = PendingQueue.back();
1074 PendingQueue.pop_back();
1076 } else if (PendingQueue[i]->getDepth() < MinDepth)
1077 MinDepth = PendingQueue[i]->getDepth();
1080 DEBUG(errs() << "\n*** Examining Available\n";
1081 LatencyPriorityQueue q = AvailableQueue;
1082 while (!q.empty()) {
1083 SUnit *su = q.pop();
1084 errs() << "Height " << su->getHeight() << ": ";
1088 SUnit *FoundSUnit = 0;
1090 bool HasNoopHazards = false;
1091 while (!AvailableQueue.empty()) {
1092 SUnit *CurSUnit = AvailableQueue.pop();
1094 ScheduleHazardRecognizer::HazardType HT =
1095 HazardRec->getHazardType(CurSUnit);
1096 if (HT == ScheduleHazardRecognizer::NoHazard) {
1097 FoundSUnit = CurSUnit;
1101 // Remember if this is a noop hazard.
1102 HasNoopHazards |= HT == ScheduleHazardRecognizer::NoopHazard;
1104 NotReady.push_back(CurSUnit);
1107 // Add the nodes that aren't ready back onto the available list.
1108 if (!NotReady.empty()) {
1109 AvailableQueue.push_all(NotReady);
1113 // If we found a node to schedule, do it now.
1115 ScheduleNodeTopDown(FoundSUnit, CurCycle);
1116 HazardRec->EmitInstruction(FoundSUnit);
1117 CycleHasInsts = true;
1119 // If we are using the target-specific hazards, then don't
1120 // advance the cycle time just because we schedule a node. If
1121 // the target allows it we can schedule multiple nodes in the
1123 if (!EnablePostRAHazardAvoidance) {
1124 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
1128 if (CycleHasInsts) {
1129 DEBUG(errs() << "*** Finished cycle " << CurCycle << '\n');
1130 HazardRec->AdvanceCycle();
1131 } else if (!HasNoopHazards) {
1132 // Otherwise, we have a pipeline stall, but no other problem,
1133 // just advance the current cycle and try again.
1134 DEBUG(errs() << "*** Stall in cycle " << CurCycle << '\n');
1135 HazardRec->AdvanceCycle();
1138 // Otherwise, we have no instructions to issue and we have instructions
1139 // that will fault if we don't do this right. This is the case for
1140 // processors without pipeline interlocks and other cases.
1141 DEBUG(errs() << "*** Emitting noop in cycle " << CurCycle << '\n');
1142 HazardRec->EmitNoop();
1143 Sequence.push_back(0); // NULL here means noop
1148 CycleHasInsts = false;
1153 VerifySchedule(/*isBottomUp=*/false);
1157 //===----------------------------------------------------------------------===//
1158 // Public Constructor Functions
1159 //===----------------------------------------------------------------------===//
1161 FunctionPass *llvm::createPostRAScheduler() {
1162 return new PostRAScheduler();