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"
38 static Statistic NumNoops ("scheduler", "Number of noops inserted");
39 static Statistic NumStalls("scheduler", "Number of pipeline stalls");
42 static RegisterScheduler
43 tdListDAGScheduler("list-td", " Top-down list scheduler",
44 createTDListDAGScheduler);
47 //===----------------------------------------------------------------------===//
48 /// ScheduleDAGList - The actual list scheduler implementation. This supports
49 /// top-down scheduling.
51 class VISIBILITY_HIDDEN ScheduleDAGList : public ScheduleDAG {
53 /// AvailableQueue - The priority queue to use for the available SUnits.
55 SchedulingPriorityQueue *AvailableQueue;
57 /// PendingQueue - This contains all of the instructions whose operands have
58 /// been issued, but their results are not ready yet (due to the latency of
59 /// the operation). Once the operands becomes available, the instruction is
60 /// added to the AvailableQueue. This keeps track of each SUnit and the
61 /// number of cycles left to execute before the operation is available.
62 std::vector<std::pair<unsigned, SUnit*> > PendingQueue;
64 /// HazardRec - The hazard recognizer to use.
65 HazardRecognizer *HazardRec;
68 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
69 const TargetMachine &tm,
70 SchedulingPriorityQueue *availqueue,
72 : ScheduleDAG(dag, bb, tm),
73 AvailableQueue(availqueue), HazardRec(HR) {
78 delete AvailableQueue;
84 void ReleaseSucc(SUnit *SuccSU, bool isChain);
85 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
86 void ListScheduleTopDown();
88 } // end anonymous namespace
90 HazardRecognizer::~HazardRecognizer() {}
93 /// Schedule - Schedule the DAG using list scheduling.
94 void ScheduleDAGList::Schedule() {
95 DOUT << "********** List Scheduling **********\n";
97 // Build scheduling units.
100 AvailableQueue->initNodes(SUnitMap, SUnits);
102 ListScheduleTopDown();
104 AvailableQueue->releaseState();
106 DOUT << "*** Final schedule ***\n";
107 DEBUG(dumpSchedule());
110 // Emit in scheduled order
114 //===----------------------------------------------------------------------===//
115 // Top-Down Scheduling
116 //===----------------------------------------------------------------------===//
118 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
119 /// the PendingQueue if the count reaches zero.
120 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
122 SuccSU->NumPredsLeft--;
124 SuccSU->NumChainPredsLeft--;
126 assert(SuccSU->NumPredsLeft >= 0 && SuccSU->NumChainPredsLeft >= 0 &&
127 "List scheduling internal error");
129 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
130 // Compute how many cycles it will be before this actually becomes
131 // available. This is the max of the start time of all predecessors plus
133 unsigned AvailableCycle = 0;
134 for (SUnit::pred_iterator I = SuccSU->Preds.begin(),
135 E = SuccSU->Preds.end(); I != E; ++I) {
136 // If this is a token edge, we don't need to wait for the latency of the
137 // preceeding instruction (e.g. a long-latency load) unless there is also
138 // some other data dependence.
139 SUnit &Pred = *I->first;
140 unsigned PredDoneCycle = Pred.Cycle;
142 PredDoneCycle += Pred.Latency;
143 else if (Pred.Latency)
146 AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
149 PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
153 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
154 /// count of its successors. If a successor pending count is zero, add it to
155 /// the Available queue.
156 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
157 DOUT << "*** Scheduling [" << CurCycle << "]: ";
158 DEBUG(SU->dump(&DAG));
160 Sequence.push_back(SU);
161 SU->Cycle = CurCycle;
163 // Bottom up: release successors.
164 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
166 ReleaseSucc(I->first, I->second);
169 /// ListScheduleTopDown - The main loop of list scheduling for top-down
171 void ScheduleDAGList::ListScheduleTopDown() {
172 unsigned CurCycle = 0;
173 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
175 // All leaves to Available queue.
176 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
177 // It is available if it has no predecessors.
178 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
179 AvailableQueue->push(&SUnits[i]);
180 SUnits[i].isAvailable = SUnits[i].isPending = true;
184 // Emit the entry node first.
185 ScheduleNodeTopDown(Entry, CurCycle);
186 HazardRec->EmitInstruction(Entry->Node);
188 // While Available queue is not empty, grab the node with the highest
189 // priority. If it is not ready put it back. Schedule the node.
190 std::vector<SUnit*> NotReady;
191 while (!AvailableQueue->empty() || !PendingQueue.empty()) {
192 // Check to see if any of the pending instructions are ready to issue. If
193 // so, add them to the available queue.
194 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
195 if (PendingQueue[i].first == CurCycle) {
196 AvailableQueue->push(PendingQueue[i].second);
197 PendingQueue[i].second->isAvailable = true;
198 PendingQueue[i] = PendingQueue.back();
199 PendingQueue.pop_back();
202 assert(PendingQueue[i].first > CurCycle && "Negative latency?");
206 // If there are no instructions available, don't try to issue anything, and
207 // don't advance the hazard recognizer.
208 if (AvailableQueue->empty()) {
213 SUnit *FoundSUnit = 0;
214 SDNode *FoundNode = 0;
216 bool HasNoopHazards = false;
217 while (!AvailableQueue->empty()) {
218 SUnit *CurSUnit = AvailableQueue->pop();
220 // Get the node represented by this SUnit.
221 FoundNode = CurSUnit->Node;
223 // If this is a pseudo op, like copyfromreg, look to see if there is a
224 // real target node flagged to it. If so, use the target node.
225 for (unsigned i = 0, e = CurSUnit->FlaggedNodes.size();
226 FoundNode->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
227 FoundNode = CurSUnit->FlaggedNodes[i];
229 HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
230 if (HT == HazardRecognizer::NoHazard) {
231 FoundSUnit = CurSUnit;
235 // Remember if this is a noop hazard.
236 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
238 NotReady.push_back(CurSUnit);
241 // Add the nodes that aren't ready back onto the available list.
242 if (!NotReady.empty()) {
243 AvailableQueue->push_all(NotReady);
247 // If we found a node to schedule, do it now.
249 ScheduleNodeTopDown(FoundSUnit, CurCycle);
250 HazardRec->EmitInstruction(FoundNode);
251 FoundSUnit->isScheduled = true;
252 AvailableQueue->ScheduledNode(FoundSUnit);
254 // If this is a pseudo-op node, we don't want to increment the current
256 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
258 } else if (!HasNoopHazards) {
259 // Otherwise, we have a pipeline stall, but no other problem, just advance
260 // the current cycle and try again.
261 DOUT << "*** Advancing cycle, no work to do\n";
262 HazardRec->AdvanceCycle();
266 // Otherwise, we have no instructions to issue and we have instructions
267 // that will fault if we don't do this right. This is the case for
268 // processors without pipeline interlocks and other cases.
269 DOUT << "*** Emitting noop\n";
270 HazardRec->EmitNoop();
271 Sequence.push_back(0); // NULL SUnit* -> noop
278 // Verify that all SUnits were scheduled.
279 bool AnyNotSched = false;
280 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
281 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
283 cerr << "*** List scheduling failed! ***\n";
284 SUnits[i].dump(&DAG);
285 cerr << "has not been scheduled!\n";
289 assert(!AnyNotSched);
293 //===----------------------------------------------------------------------===//
294 // LatencyPriorityQueue Implementation
295 //===----------------------------------------------------------------------===//
297 // This is a SchedulingPriorityQueue that schedules using latency information to
298 // reduce the length of the critical path through the basic block.
301 class LatencyPriorityQueue;
303 /// Sorting functions for the Available queue.
304 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
305 LatencyPriorityQueue *PQ;
306 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
307 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
309 bool operator()(const SUnit* left, const SUnit* right) const;
311 } // end anonymous namespace
314 class LatencyPriorityQueue : public SchedulingPriorityQueue {
315 // SUnits - The SUnits for the current graph.
316 std::vector<SUnit> *SUnits;
318 // Latencies - The latency (max of latency from this node to the bb exit)
320 std::vector<int> Latencies;
322 /// NumNodesSolelyBlocking - This vector contains, for every node in the
323 /// Queue, the number of nodes that the node is the sole unscheduled
324 /// predecessor for. This is used as a tie-breaker heuristic for better
326 std::vector<unsigned> NumNodesSolelyBlocking;
328 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
330 LatencyPriorityQueue() : Queue(latency_sort(this)) {
333 void initNodes(std::map<SDNode*, SUnit*> &sumap,
334 std::vector<SUnit> &sunits) {
336 // Calculate node priorities.
337 CalculatePriorities();
339 void releaseState() {
344 unsigned getLatency(unsigned NodeNum) const {
345 assert(NodeNum < Latencies.size());
346 return Latencies[NodeNum];
349 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
350 assert(NodeNum < NumNodesSolelyBlocking.size());
351 return NumNodesSolelyBlocking[NodeNum];
354 bool empty() const { return Queue.empty(); }
356 virtual void push(SUnit *U) {
359 void push_impl(SUnit *U);
361 void push_all(const std::vector<SUnit *> &Nodes) {
362 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
367 if (empty()) return NULL;
368 SUnit *V = Queue.top();
373 // ScheduledNode - As nodes are scheduled, we look to see if there are any
374 // successor nodes that have a single unscheduled predecessor. If so, that
375 // single predecessor has a higher priority, since scheduling it will make
376 // the node available.
377 void ScheduledNode(SUnit *Node);
380 void CalculatePriorities();
381 int CalcLatency(const SUnit &SU);
382 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
383 SUnit *getSingleUnscheduledPred(SUnit *SU);
385 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
386 /// node from a priority queue. We should roll our own heap to make this
387 /// better or something.
388 void RemoveFromPriorityQueue(SUnit *SU) {
389 std::vector<SUnit*> Temp;
391 assert(!Queue.empty() && "Not in queue!");
392 while (Queue.top() != SU) {
393 Temp.push_back(Queue.top());
395 assert(!Queue.empty() && "Not in queue!");
398 // Remove the node from the PQ.
401 // Add all the other nodes back.
402 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
408 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
409 unsigned LHSNum = LHS->NodeNum;
410 unsigned RHSNum = RHS->NodeNum;
412 // The most important heuristic is scheduling the critical path.
413 unsigned LHSLatency = PQ->getLatency(LHSNum);
414 unsigned RHSLatency = PQ->getLatency(RHSNum);
415 if (LHSLatency < RHSLatency) return true;
416 if (LHSLatency > RHSLatency) return false;
418 // After that, if two nodes have identical latencies, look to see if one will
419 // unblock more other nodes than the other.
420 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
421 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
422 if (LHSBlocked < RHSBlocked) return true;
423 if (LHSBlocked > RHSBlocked) return false;
425 // Finally, just to provide a stable ordering, use the node number as a
427 return LHSNum < RHSNum;
431 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
433 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
434 int &Latency = Latencies[SU.NodeNum];
438 int MaxSuccLatency = 0;
439 for (SUnit::const_succ_iterator I = SU.Succs.begin(), E = SU.Succs.end();
441 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
443 return Latency = MaxSuccLatency + SU.Latency;
446 /// CalculatePriorities - Calculate priorities of all scheduling units.
447 void LatencyPriorityQueue::CalculatePriorities() {
448 Latencies.assign(SUnits->size(), -1);
449 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
451 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
452 CalcLatency((*SUnits)[i]);
455 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
456 /// of SU, return it, otherwise return null.
457 SUnit *LatencyPriorityQueue::getSingleUnscheduledPred(SUnit *SU) {
458 SUnit *OnlyAvailablePred = 0;
459 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
461 SUnit &Pred = *I->first;
462 if (!Pred.isScheduled) {
463 // We found an available, but not scheduled, predecessor. If it's the
464 // only one we have found, keep track of it... otherwise give up.
465 if (OnlyAvailablePred && OnlyAvailablePred != &Pred)
467 OnlyAvailablePred = &Pred;
471 return OnlyAvailablePred;
474 void LatencyPriorityQueue::push_impl(SUnit *SU) {
475 // Look at all of the successors of this node. Count the number of nodes that
476 // this node is the sole unscheduled node for.
477 unsigned NumNodesBlocking = 0;
478 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
480 if (getSingleUnscheduledPred(I->first) == SU)
482 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
488 // ScheduledNode - As nodes are scheduled, we look to see if there are any
489 // successor nodes that have a single unscheduled predecessor. If so, that
490 // single predecessor has a higher priority, since scheduling it will make
491 // the node available.
492 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
493 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
495 AdjustPriorityOfUnscheduledPreds(I->first);
498 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
499 /// scheduled. If SU is not itself available, then there is at least one
500 /// predecessor node that has not been scheduled yet. If SU has exactly ONE
501 /// unscheduled predecessor, we want to increase its priority: it getting
502 /// scheduled will make this node available, so it is better than some other
503 /// node of the same priority that will not make a node available.
504 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
505 if (SU->isPending) return; // All preds scheduled.
507 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
508 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
510 // Okay, we found a single predecessor that is available, but not scheduled.
511 // Since it is available, it must be in the priority queue. First remove it.
512 RemoveFromPriorityQueue(OnlyAvailablePred);
514 // Reinsert the node into the priority queue, which recomputes its
515 // NumNodesSolelyBlocking value.
516 push(OnlyAvailablePred);
520 //===----------------------------------------------------------------------===//
521 // Public Constructor Functions
522 //===----------------------------------------------------------------------===//
524 /// createTDListDAGScheduler - This creates a top-down list scheduler with a
525 /// new hazard recognizer. This scheduler takes ownership of the hazard
526 /// recognizer and deletes it when done.
527 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAGISel *IS,
529 MachineBasicBlock *BB) {
530 return new ScheduleDAGList(*DAG, BB, DAG->getTarget(),
531 new LatencyPriorityQueue(),
532 IS->CreateTargetHazardRecognizer());