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 bottom-up and top-down list schedulers, using standard
11 // algorithms. The basic approach uses a priority queue of available nodes to
12 // schedule. One at a time, nodes are taken from the priority queue (thus in
13 // priority 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/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CommandLine.h"
36 Statistic<> NumNoops ("scheduler", "Number of noops inserted");
37 Statistic<> NumStalls("scheduler", "Number of pipeline stalls");
39 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
40 /// a group of nodes flagged together.
42 SDNode *Node; // Representative node.
43 std::vector<SDNode*> FlaggedNodes; // All nodes flagged to Node.
45 // Preds/Succs - The SUnits before/after us in the graph. The boolean value
46 // is true if the edge is a token chain edge, false if it is a value edge.
47 std::set<std::pair<SUnit*,bool> > Preds; // All sunit predecessors.
48 std::set<std::pair<SUnit*,bool> > Succs; // All sunit successors.
50 short NumPredsLeft; // # of preds not scheduled.
51 short NumSuccsLeft; // # of succs not scheduled.
52 short NumChainPredsLeft; // # of chain preds not scheduled.
53 short NumChainSuccsLeft; // # of chain succs not scheduled.
54 bool isTwoAddress : 1; // Is a two-address instruction.
55 bool isDefNUseOperand : 1; // Is a def&use operand.
56 bool isPending : 1; // True once pending.
57 bool isAvailable : 1; // True once available.
58 bool isScheduled : 1; // True once scheduled.
59 unsigned short Latency; // Node latency.
60 unsigned CycleBound; // Upper/lower cycle to be scheduled at.
61 unsigned Cycle; // Once scheduled, the cycle of the op.
62 unsigned NodeNum; // Entry # of node in the node vector.
64 SUnit(SDNode *node, unsigned nodenum)
65 : Node(node), NumPredsLeft(0), NumSuccsLeft(0),
66 NumChainPredsLeft(0), NumChainSuccsLeft(0),
67 isTwoAddress(false), isDefNUseOperand(false),
68 isPending(false), isAvailable(false), isScheduled(false),
69 Latency(0), CycleBound(0), Cycle(0), NodeNum(nodenum) {}
71 void dump(const SelectionDAG *G) const;
72 void dumpAll(const SelectionDAG *G) const;
76 void SUnit::dump(const SelectionDAG *G) const {
80 if (FlaggedNodes.size() != 0) {
81 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
83 FlaggedNodes[i]->dump(G);
89 void SUnit::dumpAll(const SelectionDAG *G) const {
92 std::cerr << " # preds left : " << NumPredsLeft << "\n";
93 std::cerr << " # succs left : " << NumSuccsLeft << "\n";
94 std::cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
95 std::cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
96 std::cerr << " Latency : " << Latency << "\n";
98 if (Preds.size() != 0) {
99 std::cerr << " Predecessors:\n";
100 for (std::set<std::pair<SUnit*,bool> >::const_iterator I = Preds.begin(),
101 E = Preds.end(); I != E; ++I) {
105 std::cerr << " val ";
109 if (Succs.size() != 0) {
110 std::cerr << " Successors:\n";
111 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = Succs.begin(),
112 E = Succs.end(); I != E; ++I) {
116 std::cerr << " val ";
123 //===----------------------------------------------------------------------===//
124 /// SchedulingPriorityQueue - This interface is used to plug different
125 /// priorities computation algorithms into the list scheduler. It implements the
126 /// interface of a standard priority queue, where nodes are inserted in
127 /// arbitrary order and returned in priority order. The computation of the
128 /// priority and the representation of the queue are totally up to the
129 /// implementation to decide.
132 class SchedulingPriorityQueue {
134 virtual ~SchedulingPriorityQueue() {}
136 virtual void initNodes(const std::vector<SUnit> &SUnits) = 0;
137 virtual void releaseState() = 0;
139 virtual bool empty() const = 0;
140 virtual void push(SUnit *U) = 0;
142 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
143 virtual SUnit *pop() = 0;
145 /// ScheduledNode - As each node is scheduled, this method is invoked. This
146 /// allows the priority function to adjust the priority of node that have
147 /// already been emitted.
148 virtual void ScheduledNode(SUnit *Node) {}
155 //===----------------------------------------------------------------------===//
156 /// ScheduleDAGList - The actual list scheduler implementation. This supports
157 /// both top-down and bottom-up scheduling.
159 class ScheduleDAGList : public ScheduleDAG {
161 // SDNode to SUnit mapping (many to one).
162 std::map<SDNode*, SUnit*> SUnitMap;
163 // The schedule. Null SUnit*'s represent noop instructions.
164 std::vector<SUnit*> Sequence;
166 // The scheduling units.
167 std::vector<SUnit> SUnits;
169 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
173 /// AvailableQueue - The priority queue to use for the available SUnits.
175 SchedulingPriorityQueue *AvailableQueue;
177 /// PendingQueue - This contains all of the instructions whose operands have
178 /// been issued, but their results are not ready yet (due to the latency of
179 /// the operation). Once the operands becomes available, the instruction is
180 /// added to the AvailableQueue. This keeps track of each SUnit and the
181 /// number of cycles left to execute before the operation is available.
182 std::vector<std::pair<unsigned, SUnit*> > PendingQueue;
184 /// HazardRec - The hazard recognizer to use.
185 HazardRecognizer *HazardRec;
188 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
189 const TargetMachine &tm, bool isbottomup,
190 SchedulingPriorityQueue *availqueue,
191 HazardRecognizer *HR)
192 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
193 AvailableQueue(availqueue), HazardRec(HR) {
198 delete AvailableQueue;
203 void dumpSchedule() const;
206 SUnit *NewSUnit(SDNode *N);
207 void ReleasePred(SUnit *PredSU, bool isChain, unsigned CurCycle);
208 void ReleaseSucc(SUnit *SuccSU, bool isChain);
209 void ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle);
210 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
211 void ListScheduleTopDown();
212 void ListScheduleBottomUp();
213 void BuildSchedUnits();
216 } // end anonymous namespace
218 HazardRecognizer::~HazardRecognizer() {}
221 /// NewSUnit - Creates a new SUnit and return a ptr to it.
222 SUnit *ScheduleDAGList::NewSUnit(SDNode *N) {
223 SUnits.push_back(SUnit(N, SUnits.size()));
224 return &SUnits.back();
227 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
228 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
229 /// together nodes with a single SUnit.
230 void ScheduleDAGList::BuildSchedUnits() {
231 // Reserve entries in the vector for each of the SUnits we are creating. This
232 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
234 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
236 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
238 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
239 E = DAG.allnodes_end(); NI != E; ++NI) {
240 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
243 // If this node has already been processed, stop now.
244 if (SUnitMap[NI]) continue;
246 SUnit *NodeSUnit = NewSUnit(NI);
248 // See if anything is flagged to this node, if so, add them to flagged
249 // nodes. Nodes can have at most one flag input and one flag output. Flags
250 // are required the be the last operand and result of a node.
252 // Scan up, adding flagged preds to FlaggedNodes.
254 while (N->getNumOperands() &&
255 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
256 N = N->getOperand(N->getNumOperands()-1).Val;
257 NodeSUnit->FlaggedNodes.push_back(N);
258 SUnitMap[N] = NodeSUnit;
261 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
262 // have a user of the flag operand.
264 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
265 SDOperand FlagVal(N, N->getNumValues()-1);
267 // There are either zero or one users of the Flag result.
268 bool HasFlagUse = false;
269 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
271 if (FlagVal.isOperand(*UI)) {
273 NodeSUnit->FlaggedNodes.push_back(N);
274 SUnitMap[N] = NodeSUnit;
278 if (!HasFlagUse) break;
281 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
284 SUnitMap[N] = NodeSUnit;
286 // Compute the latency for the node. We use the sum of the latencies for
287 // all nodes flagged together into this SUnit.
288 if (InstrItins.isEmpty()) {
289 // No latency information.
290 NodeSUnit->Latency = 1;
292 NodeSUnit->Latency = 0;
293 if (N->isTargetOpcode()) {
294 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
295 InstrStage *S = InstrItins.begin(SchedClass);
296 InstrStage *E = InstrItins.end(SchedClass);
298 NodeSUnit->Latency += S->Cycles;
300 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
301 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
302 if (FNode->isTargetOpcode()) {
303 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
304 InstrStage *S = InstrItins.begin(SchedClass);
305 InstrStage *E = InstrItins.end(SchedClass);
307 NodeSUnit->Latency += S->Cycles;
313 // Pass 2: add the preds, succs, etc.
314 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
315 SUnit *SU = &SUnits[su];
316 SDNode *MainNode = SU->Node;
318 if (MainNode->isTargetOpcode() &&
319 TII->isTwoAddrInstr(MainNode->getTargetOpcode()))
320 SU->isTwoAddress = true;
322 // Find all predecessors and successors of the group.
323 // Temporarily add N to make code simpler.
324 SU->FlaggedNodes.push_back(MainNode);
326 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
327 SDNode *N = SU->FlaggedNodes[n];
329 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
330 SDNode *OpN = N->getOperand(i).Val;
331 if (isPassiveNode(OpN)) continue; // Not scheduled.
332 SUnit *OpSU = SUnitMap[OpN];
333 assert(OpSU && "Node has no SUnit!");
334 if (OpSU == SU) continue; // In the same group.
336 MVT::ValueType OpVT = N->getOperand(i).getValueType();
337 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
338 bool isChain = OpVT == MVT::Other;
340 if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
344 SU->NumChainPredsLeft++;
347 if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
349 OpSU->NumSuccsLeft++;
351 OpSU->NumChainSuccsLeft++;
357 // Remove MainNode from FlaggedNodes again.
358 SU->FlaggedNodes.pop_back();
362 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
363 SUnits[su].dumpAll(&DAG));
366 /// EmitSchedule - Emit the machine code in scheduled order.
367 void ScheduleDAGList::EmitSchedule() {
368 std::map<SDNode*, unsigned> VRBaseMap;
369 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
370 if (SUnit *SU = Sequence[i]) {
371 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
372 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
373 EmitNode(SU->Node, VRBaseMap);
375 // Null SUnit* is a noop.
381 /// dump - dump the schedule.
382 void ScheduleDAGList::dumpSchedule() const {
383 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
384 if (SUnit *SU = Sequence[i])
387 std::cerr << "**** NOOP ****\n";
391 /// Schedule - Schedule the DAG using list scheduling.
392 void ScheduleDAGList::Schedule() {
393 DEBUG(std::cerr << "********** List Scheduling **********\n");
395 // Build scheduling units.
398 AvailableQueue->initNodes(SUnits);
400 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
402 ListScheduleBottomUp();
404 ListScheduleTopDown();
406 AvailableQueue->releaseState();
408 DEBUG(std::cerr << "*** Final schedule ***\n");
409 DEBUG(dumpSchedule());
410 DEBUG(std::cerr << "\n");
412 // Emit in scheduled order
416 //===----------------------------------------------------------------------===//
417 // Bottom-Up Scheduling
418 //===----------------------------------------------------------------------===//
420 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
421 /// the Available queue is the count reaches zero. Also update its cycle bound.
422 void ScheduleDAGList::ReleasePred(SUnit *PredSU, bool isChain,
424 // FIXME: the distance between two nodes is not always == the predecessor's
425 // latency. For example, the reader can very well read the register written
426 // by the predecessor later than the issue cycle. It also depends on the
427 // interrupt model (drain vs. freeze).
428 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
431 PredSU->NumSuccsLeft--;
433 PredSU->NumChainSuccsLeft--;
436 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
437 std::cerr << "*** List scheduling failed! ***\n";
439 std::cerr << " has been released too many times!\n";
444 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
445 // EntryToken has to go last! Special case it here.
446 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
447 PredSU->isAvailable = true;
448 AvailableQueue->push(PredSU);
452 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
453 /// count of its predecessors. If a predecessor pending count is zero, add it to
454 /// the Available queue.
455 void ScheduleDAGList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
456 DEBUG(std::cerr << "*** Scheduling [" << CurCycle << "]: ");
457 DEBUG(SU->dump(&DAG));
458 SU->Cycle = CurCycle;
460 Sequence.push_back(SU);
462 // Bottom up: release predecessors
463 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
464 E = SU->Preds.end(); I != E; ++I) {
465 ReleasePred(I->first, I->second, CurCycle);
466 // FIXME: This is something used by the priority function that it should
467 // calculate directly.
473 /// isReady - True if node's lower cycle bound is less or equal to the current
474 /// scheduling cycle. Always true if all nodes have uniform latency 1.
475 static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
476 return SU->CycleBound <= CurrCycle;
479 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
481 void ScheduleDAGList::ListScheduleBottomUp() {
482 unsigned CurrCycle = 0;
483 // Add root to Available queue.
484 AvailableQueue->push(SUnitMap[DAG.getRoot().Val]);
486 // While Available queue is not empty, grab the node with the highest
487 // priority. If it is not ready put it back. Schedule the node.
488 std::vector<SUnit*> NotReady;
489 while (!AvailableQueue->empty()) {
490 SUnit *CurrNode = AvailableQueue->pop();
492 while (!isReady(CurrNode, CurrCycle)) {
493 NotReady.push_back(CurrNode);
494 CurrNode = AvailableQueue->pop();
497 // Add the nodes that aren't ready back onto the available list.
498 AvailableQueue->push_all(NotReady);
501 ScheduleNodeBottomUp(CurrNode, CurrCycle);
503 CurrNode->isScheduled = true;
504 AvailableQueue->ScheduledNode(CurrNode);
507 // Add entry node last
508 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
509 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
510 Sequence.push_back(Entry);
513 // Reverse the order if it is bottom up.
514 std::reverse(Sequence.begin(), Sequence.end());
518 // Verify that all SUnits were scheduled.
519 bool AnyNotSched = false;
520 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
521 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
523 std::cerr << "*** List scheduling failed! ***\n";
524 SUnits[i].dump(&DAG);
525 std::cerr << "has not been scheduled!\n";
529 assert(!AnyNotSched);
533 //===----------------------------------------------------------------------===//
534 // Top-Down Scheduling
535 //===----------------------------------------------------------------------===//
537 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
538 /// the PendingQueue if the count reaches zero.
539 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
541 SuccSU->NumPredsLeft--;
543 SuccSU->NumChainPredsLeft--;
545 assert(SuccSU->NumPredsLeft >= 0 && SuccSU->NumChainPredsLeft >= 0 &&
546 "List scheduling internal error");
548 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
549 // Compute how many cycles it will be before this actually becomes
550 // available. This is the max of the start time of all predecessors plus
552 unsigned AvailableCycle = 0;
553 for (std::set<std::pair<SUnit*, bool> >::iterator I = SuccSU->Preds.begin(),
554 E = SuccSU->Preds.end(); I != E; ++I) {
555 // If this is a token edge, we don't need to wait for the latency of the
556 // preceeding instruction (e.g. a long-latency load) unless there is also
557 // some other data dependence.
558 unsigned PredDoneCycle = I->first->Cycle;
560 PredDoneCycle += I->first->Latency;
561 else if (I->first->Latency)
564 AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
567 PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
568 SuccSU->isPending = true;
572 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
573 /// count of its successors. If a successor pending count is zero, add it to
574 /// the Available queue.
575 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
576 DEBUG(std::cerr << "*** Scheduling [" << CurCycle << "]: ");
577 DEBUG(SU->dump(&DAG));
579 Sequence.push_back(SU);
580 SU->Cycle = CurCycle;
582 // Bottom up: release successors.
583 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
584 E = SU->Succs.end(); I != E; ++I)
585 ReleaseSucc(I->first, I->second);
588 /// ListScheduleTopDown - The main loop of list scheduling for top-down
590 void ScheduleDAGList::ListScheduleTopDown() {
591 unsigned CurCycle = 0;
592 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
594 // All leaves to Available queue.
595 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
596 // It is available if it has no predecessors.
597 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
598 AvailableQueue->push(&SUnits[i]);
599 SUnits[i].isAvailable = SUnits[i].isPending = true;
603 // Emit the entry node first.
604 ScheduleNodeTopDown(Entry, CurCycle);
605 HazardRec->EmitInstruction(Entry->Node);
607 // While Available queue is not empty, grab the node with the highest
608 // priority. If it is not ready put it back. Schedule the node.
609 std::vector<SUnit*> NotReady;
610 while (!AvailableQueue->empty() || !PendingQueue.empty()) {
611 // Check to see if any of the pending instructions are ready to issue. If
612 // so, add them to the available queue.
613 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
614 if (PendingQueue[i].first == CurCycle) {
615 AvailableQueue->push(PendingQueue[i].second);
616 PendingQueue[i].second->isAvailable = true;
617 PendingQueue[i] = PendingQueue.back();
618 PendingQueue.pop_back();
621 assert(PendingQueue[i].first > CurCycle && "Negative latency?");
625 // If there are no instructions available, don't try to issue anything, and
626 // don't advance the hazard recognizer.
627 if (AvailableQueue->empty()) {
632 SUnit *FoundSUnit = 0;
633 SDNode *FoundNode = 0;
635 bool HasNoopHazards = false;
636 while (!AvailableQueue->empty()) {
637 SUnit *CurSUnit = AvailableQueue->pop();
639 // Get the node represented by this SUnit.
640 FoundNode = CurSUnit->Node;
642 // If this is a pseudo op, like copyfromreg, look to see if there is a
643 // real target node flagged to it. If so, use the target node.
644 for (unsigned i = 0, e = CurSUnit->FlaggedNodes.size();
645 FoundNode->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
646 FoundNode = CurSUnit->FlaggedNodes[i];
648 HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
649 if (HT == HazardRecognizer::NoHazard) {
650 FoundSUnit = CurSUnit;
654 // Remember if this is a noop hazard.
655 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
657 NotReady.push_back(CurSUnit);
660 // Add the nodes that aren't ready back onto the available list.
661 if (!NotReady.empty()) {
662 AvailableQueue->push_all(NotReady);
666 // If we found a node to schedule, do it now.
668 ScheduleNodeTopDown(FoundSUnit, CurCycle);
669 HazardRec->EmitInstruction(FoundNode);
670 FoundSUnit->isScheduled = true;
671 AvailableQueue->ScheduledNode(FoundSUnit);
673 // If this is a pseudo-op node, we don't want to increment the current
675 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
677 } else if (!HasNoopHazards) {
678 // Otherwise, we have a pipeline stall, but no other problem, just advance
679 // the current cycle and try again.
680 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
681 HazardRec->AdvanceCycle();
685 // Otherwise, we have no instructions to issue and we have instructions
686 // that will fault if we don't do this right. This is the case for
687 // processors without pipeline interlocks and other cases.
688 DEBUG(std::cerr << "*** Emitting noop\n");
689 HazardRec->EmitNoop();
690 Sequence.push_back(0); // NULL SUnit* -> noop
697 // Verify that all SUnits were scheduled.
698 bool AnyNotSched = false;
699 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
700 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
702 std::cerr << "*** List scheduling failed! ***\n";
703 SUnits[i].dump(&DAG);
704 std::cerr << "has not been scheduled!\n";
708 assert(!AnyNotSched);
712 //===----------------------------------------------------------------------===//
713 // RegReductionPriorityQueue Implementation
714 //===----------------------------------------------------------------------===//
716 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
717 // to reduce register pressure.
720 class RegReductionPriorityQueue;
722 /// Sorting functions for the Available queue.
723 struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
724 RegReductionPriorityQueue *SPQ;
725 ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
726 ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
728 bool operator()(const SUnit* left, const SUnit* right) const;
730 } // end anonymous namespace
733 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
734 // SUnits - The SUnits for the current graph.
735 const std::vector<SUnit> *SUnits;
737 // SethiUllmanNumbers - The SethiUllman number for each node.
738 std::vector<int> SethiUllmanNumbers;
740 std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
742 RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
745 void initNodes(const std::vector<SUnit> &sunits) {
747 // Calculate node priorities.
748 CalculatePriorities();
750 void releaseState() {
752 SethiUllmanNumbers.clear();
755 unsigned getSethiUllmanNumber(unsigned NodeNum) const {
756 assert(NodeNum < SethiUllmanNumbers.size());
757 return SethiUllmanNumbers[NodeNum];
760 bool empty() const { return Queue.empty(); }
762 void push(SUnit *U) {
765 void push_all(const std::vector<SUnit *> &Nodes) {
766 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
767 Queue.push(Nodes[i]);
771 SUnit *V = Queue.top();
776 void CalculatePriorities();
777 int CalcNodePriority(const SUnit *SU);
781 bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
782 unsigned LeftNum = left->NodeNum;
783 unsigned RightNum = right->NodeNum;
785 int LBonus = (int)left ->isDefNUseOperand;
786 int RBonus = (int)right->isDefNUseOperand;
788 // Special tie breaker: if two nodes share a operand, the one that
789 // use it as a def&use operand is preferred.
790 if (left->isTwoAddress && !right->isTwoAddress) {
791 SDNode *DUNode = left->Node->getOperand(0).Val;
792 if (DUNode->isOperand(right->Node))
795 if (!left->isTwoAddress && right->isTwoAddress) {
796 SDNode *DUNode = right->Node->getOperand(0).Val;
797 if (DUNode->isOperand(left->Node))
801 // Priority1 is just the number of live range genned.
802 int LPriority1 = left ->NumPredsLeft - LBonus;
803 int RPriority1 = right->NumPredsLeft - RBonus;
804 int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
805 int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
807 if (LPriority1 > RPriority1)
809 else if (LPriority1 == RPriority1)
810 if (LPriority2 < RPriority2)
812 else if (LPriority2 == RPriority2)
813 if (left->CycleBound > right->CycleBound)
820 /// CalcNodePriority - Priority is the Sethi Ullman number.
821 /// Smaller number is the higher priority.
822 int RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
823 int &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
824 if (SethiUllmanNumber != INT_MIN)
825 return SethiUllmanNumber;
827 if (SU->Preds.size() == 0) {
828 SethiUllmanNumber = 1;
831 for (std::set<std::pair<SUnit*, bool> >::const_iterator
832 I = SU->Preds.begin(), E = SU->Preds.end(); I != E; ++I) {
833 if (I->second) continue; // ignore chain preds.
834 SUnit *PredSU = I->first;
835 int PredSethiUllman = CalcNodePriority(PredSU);
836 if (PredSethiUllman > SethiUllmanNumber) {
837 SethiUllmanNumber = PredSethiUllman;
839 } else if (PredSethiUllman == SethiUllmanNumber)
843 if (SU->Node->getOpcode() != ISD::TokenFactor)
844 SethiUllmanNumber += Extra;
846 SethiUllmanNumber = (Extra == 1) ? 0 : Extra-1;
849 return SethiUllmanNumber;
852 /// CalculatePriorities - Calculate priorities of all scheduling units.
853 void RegReductionPriorityQueue::CalculatePriorities() {
854 SethiUllmanNumbers.assign(SUnits->size(), INT_MIN);
856 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
857 CalcNodePriority(&(*SUnits)[i]);
860 //===----------------------------------------------------------------------===//
861 // LatencyPriorityQueue Implementation
862 //===----------------------------------------------------------------------===//
864 // This is a SchedulingPriorityQueue that schedules using latency information to
865 // reduce the length of the critical path through the basic block.
868 class LatencyPriorityQueue;
870 /// Sorting functions for the Available queue.
871 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
872 LatencyPriorityQueue *PQ;
873 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
874 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
876 bool operator()(const SUnit* left, const SUnit* right) const;
878 } // end anonymous namespace
881 class LatencyPriorityQueue : public SchedulingPriorityQueue {
882 // SUnits - The SUnits for the current graph.
883 const std::vector<SUnit> *SUnits;
885 // Latencies - The latency (max of latency from this node to the bb exit)
887 std::vector<int> Latencies;
889 /// NumNodesSolelyBlocking - This vector contains, for every node in the
890 /// Queue, the number of nodes that the node is the sole unscheduled
891 /// predecessor for. This is used as a tie-breaker heuristic for better
893 std::vector<unsigned> NumNodesSolelyBlocking;
895 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
897 LatencyPriorityQueue() : Queue(latency_sort(this)) {
900 void initNodes(const std::vector<SUnit> &sunits) {
902 // Calculate node priorities.
903 CalculatePriorities();
905 void releaseState() {
910 unsigned getLatency(unsigned NodeNum) const {
911 assert(NodeNum < Latencies.size());
912 return Latencies[NodeNum];
915 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
916 assert(NodeNum < NumNodesSolelyBlocking.size());
917 return NumNodesSolelyBlocking[NodeNum];
920 bool empty() const { return Queue.empty(); }
922 virtual void push(SUnit *U) {
925 void push_impl(SUnit *U);
927 void push_all(const std::vector<SUnit *> &Nodes) {
928 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
933 SUnit *V = Queue.top();
938 // ScheduledNode - As nodes are scheduled, we look to see if there are any
939 // successor nodes that have a single unscheduled predecessor. If so, that
940 // single predecessor has a higher priority, since scheduling it will make
941 // the node available.
942 void ScheduledNode(SUnit *Node);
945 void CalculatePriorities();
946 int CalcLatency(const SUnit &SU);
947 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
949 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
950 /// node from a priority queue. We should roll our own heap to make this
951 /// better or something.
952 void RemoveFromPriorityQueue(SUnit *SU) {
953 std::vector<SUnit*> Temp;
955 assert(!Queue.empty() && "Not in queue!");
956 while (Queue.top() != SU) {
957 Temp.push_back(Queue.top());
959 assert(!Queue.empty() && "Not in queue!");
962 // Remove the node from the PQ.
965 // Add all the other nodes back.
966 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
972 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
973 unsigned LHSNum = LHS->NodeNum;
974 unsigned RHSNum = RHS->NodeNum;
976 // The most important heuristic is scheduling the critical path.
977 unsigned LHSLatency = PQ->getLatency(LHSNum);
978 unsigned RHSLatency = PQ->getLatency(RHSNum);
979 if (LHSLatency < RHSLatency) return true;
980 if (LHSLatency > RHSLatency) return false;
982 // After that, if two nodes have identical latencies, look to see if one will
983 // unblock more other nodes than the other.
984 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
985 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
986 if (LHSBlocked < RHSBlocked) return true;
987 if (LHSBlocked > RHSBlocked) return false;
989 // Finally, just to provide a stable ordering, use the node number as a
991 return LHSNum < RHSNum;
995 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
997 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
998 int &Latency = Latencies[SU.NodeNum];
1002 int MaxSuccLatency = 0;
1003 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU.Succs.begin(),
1004 E = SU.Succs.end(); I != E; ++I)
1005 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
1007 return Latency = MaxSuccLatency + SU.Latency;
1010 /// CalculatePriorities - Calculate priorities of all scheduling units.
1011 void LatencyPriorityQueue::CalculatePriorities() {
1012 Latencies.assign(SUnits->size(), -1);
1013 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
1015 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1016 CalcLatency((*SUnits)[i]);
1019 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
1020 /// of SU, return it, otherwise return null.
1021 static SUnit *getSingleUnscheduledPred(SUnit *SU) {
1022 SUnit *OnlyAvailablePred = 0;
1023 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Preds.begin(),
1024 E = SU->Preds.end(); I != E; ++I)
1025 if (!I->first->isScheduled) {
1026 // We found an available, but not scheduled, predecessor. If it's the
1027 // only one we have found, keep track of it... otherwise give up.
1028 if (OnlyAvailablePred && OnlyAvailablePred != I->first)
1030 OnlyAvailablePred = I->first;
1033 return OnlyAvailablePred;
1036 void LatencyPriorityQueue::push_impl(SUnit *SU) {
1037 // Look at all of the successors of this node. Count the number of nodes that
1038 // this node is the sole unscheduled node for.
1039 unsigned NumNodesBlocking = 0;
1040 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
1041 E = SU->Succs.end(); I != E; ++I)
1042 if (getSingleUnscheduledPred(I->first) == SU)
1044 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
1050 // ScheduledNode - As nodes are scheduled, we look to see if there are any
1051 // successor nodes that have a single unscheduled predecessor. If so, that
1052 // single predecessor has a higher priority, since scheduling it will make
1053 // the node available.
1054 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
1055 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
1056 E = SU->Succs.end(); I != E; ++I)
1057 AdjustPriorityOfUnscheduledPreds(I->first);
1060 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
1061 /// scheduled. If SU is not itself available, then there is at least one
1062 /// predecessor node that has not been scheduled yet. If SU has exactly ONE
1063 /// unscheduled predecessor, we want to increase its priority: it getting
1064 /// scheduled will make this node available, so it is better than some other
1065 /// node of the same priority that will not make a node available.
1066 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
1067 if (SU->isPending) return; // All preds scheduled.
1069 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
1070 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
1072 // Okay, we found a single predecessor that is available, but not scheduled.
1073 // Since it is available, it must be in the priority queue. First remove it.
1074 RemoveFromPriorityQueue(OnlyAvailablePred);
1076 // Reinsert the node into the priority queue, which recomputes its
1077 // NumNodesSolelyBlocking value.
1078 push(OnlyAvailablePred);
1082 //===----------------------------------------------------------------------===//
1083 // Public Constructor Functions
1084 //===----------------------------------------------------------------------===//
1086 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
1087 MachineBasicBlock *BB) {
1088 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true,
1089 new RegReductionPriorityQueue(),
1090 new HazardRecognizer());
1093 /// createTDListDAGScheduler - This creates a top-down list scheduler with the
1094 /// specified hazard recognizer.
1095 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
1096 MachineBasicBlock *BB,
1097 HazardRecognizer *HR) {
1098 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
1099 new LatencyPriorityQueue(),