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 "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
24 #include "llvm/CodeGen/LatencyPriorityQueue.h"
25 #include "llvm/CodeGen/SchedulerRegistry.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/DenseSet.h"
38 STATISTIC(NumStalls, "Number of pipeline stalls");
41 EnableAntiDepBreaking("break-anti-dependencies",
42 cl::desc("Break scheduling anti-dependencies"),
46 class VISIBILITY_HIDDEN PostRAScheduler : public MachineFunctionPass {
49 PostRAScheduler() : MachineFunctionPass(&ID) {}
51 const char *getPassName() const {
52 return "Post RA top-down list latency scheduler";
55 bool runOnMachineFunction(MachineFunction &Fn);
57 char PostRAScheduler::ID = 0;
59 class VISIBILITY_HIDDEN SchedulePostRATDList : public ScheduleDAGInstrs {
60 /// AvailableQueue - The priority queue to use for the available SUnits.
62 LatencyPriorityQueue AvailableQueue;
64 /// PendingQueue - This contains all of the instructions whose operands have
65 /// been issued, but their results are not ready yet (due to the latency of
66 /// the operation). Once the operands becomes available, the instruction is
67 /// added to the AvailableQueue.
68 std::vector<SUnit*> PendingQueue;
70 /// Topo - A topological ordering for SUnits.
71 ScheduleDAGTopologicalSort Topo;
74 SchedulePostRATDList(MachineBasicBlock *mbb, const TargetMachine &tm)
75 : ScheduleDAGInstrs(mbb, tm), Topo(SUnits) {}
80 void ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain);
81 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
82 void ListScheduleTopDown();
83 bool BreakAntiDependencies();
87 bool PostRAScheduler::runOnMachineFunction(MachineFunction &Fn) {
88 DOUT << "PostRAScheduler\n";
90 // Loop over all of the basic blocks
91 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
94 SchedulePostRATDList Scheduler(MBB, Fn.getTarget());
98 Scheduler.EmitSchedule();
104 /// Schedule - Schedule the DAG using list scheduling.
105 void SchedulePostRATDList::Schedule() {
106 DOUT << "********** List Scheduling **********\n";
108 // Build scheduling units.
111 if (EnableAntiDepBreaking) {
112 if (BreakAntiDependencies()) {
113 // We made changes. Update the dependency graph.
114 // Theoretically we could update the graph in place:
115 // When a live range is changed to use a different register, remove
116 // the def's anti-dependence *and* output-dependence edges due to
117 // that register, and add new anti-dependence and output-dependence
118 // edges based on the next live range of the register.
124 AvailableQueue.initNodes(SUnits);
126 ListScheduleTopDown();
128 AvailableQueue.releaseState();
131 /// getInstrOperandRegClass - Return register class of the operand of an
132 /// instruction of the specified TargetInstrDesc.
133 static const TargetRegisterClass*
134 getInstrOperandRegClass(const TargetRegisterInfo *TRI,
135 const TargetInstrInfo *TII, const TargetInstrDesc &II,
137 if (Op >= II.getNumOperands())
139 if (II.OpInfo[Op].isLookupPtrRegClass())
140 return TII->getPointerRegClass();
141 return TRI->getRegClass(II.OpInfo[Op].RegClass);
144 /// BreakAntiDependencies - Identifiy anti-dependencies along the critical path
145 /// of the ScheduleDAG and break them by renaming registers.
147 bool SchedulePostRATDList::BreakAntiDependencies() {
148 // The code below assumes that there is at least one instruction,
149 // so just duck out immediately if the block is empty.
150 if (BB->empty()) return false;
152 Topo.InitDAGTopologicalSorting();
154 // Compute a critical path for the DAG.
156 std::vector<SDep *> CriticalPath(SUnits.size());
157 for (ScheduleDAGTopologicalSort::const_iterator I = Topo.begin(),
158 E = Topo.end(); I != E; ++I) {
159 SUnit *SU = &SUnits[*I];
160 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
162 SUnit *PredSU = P->Dep;
163 // This assumes that there's no delay for reusing registers.
164 unsigned PredLatency = (P->isCtrl && P->Reg != 0) ? 1 : PredSU->Latency;
165 unsigned PredTotalLatency = PredSU->CycleBound + PredLatency;
166 if (SU->CycleBound < PredTotalLatency ||
167 (SU->CycleBound == PredTotalLatency && !P->isAntiDep)) {
168 SU->CycleBound = PredTotalLatency;
169 CriticalPath[*I] = &*P;
172 // Keep track of the node at the end of the critical path.
173 if (!Max || SU->CycleBound + SU->Latency > Max->CycleBound + Max->Latency)
177 DOUT << "Critical path has total latency "
178 << (Max ? Max->CycleBound + Max->Latency : 0) << "\n";
180 // Walk the critical path from the bottom up. Collect all anti-dependence
181 // edges on the critical path. Skip anti-dependencies between SUnits that
182 // are connected with other edges, since such units won't be able to be
183 // scheduled past each other anyway.
185 // The heuristic is that edges on the critical path are more important to
186 // break than other edges. And since there are a limited number of
187 // registers, we don't want to waste them breaking edges that aren't
190 // TODO: Instructions with multiple defs could have multiple
191 // anti-dependencies. The current code here only knows how to break one
192 // edge per instruction. Note that we'd have to be able to break all of
193 // the anti-dependencies in an instruction in order to be effective.
194 BitVector AllocatableSet = TRI->getAllocatableSet(*MF);
195 DenseMap<MachineInstr *, unsigned> CriticalAntiDeps;
196 for (SUnit *SU = Max; CriticalPath[SU->NodeNum];
197 SU = CriticalPath[SU->NodeNum]->Dep) {
198 SDep *Edge = CriticalPath[SU->NodeNum];
199 SUnit *NextSU = Edge->Dep;
200 unsigned AntiDepReg = Edge->Reg;
201 // Only consider anti-dependence edges.
202 if (!Edge->isAntiDep)
204 assert(AntiDepReg != 0 && "Anti-dependence on reg0?");
205 // Don't break anti-dependencies on non-allocatable registers.
206 if (!AllocatableSet.test(AntiDepReg))
208 // If the SUnit has other dependencies on the SUnit that it
209 // anti-depends on, don't bother breaking the anti-dependency.
210 // Also, if there are dependencies on other SUnits with the
211 // same register as the anti-dependency, don't attempt to
213 for (SUnit::pred_iterator P = SU->Preds.begin(), PE = SU->Preds.end();
215 if (P->Dep == NextSU ?
216 (!P->isAntiDep || P->Reg != AntiDepReg) :
217 (!P->isCtrl && !P->isAntiDep && P->Reg == AntiDepReg)) {
222 CriticalAntiDeps[SU->getInstr()] = AntiDepReg;
225 // For live regs that are only used in one register class in a live range,
226 // the register class. If the register is not live, the corresponding value
227 // is null. If the register is live but used in multiple register classes,
228 // the corresponding value is -1 casted to a pointer.
229 const TargetRegisterClass *
230 Classes[TargetRegisterInfo::FirstVirtualRegister] = {};
232 // Map registers to all their references within a live range.
233 std::multimap<unsigned, MachineOperand *> RegRefs;
235 // The index of the most recent kill (proceding bottom-up), or -1 if
236 // the register is not live.
237 unsigned KillIndices[TargetRegisterInfo::FirstVirtualRegister];
238 std::fill(KillIndices, array_endof(KillIndices), -1);
239 // The index of the most recent def (proceding bottom up), or -1 if
240 // the register is live.
241 unsigned DefIndices[TargetRegisterInfo::FirstVirtualRegister];
242 std::fill(DefIndices, array_endof(DefIndices), BB->size());
244 // Determine the live-out physregs for this block.
245 if (!BB->empty() && BB->back().getDesc().isReturn())
246 // In a return block, examine the function live-out regs.
247 for (MachineRegisterInfo::liveout_iterator I = MRI.liveout_begin(),
248 E = MRI.liveout_end(); I != E; ++I) {
250 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
251 KillIndices[Reg] = BB->size();
252 DefIndices[Reg] = -1;
253 // Repeat, for all aliases.
254 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
255 unsigned AliasReg = *Alias;
256 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
257 KillIndices[AliasReg] = BB->size();
258 DefIndices[AliasReg] = -1;
262 // In a non-return block, examine the live-in regs of all successors.
263 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
264 SE = BB->succ_end(); SI != SE; ++SI)
265 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
266 E = (*SI)->livein_end(); I != E; ++I) {
268 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
269 KillIndices[Reg] = BB->size();
270 DefIndices[Reg] = -1;
271 // Repeat, for all aliases.
272 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
273 unsigned AliasReg = *Alias;
274 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
275 KillIndices[AliasReg] = BB->size();
276 DefIndices[AliasReg] = -1;
280 // Consider callee-saved registers as live-out, since we're running after
281 // prologue/epilogue insertion so there's no way to add additional
284 // TODO: If the callee saves and restores these, then we can potentially
285 // use them between the save and the restore. To do that, we could scan
286 // the exit blocks to see which of these registers are defined.
287 // Alternatively, calle-saved registers that aren't saved and restored
288 // could be marked live-in in every block.
289 for (const unsigned *I = TRI->getCalleeSavedRegs(); *I; ++I) {
291 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
292 KillIndices[Reg] = BB->size();
293 DefIndices[Reg] = -1;
294 // Repeat, for all aliases.
295 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
296 unsigned AliasReg = *Alias;
297 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
298 KillIndices[AliasReg] = BB->size();
299 DefIndices[AliasReg] = -1;
303 // Consider this pattern:
312 // There are three anti-dependencies here, and without special care,
313 // we'd break all of them using the same register:
322 // because at each anti-dependence, B is the first register that
323 // isn't A which is free. This re-introduces anti-dependencies
324 // at all but one of the original anti-dependencies that we were
325 // trying to break. To avoid this, keep track of the most recent
326 // register that each register was replaced with, avoid avoid
327 // using it to repair an anti-dependence on the same register.
328 // This lets us produce this:
337 // This still has an anti-dependence on B, but at least it isn't on the
338 // original critical path.
340 // TODO: If we tracked more than one register here, we could potentially
341 // fix that remaining critical edge too. This is a little more involved,
342 // because unlike the most recent register, less recent registers should
343 // still be considered, though only if no other registers are available.
344 unsigned LastNewReg[TargetRegisterInfo::FirstVirtualRegister] = {};
346 // A registers defined and not used in an instruction. This is used for
347 // liveness tracking and is declared outside the loop only to avoid
348 // having it be re-allocated on each iteration.
349 DenseSet<unsigned> Defs;
351 // Attempt to break anti-dependence edges on the critical path. Walk the
352 // instructions from the bottom up, tracking information about liveness
353 // as we go to help determine which registers are available.
354 bool Changed = false;
355 unsigned Count = BB->size() - 1;
356 for (MachineBasicBlock::reverse_iterator I = BB->rbegin(), E = BB->rend();
357 I != E; ++I, --Count) {
358 MachineInstr *MI = &*I;
360 // Check if this instruction has an anti-dependence that we're
362 DenseMap<MachineInstr *, unsigned>::iterator C = CriticalAntiDeps.find(MI);
363 unsigned AntiDepReg = C != CriticalAntiDeps.end() ?
366 // Scan the register operands for this instruction and update
367 // Classes and RegRefs.
368 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
369 MachineOperand &MO = MI->getOperand(i);
370 if (!MO.isReg()) continue;
371 unsigned Reg = MO.getReg();
372 if (Reg == 0) continue;
373 const TargetRegisterClass *NewRC =
374 getInstrOperandRegClass(TRI, TII, MI->getDesc(), i);
376 // If this instruction has a use of AntiDepReg, breaking it
378 if (MO.isUse() && AntiDepReg == Reg)
381 // For now, only allow the register to be changed if its register
382 // class is consistent across all uses.
383 if (!Classes[Reg] && NewRC)
384 Classes[Reg] = NewRC;
385 else if (!NewRC || Classes[Reg] != NewRC)
386 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
388 // Now check for aliases.
389 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
390 // If an alias of the reg is used during the live range, give up.
391 // Note that this allows us to skip checking if AntiDepReg
392 // overlaps with any of the aliases, among other things.
393 unsigned AliasReg = *Alias;
394 if (Classes[AliasReg]) {
395 Classes[AliasReg] = reinterpret_cast<TargetRegisterClass *>(-1);
396 Classes[Reg] = reinterpret_cast<TargetRegisterClass *>(-1);
400 // If we're still willing to consider this register, note the reference.
401 if (Classes[Reg] != reinterpret_cast<TargetRegisterClass *>(-1))
402 RegRefs.insert(std::make_pair(Reg, &MO));
405 // Determine AntiDepReg's register class, if it is live and is
406 // consistently used within a single class.
407 const TargetRegisterClass *RC = AntiDepReg != 0 ? Classes[AntiDepReg] : 0;
408 assert((AntiDepReg == 0 || RC != NULL) &&
409 "Register should be live if it's causing an anti-dependence!");
410 if (RC == reinterpret_cast<TargetRegisterClass *>(-1))
413 // Look for a suitable register to use to break the anti-depenence.
415 // TODO: Instead of picking the first free register, consider which might
417 if (AntiDepReg != 0) {
418 for (TargetRegisterClass::iterator R = RC->allocation_order_begin(*MF),
419 RE = RC->allocation_order_end(*MF); R != RE; ++R) {
420 unsigned NewReg = *R;
421 // Don't replace a register with itself.
422 if (NewReg == AntiDepReg) continue;
423 // Don't replace a register with one that was recently used to repair
424 // an anti-dependence with this AntiDepReg, because that would
425 // re-introduce that anti-dependence.
426 if (NewReg == LastNewReg[AntiDepReg]) continue;
427 // If NewReg is dead and NewReg's most recent def is not before
428 // AntiDepReg's kill, it's safe to replace AntiDepReg with NewReg.
429 assert(((KillIndices[AntiDepReg] == -1u) != (DefIndices[AntiDepReg] == -1u)) &&
430 "Kill and Def maps aren't consistent for AntiDepReg!");
431 assert(((KillIndices[NewReg] == -1u) != (DefIndices[NewReg] == -1u)) &&
432 "Kill and Def maps aren't consistent for NewReg!");
433 if (KillIndices[NewReg] == -1u &&
434 KillIndices[AntiDepReg] <= DefIndices[NewReg]) {
435 DOUT << "Breaking anti-dependence edge on reg " << AntiDepReg
436 << " with reg " << NewReg << "!\n";
438 // Update the references to the old register to refer to the new
440 std::pair<std::multimap<unsigned, MachineOperand *>::iterator,
441 std::multimap<unsigned, MachineOperand *>::iterator>
442 Range = RegRefs.equal_range(AntiDepReg);
443 for (std::multimap<unsigned, MachineOperand *>::iterator
444 Q = Range.first, QE = Range.second; Q != QE; ++Q)
445 Q->second->setReg(NewReg);
447 // We just went back in time and modified history; the
448 // liveness information for the anti-depenence reg is now
449 // inconsistent. Set the state as if it were dead.
450 Classes[NewReg] = Classes[AntiDepReg];
451 DefIndices[NewReg] = DefIndices[AntiDepReg];
452 KillIndices[NewReg] = KillIndices[AntiDepReg];
454 Classes[AntiDepReg] = 0;
455 DefIndices[AntiDepReg] = KillIndices[AntiDepReg];
456 KillIndices[AntiDepReg] = -1;
458 RegRefs.erase(AntiDepReg);
460 LastNewReg[AntiDepReg] = NewReg;
468 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
469 MachineOperand &MO = MI->getOperand(i);
470 if (!MO.isReg()) continue;
471 unsigned Reg = MO.getReg();
472 if (Reg == 0) continue;
476 // Treat a use in the same instruction as a def as an extension of
479 // It wasn't previously live but now it is, this is a kill.
480 if (KillIndices[Reg] == -1u) {
481 KillIndices[Reg] = Count;
482 DefIndices[Reg] = -1u;
484 // Repeat, for all aliases.
485 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
486 unsigned AliasReg = *Alias;
487 Defs.erase(AliasReg);
488 if (KillIndices[AliasReg] == -1u) {
489 KillIndices[AliasReg] = Count;
490 DefIndices[AliasReg] = -1u;
495 // Proceding upwards, registers that are defed but not used in this
496 // instruction are now dead.
497 for (DenseSet<unsigned>::iterator D = Defs.begin(), DE = Defs.end();
500 DefIndices[Reg] = Count;
501 KillIndices[Reg] = -1;
504 // Repeat, for all subregs.
505 for (const unsigned *Subreg = TRI->getSubRegisters(Reg);
507 unsigned SubregReg = *Subreg;
508 DefIndices[SubregReg] = Count;
509 KillIndices[SubregReg] = -1;
510 Classes[SubregReg] = 0;
511 RegRefs.erase(SubregReg);
515 assert(Count == -1u && "Count mismatch!");
520 //===----------------------------------------------------------------------===//
521 // Top-Down Scheduling
522 //===----------------------------------------------------------------------===//
524 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
525 /// the PendingQueue if the count reaches zero. Also update its cycle bound.
526 void SchedulePostRATDList::ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain) {
527 --SuccSU->NumPredsLeft;
530 if (SuccSU->NumPredsLeft < 0) {
531 cerr << "*** Scheduling failed! ***\n";
533 cerr << " has been released too many times!\n";
538 // Compute how many cycles it will be before this actually becomes
539 // available. This is the max of the start time of all predecessors plus
541 // If this is a token edge, we don't need to wait for the latency of the
542 // preceeding instruction (e.g. a long-latency load) unless there is also
543 // some other data dependence.
544 unsigned PredDoneCycle = SU->Cycle;
546 PredDoneCycle += SU->Latency;
547 else if (SU->Latency)
549 SuccSU->CycleBound = std::max(SuccSU->CycleBound, PredDoneCycle);
551 if (SuccSU->NumPredsLeft == 0) {
552 PendingQueue.push_back(SuccSU);
556 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
557 /// count of its successors. If a successor pending count is zero, add it to
558 /// the Available queue.
559 void SchedulePostRATDList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
560 DOUT << "*** Scheduling [" << CurCycle << "]: ";
561 DEBUG(SU->dump(this));
563 Sequence.push_back(SU);
564 SU->Cycle = CurCycle;
566 // Top down: release successors.
567 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
569 ReleaseSucc(SU, I->Dep, I->isCtrl);
571 SU->isScheduled = true;
572 AvailableQueue.ScheduledNode(SU);
575 /// ListScheduleTopDown - The main loop of list scheduling for top-down
577 void SchedulePostRATDList::ListScheduleTopDown() {
578 unsigned CurCycle = 0;
580 // All leaves to Available queue.
581 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
582 // It is available if it has no predecessors.
583 if (SUnits[i].Preds.empty()) {
584 AvailableQueue.push(&SUnits[i]);
585 SUnits[i].isAvailable = true;
589 // While Available queue is not empty, grab the node with the highest
590 // priority. If it is not ready put it back. Schedule the node.
591 Sequence.reserve(SUnits.size());
592 while (!AvailableQueue.empty() || !PendingQueue.empty()) {
593 // Check to see if any of the pending instructions are ready to issue. If
594 // so, add them to the available queue.
595 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
596 if (PendingQueue[i]->CycleBound == CurCycle) {
597 AvailableQueue.push(PendingQueue[i]);
598 PendingQueue[i]->isAvailable = true;
599 PendingQueue[i] = PendingQueue.back();
600 PendingQueue.pop_back();
603 assert(PendingQueue[i]->CycleBound > CurCycle && "Negative latency?");
607 // If there are no instructions available, don't try to issue anything.
608 if (AvailableQueue.empty()) {
613 SUnit *FoundSUnit = AvailableQueue.pop();
615 // If we found a node to schedule, do it now.
617 ScheduleNodeTopDown(FoundSUnit, CurCycle);
619 // If this is a pseudo-op node, we don't want to increment the current
621 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
624 // Otherwise, we have a pipeline stall, but no other problem, just advance
625 // the current cycle and try again.
626 DOUT << "*** Advancing cycle, no work to do\n";
633 VerifySchedule(/*isBottomUp=*/false);
637 //===----------------------------------------------------------------------===//
638 // Public Constructor Functions
639 //===----------------------------------------------------------------------===//
641 FunctionPass *llvm::createPostRAScheduler() {
642 return new PostRAScheduler();