1 //===---- ScheduleDAGList.cpp - Implement a list scheduler for isel DAG ---===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Evan Cheng and is distributed under the
6 // University of Illinois Open Source 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 "sched"
22 #include "llvm/CodeGen/ScheduleDAG.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Visibility.h"
30 #include "llvm/ADT/Statistic.h"
37 Statistic<> NumNoops ("scheduler", "Number of noops inserted");
38 Statistic<> NumStalls("scheduler", "Number of pipeline stalls");
42 //===----------------------------------------------------------------------===//
43 /// ScheduleDAGList - The actual list scheduler implementation. This supports
44 /// top-down scheduling.
46 class VISIBILITY_HIDDEN ScheduleDAGList : public ScheduleDAG {
48 /// AvailableQueue - The priority queue to use for the available SUnits.
50 SchedulingPriorityQueue *AvailableQueue;
52 /// PendingQueue - This contains all of the instructions whose operands have
53 /// been issued, but their results are not ready yet (due to the latency of
54 /// the operation). Once the operands becomes available, the instruction is
55 /// added to the AvailableQueue. This keeps track of each SUnit and the
56 /// number of cycles left to execute before the operation is available.
57 std::vector<std::pair<unsigned, SUnit*> > PendingQueue;
59 /// HazardRec - The hazard recognizer to use.
60 HazardRecognizer *HazardRec;
63 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
64 const TargetMachine &tm,
65 SchedulingPriorityQueue *availqueue,
67 : ScheduleDAG(dag, bb, tm),
68 AvailableQueue(availqueue), HazardRec(HR) {
73 delete AvailableQueue;
79 void ReleaseSucc(SUnit *SuccSU, bool isChain);
80 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
81 void ListScheduleTopDown();
83 } // end anonymous namespace
85 HazardRecognizer::~HazardRecognizer() {}
88 /// Schedule - Schedule the DAG using list scheduling.
89 void ScheduleDAGList::Schedule() {
90 DEBUG(std::cerr << "********** List Scheduling **********\n");
92 // Build scheduling units.
95 AvailableQueue->initNodes(SUnits);
97 ListScheduleTopDown();
99 AvailableQueue->releaseState();
101 DEBUG(std::cerr << "*** Final schedule ***\n");
102 DEBUG(dumpSchedule());
103 DEBUG(std::cerr << "\n");
105 // Emit in scheduled order
109 //===----------------------------------------------------------------------===//
110 // Top-Down Scheduling
111 //===----------------------------------------------------------------------===//
113 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
114 /// the PendingQueue if the count reaches zero.
115 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
117 SuccSU->NumPredsLeft--;
119 SuccSU->NumChainPredsLeft--;
121 assert(SuccSU->NumPredsLeft >= 0 && SuccSU->NumChainPredsLeft >= 0 &&
122 "List scheduling internal error");
124 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
125 // Compute how many cycles it will be before this actually becomes
126 // available. This is the max of the start time of all predecessors plus
128 unsigned AvailableCycle = 0;
129 for (std::set<std::pair<SUnit*, bool> >::iterator I = SuccSU->Preds.begin(),
130 E = SuccSU->Preds.end(); I != E; ++I) {
131 // If this is a token edge, we don't need to wait for the latency of the
132 // preceeding instruction (e.g. a long-latency load) unless there is also
133 // some other data dependence.
134 unsigned PredDoneCycle = I->first->Cycle;
136 PredDoneCycle += I->first->Latency;
137 else if (I->first->Latency)
140 AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
143 PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
147 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
148 /// count of its successors. If a successor pending count is zero, add it to
149 /// the Available queue.
150 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
151 DEBUG(std::cerr << "*** Scheduling [" << CurCycle << "]: ");
152 DEBUG(SU->dump(&DAG));
154 Sequence.push_back(SU);
155 SU->Cycle = CurCycle;
157 // Bottom up: release successors.
158 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
159 E = SU->Succs.end(); I != E; ++I)
160 ReleaseSucc(I->first, I->second);
163 /// ListScheduleTopDown - The main loop of list scheduling for top-down
165 void ScheduleDAGList::ListScheduleTopDown() {
166 unsigned CurCycle = 0;
167 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
169 // All leaves to Available queue.
170 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
171 // It is available if it has no predecessors.
172 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
173 AvailableQueue->push(&SUnits[i]);
174 SUnits[i].isAvailable = SUnits[i].isPending = true;
178 // Emit the entry node first.
179 ScheduleNodeTopDown(Entry, CurCycle);
180 HazardRec->EmitInstruction(Entry->Node);
182 // While Available queue is not empty, grab the node with the highest
183 // priority. If it is not ready put it back. Schedule the node.
184 std::vector<SUnit*> NotReady;
185 while (!AvailableQueue->empty() || !PendingQueue.empty()) {
186 // Check to see if any of the pending instructions are ready to issue. If
187 // so, add them to the available queue.
188 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
189 if (PendingQueue[i].first == CurCycle) {
190 AvailableQueue->push(PendingQueue[i].second);
191 PendingQueue[i].second->isAvailable = true;
192 PendingQueue[i] = PendingQueue.back();
193 PendingQueue.pop_back();
196 assert(PendingQueue[i].first > CurCycle && "Negative latency?");
200 // If there are no instructions available, don't try to issue anything, and
201 // don't advance the hazard recognizer.
202 if (AvailableQueue->empty()) {
207 SUnit *FoundSUnit = 0;
208 SDNode *FoundNode = 0;
210 bool HasNoopHazards = false;
211 while (!AvailableQueue->empty()) {
212 SUnit *CurSUnit = AvailableQueue->pop();
214 // Get the node represented by this SUnit.
215 FoundNode = CurSUnit->Node;
217 // If this is a pseudo op, like copyfromreg, look to see if there is a
218 // real target node flagged to it. If so, use the target node.
219 for (unsigned i = 0, e = CurSUnit->FlaggedNodes.size();
220 FoundNode->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
221 FoundNode = CurSUnit->FlaggedNodes[i];
223 HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
224 if (HT == HazardRecognizer::NoHazard) {
225 FoundSUnit = CurSUnit;
229 // Remember if this is a noop hazard.
230 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
232 NotReady.push_back(CurSUnit);
235 // Add the nodes that aren't ready back onto the available list.
236 if (!NotReady.empty()) {
237 AvailableQueue->push_all(NotReady);
241 // If we found a node to schedule, do it now.
243 ScheduleNodeTopDown(FoundSUnit, CurCycle);
244 HazardRec->EmitInstruction(FoundNode);
245 FoundSUnit->isScheduled = true;
246 AvailableQueue->ScheduledNode(FoundSUnit);
248 // If this is a pseudo-op node, we don't want to increment the current
250 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
252 } else if (!HasNoopHazards) {
253 // Otherwise, we have a pipeline stall, but no other problem, just advance
254 // the current cycle and try again.
255 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
256 HazardRec->AdvanceCycle();
260 // Otherwise, we have no instructions to issue and we have instructions
261 // that will fault if we don't do this right. This is the case for
262 // processors without pipeline interlocks and other cases.
263 DEBUG(std::cerr << "*** Emitting noop\n");
264 HazardRec->EmitNoop();
265 Sequence.push_back(0); // NULL SUnit* -> noop
272 // Verify that all SUnits were scheduled.
273 bool AnyNotSched = false;
274 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
275 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
277 std::cerr << "*** List scheduling failed! ***\n";
278 SUnits[i].dump(&DAG);
279 std::cerr << "has not been scheduled!\n";
283 assert(!AnyNotSched);
287 //===----------------------------------------------------------------------===//
288 // LatencyPriorityQueue Implementation
289 //===----------------------------------------------------------------------===//
291 // This is a SchedulingPriorityQueue that schedules using latency information to
292 // reduce the length of the critical path through the basic block.
295 class LatencyPriorityQueue;
297 /// Sorting functions for the Available queue.
298 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
299 LatencyPriorityQueue *PQ;
300 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
301 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
303 bool operator()(const SUnit* left, const SUnit* right) const;
305 } // end anonymous namespace
308 class LatencyPriorityQueue : public SchedulingPriorityQueue {
309 // SUnits - The SUnits for the current graph.
310 const std::vector<SUnit> *SUnits;
312 // Latencies - The latency (max of latency from this node to the bb exit)
314 std::vector<int> Latencies;
316 /// NumNodesSolelyBlocking - This vector contains, for every node in the
317 /// Queue, the number of nodes that the node is the sole unscheduled
318 /// predecessor for. This is used as a tie-breaker heuristic for better
320 std::vector<unsigned> NumNodesSolelyBlocking;
322 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
324 LatencyPriorityQueue() : Queue(latency_sort(this)) {
327 void initNodes(const std::vector<SUnit> &sunits) {
329 // Calculate node priorities.
330 CalculatePriorities();
332 void releaseState() {
337 unsigned getLatency(unsigned NodeNum) const {
338 assert(NodeNum < Latencies.size());
339 return Latencies[NodeNum];
342 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
343 assert(NodeNum < NumNodesSolelyBlocking.size());
344 return NumNodesSolelyBlocking[NodeNum];
347 bool empty() const { return Queue.empty(); }
349 virtual void push(SUnit *U) {
352 void push_impl(SUnit *U);
354 void push_all(const std::vector<SUnit *> &Nodes) {
355 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
360 if (empty()) return NULL;
361 SUnit *V = Queue.top();
366 // ScheduledNode - As nodes are scheduled, we look to see if there are any
367 // successor nodes that have a single unscheduled predecessor. If so, that
368 // single predecessor has a higher priority, since scheduling it will make
369 // the node available.
370 void ScheduledNode(SUnit *Node);
373 void CalculatePriorities();
374 int CalcLatency(const SUnit &SU);
375 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
377 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
378 /// node from a priority queue. We should roll our own heap to make this
379 /// better or something.
380 void RemoveFromPriorityQueue(SUnit *SU) {
381 std::vector<SUnit*> Temp;
383 assert(!Queue.empty() && "Not in queue!");
384 while (Queue.top() != SU) {
385 Temp.push_back(Queue.top());
387 assert(!Queue.empty() && "Not in queue!");
390 // Remove the node from the PQ.
393 // Add all the other nodes back.
394 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
400 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
401 unsigned LHSNum = LHS->NodeNum;
402 unsigned RHSNum = RHS->NodeNum;
404 // The most important heuristic is scheduling the critical path.
405 unsigned LHSLatency = PQ->getLatency(LHSNum);
406 unsigned RHSLatency = PQ->getLatency(RHSNum);
407 if (LHSLatency < RHSLatency) return true;
408 if (LHSLatency > RHSLatency) return false;
410 // After that, if two nodes have identical latencies, look to see if one will
411 // unblock more other nodes than the other.
412 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
413 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
414 if (LHSBlocked < RHSBlocked) return true;
415 if (LHSBlocked > RHSBlocked) return false;
417 // Finally, just to provide a stable ordering, use the node number as a
419 return LHSNum < RHSNum;
423 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
425 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
426 int &Latency = Latencies[SU.NodeNum];
430 int MaxSuccLatency = 0;
431 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU.Succs.begin(),
432 E = SU.Succs.end(); I != E; ++I)
433 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
435 return Latency = MaxSuccLatency + SU.Latency;
438 /// CalculatePriorities - Calculate priorities of all scheduling units.
439 void LatencyPriorityQueue::CalculatePriorities() {
440 Latencies.assign(SUnits->size(), -1);
441 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
443 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
444 CalcLatency((*SUnits)[i]);
447 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
448 /// of SU, return it, otherwise return null.
449 static SUnit *getSingleUnscheduledPred(SUnit *SU) {
450 SUnit *OnlyAvailablePred = 0;
451 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Preds.begin(),
452 E = SU->Preds.end(); I != E; ++I)
453 if (!I->first->isScheduled) {
454 // We found an available, but not scheduled, predecessor. If it's the
455 // only one we have found, keep track of it... otherwise give up.
456 if (OnlyAvailablePred && OnlyAvailablePred != I->first)
458 OnlyAvailablePred = I->first;
461 return OnlyAvailablePred;
464 void LatencyPriorityQueue::push_impl(SUnit *SU) {
465 // Look at all of the successors of this node. Count the number of nodes that
466 // this node is the sole unscheduled node for.
467 unsigned NumNodesBlocking = 0;
468 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
469 E = SU->Succs.end(); I != E; ++I)
470 if (getSingleUnscheduledPred(I->first) == SU)
472 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
478 // ScheduledNode - As nodes are scheduled, we look to see if there are any
479 // successor nodes that have a single unscheduled predecessor. If so, that
480 // single predecessor has a higher priority, since scheduling it will make
481 // the node available.
482 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
483 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
484 E = SU->Succs.end(); I != E; ++I)
485 AdjustPriorityOfUnscheduledPreds(I->first);
488 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
489 /// scheduled. If SU is not itself available, then there is at least one
490 /// predecessor node that has not been scheduled yet. If SU has exactly ONE
491 /// unscheduled predecessor, we want to increase its priority: it getting
492 /// scheduled will make this node available, so it is better than some other
493 /// node of the same priority that will not make a node available.
494 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
495 if (SU->isPending) return; // All preds scheduled.
497 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
498 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
500 // Okay, we found a single predecessor that is available, but not scheduled.
501 // Since it is available, it must be in the priority queue. First remove it.
502 RemoveFromPriorityQueue(OnlyAvailablePred);
504 // Reinsert the node into the priority queue, which recomputes its
505 // NumNodesSolelyBlocking value.
506 push(OnlyAvailablePred);
510 //===----------------------------------------------------------------------===//
511 // Public Constructor Functions
512 //===----------------------------------------------------------------------===//
514 /// createTDListDAGScheduler - This creates a top-down list scheduler with the
515 /// specified hazard recognizer.
516 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
517 MachineBasicBlock *BB,
518 HazardRecognizer *HR) {
519 return new ScheduleDAGList(DAG, BB, DAG.getTarget(),
520 new LatencyPriorityQueue(),