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/SchedulerRegistry.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/MRegisterInfo.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/ADT/Statistic.h"
39 static Statistic<> NumNoops ("scheduler", "Number of noops inserted");
40 static Statistic<> NumStalls("scheduler", "Number of pipeline stalls");
43 static RegisterScheduler
44 tdListDAGScheduler("list-td", " Top-down list scheduler",
45 createTDListDAGScheduler);
48 //===----------------------------------------------------------------------===//
49 /// ScheduleDAGList - The actual list scheduler implementation. This supports
50 /// top-down scheduling.
52 class VISIBILITY_HIDDEN ScheduleDAGList : public ScheduleDAG {
54 /// AvailableQueue - The priority queue to use for the available SUnits.
56 SchedulingPriorityQueue *AvailableQueue;
58 /// PendingQueue - This contains all of the instructions whose operands have
59 /// been issued, but their results are not ready yet (due to the latency of
60 /// the operation). Once the operands becomes available, the instruction is
61 /// added to the AvailableQueue. This keeps track of each SUnit and the
62 /// number of cycles left to execute before the operation is available.
63 std::vector<std::pair<unsigned, SUnit*> > PendingQueue;
65 /// HazardRec - The hazard recognizer to use.
66 HazardRecognizer *HazardRec;
69 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
70 const TargetMachine &tm,
71 SchedulingPriorityQueue *availqueue,
73 : ScheduleDAG(dag, bb, tm),
74 AvailableQueue(availqueue), HazardRec(HR) {
79 delete AvailableQueue;
85 void ReleaseSucc(SUnit *SuccSU, bool isChain);
86 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
87 void ListScheduleTopDown();
89 } // end anonymous namespace
91 HazardRecognizer::~HazardRecognizer() {}
94 /// Schedule - Schedule the DAG using list scheduling.
95 void ScheduleDAGList::Schedule() {
96 DEBUG(std::cerr << "********** List Scheduling **********\n");
98 // Build scheduling units.
101 AvailableQueue->initNodes(SUnitMap, SUnits);
103 ListScheduleTopDown();
105 AvailableQueue->releaseState();
107 DEBUG(std::cerr << "*** Final schedule ***\n");
108 DEBUG(dumpSchedule());
109 DEBUG(std::cerr << "\n");
111 // Emit in scheduled order
115 //===----------------------------------------------------------------------===//
116 // Top-Down Scheduling
117 //===----------------------------------------------------------------------===//
119 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
120 /// the PendingQueue if the count reaches zero.
121 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
123 SuccSU->NumPredsLeft--;
125 SuccSU->NumChainPredsLeft--;
127 assert(SuccSU->NumPredsLeft >= 0 && SuccSU->NumChainPredsLeft >= 0 &&
128 "List scheduling internal error");
130 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
131 // Compute how many cycles it will be before this actually becomes
132 // available. This is the max of the start time of all predecessors plus
134 unsigned AvailableCycle = 0;
135 for (SUnit::pred_iterator I = SuccSU->Preds.begin(),
136 E = SuccSU->Preds.end(); I != E; ++I) {
137 // If this is a token edge, we don't need to wait for the latency of the
138 // preceeding instruction (e.g. a long-latency load) unless there is also
139 // some other data dependence.
140 SUnit &Pred = *I->first;
141 unsigned PredDoneCycle = Pred.Cycle;
143 PredDoneCycle += Pred.Latency;
144 else if (Pred.Latency)
147 AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
150 PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
154 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
155 /// count of its successors. If a successor pending count is zero, add it to
156 /// the Available queue.
157 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
158 DEBUG(std::cerr << "*** Scheduling [" << CurCycle << "]: ");
159 DEBUG(SU->dump(&DAG));
161 Sequence.push_back(SU);
162 SU->Cycle = CurCycle;
164 // Bottom up: release successors.
165 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
167 ReleaseSucc(I->first, I->second);
170 /// ListScheduleTopDown - The main loop of list scheduling for top-down
172 void ScheduleDAGList::ListScheduleTopDown() {
173 unsigned CurCycle = 0;
174 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
176 // All leaves to Available queue.
177 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
178 // It is available if it has no predecessors.
179 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
180 AvailableQueue->push(&SUnits[i]);
181 SUnits[i].isAvailable = SUnits[i].isPending = true;
185 // Emit the entry node first.
186 ScheduleNodeTopDown(Entry, CurCycle);
187 HazardRec->EmitInstruction(Entry->Node);
189 // While Available queue is not empty, grab the node with the highest
190 // priority. If it is not ready put it back. Schedule the node.
191 std::vector<SUnit*> NotReady;
192 while (!AvailableQueue->empty() || !PendingQueue.empty()) {
193 // Check to see if any of the pending instructions are ready to issue. If
194 // so, add them to the available queue.
195 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
196 if (PendingQueue[i].first == CurCycle) {
197 AvailableQueue->push(PendingQueue[i].second);
198 PendingQueue[i].second->isAvailable = true;
199 PendingQueue[i] = PendingQueue.back();
200 PendingQueue.pop_back();
203 assert(PendingQueue[i].first > CurCycle && "Negative latency?");
207 // If there are no instructions available, don't try to issue anything, and
208 // don't advance the hazard recognizer.
209 if (AvailableQueue->empty()) {
214 SUnit *FoundSUnit = 0;
215 SDNode *FoundNode = 0;
217 bool HasNoopHazards = false;
218 while (!AvailableQueue->empty()) {
219 SUnit *CurSUnit = AvailableQueue->pop();
221 // Get the node represented by this SUnit.
222 FoundNode = CurSUnit->Node;
224 // If this is a pseudo op, like copyfromreg, look to see if there is a
225 // real target node flagged to it. If so, use the target node.
226 for (unsigned i = 0, e = CurSUnit->FlaggedNodes.size();
227 FoundNode->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
228 FoundNode = CurSUnit->FlaggedNodes[i];
230 HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
231 if (HT == HazardRecognizer::NoHazard) {
232 FoundSUnit = CurSUnit;
236 // Remember if this is a noop hazard.
237 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
239 NotReady.push_back(CurSUnit);
242 // Add the nodes that aren't ready back onto the available list.
243 if (!NotReady.empty()) {
244 AvailableQueue->push_all(NotReady);
248 // If we found a node to schedule, do it now.
250 ScheduleNodeTopDown(FoundSUnit, CurCycle);
251 HazardRec->EmitInstruction(FoundNode);
252 FoundSUnit->isScheduled = true;
253 AvailableQueue->ScheduledNode(FoundSUnit);
255 // If this is a pseudo-op node, we don't want to increment the current
257 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
259 } else if (!HasNoopHazards) {
260 // Otherwise, we have a pipeline stall, but no other problem, just advance
261 // the current cycle and try again.
262 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
263 HazardRec->AdvanceCycle();
267 // Otherwise, we have no instructions to issue and we have instructions
268 // that will fault if we don't do this right. This is the case for
269 // processors without pipeline interlocks and other cases.
270 DEBUG(std::cerr << "*** Emitting noop\n");
271 HazardRec->EmitNoop();
272 Sequence.push_back(0); // NULL SUnit* -> noop
279 // Verify that all SUnits were scheduled.
280 bool AnyNotSched = false;
281 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
282 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
284 std::cerr << "*** List scheduling failed! ***\n";
285 SUnits[i].dump(&DAG);
286 std::cerr << "has not been scheduled!\n";
290 assert(!AnyNotSched);
294 //===----------------------------------------------------------------------===//
295 // LatencyPriorityQueue Implementation
296 //===----------------------------------------------------------------------===//
298 // This is a SchedulingPriorityQueue that schedules using latency information to
299 // reduce the length of the critical path through the basic block.
302 class LatencyPriorityQueue;
304 /// Sorting functions for the Available queue.
305 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
306 LatencyPriorityQueue *PQ;
307 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
308 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
310 bool operator()(const SUnit* left, const SUnit* right) const;
312 } // end anonymous namespace
315 class LatencyPriorityQueue : public SchedulingPriorityQueue {
316 // SUnits - The SUnits for the current graph.
317 std::vector<SUnit> *SUnits;
319 // Latencies - The latency (max of latency from this node to the bb exit)
321 std::vector<int> Latencies;
323 /// NumNodesSolelyBlocking - This vector contains, for every node in the
324 /// Queue, the number of nodes that the node is the sole unscheduled
325 /// predecessor for. This is used as a tie-breaker heuristic for better
327 std::vector<unsigned> NumNodesSolelyBlocking;
329 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
331 LatencyPriorityQueue() : Queue(latency_sort(this)) {
334 void initNodes(std::map<SDNode*, SUnit*> &sumap,
335 std::vector<SUnit> &sunits) {
337 // Calculate node priorities.
338 CalculatePriorities();
340 void releaseState() {
345 unsigned getLatency(unsigned NodeNum) const {
346 assert(NodeNum < Latencies.size());
347 return Latencies[NodeNum];
350 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
351 assert(NodeNum < NumNodesSolelyBlocking.size());
352 return NumNodesSolelyBlocking[NodeNum];
355 bool empty() const { return Queue.empty(); }
357 virtual void push(SUnit *U) {
360 void push_impl(SUnit *U);
362 void push_all(const std::vector<SUnit *> &Nodes) {
363 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
368 if (empty()) return NULL;
369 SUnit *V = Queue.top();
374 // ScheduledNode - As nodes are scheduled, we look to see if there are any
375 // successor nodes that have a single unscheduled predecessor. If so, that
376 // single predecessor has a higher priority, since scheduling it will make
377 // the node available.
378 void ScheduledNode(SUnit *Node);
381 void CalculatePriorities();
382 int CalcLatency(const SUnit &SU);
383 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
384 SUnit *getSingleUnscheduledPred(SUnit *SU);
386 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
387 /// node from a priority queue. We should roll our own heap to make this
388 /// better or something.
389 void RemoveFromPriorityQueue(SUnit *SU) {
390 std::vector<SUnit*> Temp;
392 assert(!Queue.empty() && "Not in queue!");
393 while (Queue.top() != SU) {
394 Temp.push_back(Queue.top());
396 assert(!Queue.empty() && "Not in queue!");
399 // Remove the node from the PQ.
402 // Add all the other nodes back.
403 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
409 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
410 unsigned LHSNum = LHS->NodeNum;
411 unsigned RHSNum = RHS->NodeNum;
413 // The most important heuristic is scheduling the critical path.
414 unsigned LHSLatency = PQ->getLatency(LHSNum);
415 unsigned RHSLatency = PQ->getLatency(RHSNum);
416 if (LHSLatency < RHSLatency) return true;
417 if (LHSLatency > RHSLatency) return false;
419 // After that, if two nodes have identical latencies, look to see if one will
420 // unblock more other nodes than the other.
421 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
422 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
423 if (LHSBlocked < RHSBlocked) return true;
424 if (LHSBlocked > RHSBlocked) return false;
426 // Finally, just to provide a stable ordering, use the node number as a
428 return LHSNum < RHSNum;
432 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
434 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
435 int &Latency = Latencies[SU.NodeNum];
439 int MaxSuccLatency = 0;
440 for (SUnit::const_succ_iterator I = SU.Succs.begin(), E = SU.Succs.end();
442 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
444 return Latency = MaxSuccLatency + SU.Latency;
447 /// CalculatePriorities - Calculate priorities of all scheduling units.
448 void LatencyPriorityQueue::CalculatePriorities() {
449 Latencies.assign(SUnits->size(), -1);
450 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
452 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
453 CalcLatency((*SUnits)[i]);
456 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
457 /// of SU, return it, otherwise return null.
458 SUnit *LatencyPriorityQueue::getSingleUnscheduledPred(SUnit *SU) {
459 SUnit *OnlyAvailablePred = 0;
460 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
462 SUnit &Pred = *I->first;
463 if (!Pred.isScheduled) {
464 // We found an available, but not scheduled, predecessor. If it's the
465 // only one we have found, keep track of it... otherwise give up.
466 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
468 OnlyAvailablePred = &Pred;
472 return OnlyAvailablePred;
475 void LatencyPriorityQueue::push_impl(SUnit *SU) {
476 // Look at all of the successors of this node. Count the number of nodes that
477 // this node is the sole unscheduled node for.
478 unsigned NumNodesBlocking = 0;
479 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
481 if (getSingleUnscheduledPred(I->first) == SU)
483 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
489 // ScheduledNode - As nodes are scheduled, we look to see if there are any
490 // successor nodes that have a single unscheduled predecessor. If so, that
491 // single predecessor has a higher priority, since scheduling it will make
492 // the node available.
493 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
494 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
496 AdjustPriorityOfUnscheduledPreds(I->first);
499 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
500 /// scheduled. If SU is not itself available, then there is at least one
501 /// predecessor node that has not been scheduled yet. If SU has exactly ONE
502 /// unscheduled predecessor, we want to increase its priority: it getting
503 /// scheduled will make this node available, so it is better than some other
504 /// node of the same priority that will not make a node available.
505 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
506 if (SU->isPending) return; // All preds scheduled.
508 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
509 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
511 // Okay, we found a single predecessor that is available, but not scheduled.
512 // Since it is available, it must be in the priority queue. First remove it.
513 RemoveFromPriorityQueue(OnlyAvailablePred);
515 // Reinsert the node into the priority queue, which recomputes its
516 // NumNodesSolelyBlocking value.
517 push(OnlyAvailablePred);
521 //===----------------------------------------------------------------------===//
522 // Public Constructor Functions
523 //===----------------------------------------------------------------------===//
525 /// createTDListDAGScheduler - This creates a top-down list scheduler with a
526 /// new hazard recognizer. This scheduler takes ownership of the hazard
527 /// recognizer and deletes it when done.
528 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAGISel *IS,
530 MachineBasicBlock *BB) {
531 return new ScheduleDAGList(*DAG, BB, DAG->getTarget(),
532 new LatencyPriorityQueue(),
533 IS->CreateTargetHazardRecognizer());