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 // TEMPORARY option to test a fix.
38 SchedIgnorStore("sched-ignore-store", cl::Hidden);
43 Statistic<> NumNoops ("scheduler", "Number of noops inserted");
44 Statistic<> NumStalls("scheduler", "Number of pipeline stalls");
46 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
47 /// a group of nodes flagged together.
49 SDNode *Node; // Representative node.
50 std::vector<SDNode*> FlaggedNodes; // All nodes flagged to Node.
52 // Preds/Succs - The SUnits before/after us in the graph. The boolean value
53 // is true if the edge is a token chain edge, false if it is a value edge.
54 std::set<std::pair<SUnit*,bool> > Preds; // All sunit predecessors.
55 std::set<std::pair<SUnit*,bool> > Succs; // All sunit successors.
57 short NumPredsLeft; // # of preds not scheduled.
58 short NumSuccsLeft; // # of succs not scheduled.
59 short NumChainPredsLeft; // # of chain preds not scheduled.
60 short NumChainSuccsLeft; // # of chain succs not scheduled.
61 bool isStore : 1; // Is a store.
62 bool isTwoAddress : 1; // Is a two-address instruction.
63 bool isDefNUseOperand : 1; // Is a def&use operand.
64 bool isPending : 1; // True once pending.
65 bool isAvailable : 1; // True once available.
66 bool isScheduled : 1; // True once scheduled.
67 unsigned short Latency; // Node latency.
68 unsigned CycleBound; // Upper/lower cycle to be scheduled at.
69 unsigned Cycle; // Once scheduled, the cycle of the op.
70 unsigned NodeNum; // Entry # of node in the node vector.
72 SUnit(SDNode *node, unsigned nodenum)
73 : Node(node), NumPredsLeft(0), NumSuccsLeft(0),
74 NumChainPredsLeft(0), NumChainSuccsLeft(0), isStore(false),
75 isTwoAddress(false), isDefNUseOperand(false),
76 isPending(false), isAvailable(false), isScheduled(false),
77 Latency(0), CycleBound(0), Cycle(0), NodeNum(nodenum) {}
79 void dump(const SelectionDAG *G) const;
80 void dumpAll(const SelectionDAG *G) const;
84 void SUnit::dump(const SelectionDAG *G) const {
88 if (FlaggedNodes.size() != 0) {
89 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
91 FlaggedNodes[i]->dump(G);
97 void SUnit::dumpAll(const SelectionDAG *G) const {
100 std::cerr << " # preds left : " << NumPredsLeft << "\n";
101 std::cerr << " # succs left : " << NumSuccsLeft << "\n";
102 std::cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
103 std::cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
104 std::cerr << " Latency : " << Latency << "\n";
106 if (Preds.size() != 0) {
107 std::cerr << " Predecessors:\n";
108 for (std::set<std::pair<SUnit*,bool> >::const_iterator I = Preds.begin(),
109 E = Preds.end(); I != E; ++I) {
113 std::cerr << " val ";
117 if (Succs.size() != 0) {
118 std::cerr << " Successors:\n";
119 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = Succs.begin(),
120 E = Succs.end(); I != E; ++I) {
124 std::cerr << " val ";
131 //===----------------------------------------------------------------------===//
132 /// SchedulingPriorityQueue - This interface is used to plug different
133 /// priorities computation algorithms into the list scheduler. It implements the
134 /// interface of a standard priority queue, where nodes are inserted in
135 /// arbitrary order and returned in priority order. The computation of the
136 /// priority and the representation of the queue are totally up to the
137 /// implementation to decide.
140 class SchedulingPriorityQueue {
142 virtual ~SchedulingPriorityQueue() {}
144 virtual void initNodes(const std::vector<SUnit> &SUnits) = 0;
145 virtual void releaseState() = 0;
147 virtual bool empty() const = 0;
148 virtual void push(SUnit *U) = 0;
150 virtual void push_all(const std::vector<SUnit *> &Nodes) = 0;
151 virtual SUnit *pop() = 0;
153 /// ScheduledNode - As each node is scheduled, this method is invoked. This
154 /// allows the priority function to adjust the priority of node that have
155 /// already been emitted.
156 virtual void ScheduledNode(SUnit *Node) {}
163 //===----------------------------------------------------------------------===//
164 /// ScheduleDAGList - The actual list scheduler implementation. This supports
165 /// both top-down and bottom-up scheduling.
167 class ScheduleDAGList : public ScheduleDAG {
169 // SDNode to SUnit mapping (many to one).
170 std::map<SDNode*, SUnit*> SUnitMap;
171 // The schedule. Null SUnit*'s represent noop instructions.
172 std::vector<SUnit*> Sequence;
174 // The scheduling units.
175 std::vector<SUnit> SUnits;
177 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
181 /// AvailableQueue - The priority queue to use for the available SUnits.
183 SchedulingPriorityQueue *AvailableQueue;
185 /// PendingQueue - This contains all of the instructions whose operands have
186 /// been issued, but their results are not ready yet (due to the latency of
187 /// the operation). Once the operands becomes available, the instruction is
188 /// added to the AvailableQueue. This keeps track of each SUnit and the
189 /// number of cycles left to execute before the operation is available.
190 std::vector<std::pair<unsigned, SUnit*> > PendingQueue;
192 /// HazardRec - The hazard recognizer to use.
193 HazardRecognizer *HazardRec;
196 ScheduleDAGList(SelectionDAG &dag, MachineBasicBlock *bb,
197 const TargetMachine &tm, bool isbottomup,
198 SchedulingPriorityQueue *availqueue,
199 HazardRecognizer *HR)
200 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
201 AvailableQueue(availqueue), HazardRec(HR) {
206 delete AvailableQueue;
211 void dumpSchedule() const;
214 SUnit *NewSUnit(SDNode *N);
215 void ReleasePred(SUnit *PredSU, bool isChain, unsigned CurCycle);
216 void ReleaseSucc(SUnit *SuccSU, bool isChain);
217 void ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle);
218 void ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle);
219 void ListScheduleTopDown();
220 void ListScheduleBottomUp();
221 void BuildSchedUnits();
224 } // end anonymous namespace
226 HazardRecognizer::~HazardRecognizer() {}
229 /// NewSUnit - Creates a new SUnit and return a ptr to it.
230 SUnit *ScheduleDAGList::NewSUnit(SDNode *N) {
231 SUnits.push_back(SUnit(N, SUnits.size()));
232 return &SUnits.back();
235 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
236 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
237 /// together nodes with a single SUnit.
238 void ScheduleDAGList::BuildSchedUnits() {
239 // Reserve entries in the vector for each of the SUnits we are creating. This
240 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
242 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
244 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
246 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
247 E = DAG.allnodes_end(); NI != E; ++NI) {
248 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
251 // If this node has already been processed, stop now.
252 if (SUnitMap[NI]) continue;
254 SUnit *NodeSUnit = NewSUnit(NI);
256 // See if anything is flagged to this node, if so, add them to flagged
257 // nodes. Nodes can have at most one flag input and one flag output. Flags
258 // are required the be the last operand and result of a node.
260 // Scan up, adding flagged preds to FlaggedNodes.
262 while (N->getNumOperands() &&
263 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
264 N = N->getOperand(N->getNumOperands()-1).Val;
265 NodeSUnit->FlaggedNodes.push_back(N);
266 SUnitMap[N] = NodeSUnit;
269 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
270 // have a user of the flag operand.
272 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
273 SDOperand FlagVal(N, N->getNumValues()-1);
275 // There are either zero or one users of the Flag result.
276 bool HasFlagUse = false;
277 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
279 if (FlagVal.isOperand(*UI)) {
281 NodeSUnit->FlaggedNodes.push_back(N);
282 SUnitMap[N] = NodeSUnit;
286 if (!HasFlagUse) break;
289 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
292 SUnitMap[N] = NodeSUnit;
294 // Compute the latency for the node. We use the sum of the latencies for
295 // all nodes flagged together into this SUnit.
296 if (InstrItins.isEmpty()) {
297 // No latency information.
298 NodeSUnit->Latency = 1;
300 NodeSUnit->Latency = 0;
301 if (N->isTargetOpcode()) {
302 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
303 InstrStage *S = InstrItins.begin(SchedClass);
304 InstrStage *E = InstrItins.end(SchedClass);
306 NodeSUnit->Latency += S->Cycles;
308 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
309 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
310 if (FNode->isTargetOpcode()) {
311 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
312 InstrStage *S = InstrItins.begin(SchedClass);
313 InstrStage *E = InstrItins.end(SchedClass);
315 NodeSUnit->Latency += S->Cycles;
321 // Pass 2: add the preds, succs, etc.
322 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
323 SUnit *SU = &SUnits[su];
324 SDNode *MainNode = SU->Node;
326 if (MainNode->isTargetOpcode()) {
327 unsigned Opc = MainNode->getTargetOpcode();
328 if (TII->isTwoAddrInstr(Opc))
329 SU->isTwoAddress = true;
330 if (TII->isStore(Opc))
331 if (!SchedIgnorStore)
335 // Find all predecessors and successors of the group.
336 // Temporarily add N to make code simpler.
337 SU->FlaggedNodes.push_back(MainNode);
339 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
340 SDNode *N = SU->FlaggedNodes[n];
342 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
343 SDNode *OpN = N->getOperand(i).Val;
344 if (isPassiveNode(OpN)) continue; // Not scheduled.
345 SUnit *OpSU = SUnitMap[OpN];
346 assert(OpSU && "Node has no SUnit!");
347 if (OpSU == SU) continue; // In the same group.
349 MVT::ValueType OpVT = N->getOperand(i).getValueType();
350 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
351 bool isChain = OpVT == MVT::Other;
353 if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
357 SU->NumChainPredsLeft++;
360 if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
362 OpSU->NumSuccsLeft++;
364 OpSU->NumChainSuccsLeft++;
370 // Remove MainNode from FlaggedNodes again.
371 SU->FlaggedNodes.pop_back();
374 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
375 SUnits[su].dumpAll(&DAG));
379 /// EmitSchedule - Emit the machine code in scheduled order.
380 void ScheduleDAGList::EmitSchedule() {
381 std::map<SDNode*, unsigned> VRBaseMap;
382 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
383 if (SUnit *SU = Sequence[i]) {
384 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
385 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
386 EmitNode(SU->Node, VRBaseMap);
388 // Null SUnit* is a noop.
394 /// dump - dump the schedule.
395 void ScheduleDAGList::dumpSchedule() const {
396 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
397 if (SUnit *SU = Sequence[i])
400 std::cerr << "**** NOOP ****\n";
404 /// Schedule - Schedule the DAG using list scheduling.
405 void ScheduleDAGList::Schedule() {
406 DEBUG(std::cerr << "********** List Scheduling **********\n");
408 // Build scheduling units.
411 AvailableQueue->initNodes(SUnits);
413 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
415 ListScheduleBottomUp();
417 ListScheduleTopDown();
419 AvailableQueue->releaseState();
421 DEBUG(std::cerr << "*** Final schedule ***\n");
422 DEBUG(dumpSchedule());
423 DEBUG(std::cerr << "\n");
425 // Emit in scheduled order
429 //===----------------------------------------------------------------------===//
430 // Bottom-Up Scheduling
431 //===----------------------------------------------------------------------===//
433 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
434 /// the Available queue is the count reaches zero. Also update its cycle bound.
435 void ScheduleDAGList::ReleasePred(SUnit *PredSU, bool isChain,
437 // FIXME: the distance between two nodes is not always == the predecessor's
438 // latency. For example, the reader can very well read the register written
439 // by the predecessor later than the issue cycle. It also depends on the
440 // interrupt model (drain vs. freeze).
441 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
444 PredSU->NumSuccsLeft--;
446 PredSU->NumChainSuccsLeft--;
449 if (PredSU->NumSuccsLeft < 0 || PredSU->NumChainSuccsLeft < 0) {
450 std::cerr << "*** List scheduling failed! ***\n";
452 std::cerr << " has been released too many times!\n";
457 if ((PredSU->NumSuccsLeft + PredSU->NumChainSuccsLeft) == 0) {
458 // EntryToken has to go last! Special case it here.
459 if (PredSU->Node->getOpcode() != ISD::EntryToken) {
460 PredSU->isAvailable = true;
461 AvailableQueue->push(PredSU);
465 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
466 /// count of its predecessors. If a predecessor pending count is zero, add it to
467 /// the Available queue.
468 void ScheduleDAGList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
469 DEBUG(std::cerr << "*** Scheduling [" << CurCycle << "]: ");
470 DEBUG(SU->dump(&DAG));
471 SU->Cycle = CurCycle;
473 Sequence.push_back(SU);
475 // Bottom up: release predecessors
476 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
477 E = SU->Preds.end(); I != E; ++I) {
478 ReleasePred(I->first, I->second, CurCycle);
479 // FIXME: This is something used by the priority function that it should
480 // calculate directly.
486 /// isReady - True if node's lower cycle bound is less or equal to the current
487 /// scheduling cycle. Always true if all nodes have uniform latency 1.
488 static inline bool isReady(SUnit *SU, unsigned CurrCycle) {
489 return SU->CycleBound <= CurrCycle;
492 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
494 void ScheduleDAGList::ListScheduleBottomUp() {
495 unsigned CurrCycle = 0;
496 // Add root to Available queue.
497 AvailableQueue->push(SUnitMap[DAG.getRoot().Val]);
499 // While Available queue is not empty, grab the node with the highest
500 // priority. If it is not ready put it back. Schedule the node.
501 std::vector<SUnit*> NotReady;
502 while (!AvailableQueue->empty()) {
503 SUnit *CurrNode = AvailableQueue->pop();
505 while (!isReady(CurrNode, CurrCycle)) {
506 NotReady.push_back(CurrNode);
507 CurrNode = AvailableQueue->pop();
510 // Add the nodes that aren't ready back onto the available list.
511 AvailableQueue->push_all(NotReady);
514 ScheduleNodeBottomUp(CurrNode, CurrCycle);
516 CurrNode->isScheduled = true;
517 AvailableQueue->ScheduledNode(CurrNode);
520 // Add entry node last
521 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
522 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
523 Sequence.push_back(Entry);
526 // Reverse the order if it is bottom up.
527 std::reverse(Sequence.begin(), Sequence.end());
531 // Verify that all SUnits were scheduled.
532 bool AnyNotSched = false;
533 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
534 if (SUnits[i].NumSuccsLeft != 0 || SUnits[i].NumChainSuccsLeft != 0) {
536 std::cerr << "*** List scheduling failed! ***\n";
537 SUnits[i].dump(&DAG);
538 std::cerr << "has not been scheduled!\n";
542 assert(!AnyNotSched);
546 //===----------------------------------------------------------------------===//
547 // Top-Down Scheduling
548 //===----------------------------------------------------------------------===//
550 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
551 /// the PendingQueue if the count reaches zero.
552 void ScheduleDAGList::ReleaseSucc(SUnit *SuccSU, bool isChain) {
554 SuccSU->NumPredsLeft--;
556 SuccSU->NumChainPredsLeft--;
558 assert(SuccSU->NumPredsLeft >= 0 && SuccSU->NumChainPredsLeft >= 0 &&
559 "List scheduling internal error");
561 if ((SuccSU->NumPredsLeft + SuccSU->NumChainPredsLeft) == 0) {
562 // Compute how many cycles it will be before this actually becomes
563 // available. This is the max of the start time of all predecessors plus
565 unsigned AvailableCycle = 0;
566 for (std::set<std::pair<SUnit*, bool> >::iterator I = SuccSU->Preds.begin(),
567 E = SuccSU->Preds.end(); I != E; ++I) {
568 // If this is a token edge, we don't need to wait for the latency of the
569 // preceeding instruction (e.g. a long-latency load) unless there is also
570 // some other data dependence.
571 unsigned PredDoneCycle = I->first->Cycle;
573 PredDoneCycle += I->first->Latency;
574 else if (I->first->Latency)
577 AvailableCycle = std::max(AvailableCycle, PredDoneCycle);
580 PendingQueue.push_back(std::make_pair(AvailableCycle, SuccSU));
581 SuccSU->isPending = true;
585 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
586 /// count of its successors. If a successor pending count is zero, add it to
587 /// the Available queue.
588 void ScheduleDAGList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
589 DEBUG(std::cerr << "*** Scheduling [" << CurCycle << "]: ");
590 DEBUG(SU->dump(&DAG));
592 Sequence.push_back(SU);
593 SU->Cycle = CurCycle;
595 // Bottom up: release successors.
596 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
597 E = SU->Succs.end(); I != E; ++I)
598 ReleaseSucc(I->first, I->second);
601 /// ListScheduleTopDown - The main loop of list scheduling for top-down
603 void ScheduleDAGList::ListScheduleTopDown() {
604 unsigned CurCycle = 0;
605 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
607 // All leaves to Available queue.
608 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
609 // It is available if it has no predecessors.
610 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
611 AvailableQueue->push(&SUnits[i]);
612 SUnits[i].isAvailable = SUnits[i].isPending = true;
616 // Emit the entry node first.
617 ScheduleNodeTopDown(Entry, CurCycle);
618 HazardRec->EmitInstruction(Entry->Node);
620 // While Available queue is not empty, grab the node with the highest
621 // priority. If it is not ready put it back. Schedule the node.
622 std::vector<SUnit*> NotReady;
623 while (!AvailableQueue->empty() || !PendingQueue.empty()) {
624 // Check to see if any of the pending instructions are ready to issue. If
625 // so, add them to the available queue.
626 for (unsigned i = 0, e = PendingQueue.size(); i != e; ++i) {
627 if (PendingQueue[i].first == CurCycle) {
628 AvailableQueue->push(PendingQueue[i].second);
629 PendingQueue[i].second->isAvailable = true;
630 PendingQueue[i] = PendingQueue.back();
631 PendingQueue.pop_back();
634 assert(PendingQueue[i].first > CurCycle && "Negative latency?");
638 // If there are no instructions available, don't try to issue anything, and
639 // don't advance the hazard recognizer.
640 if (AvailableQueue->empty()) {
645 SUnit *FoundSUnit = 0;
646 SDNode *FoundNode = 0;
648 bool HasNoopHazards = false;
649 while (!AvailableQueue->empty()) {
650 SUnit *CurSUnit = AvailableQueue->pop();
652 // Get the node represented by this SUnit.
653 FoundNode = CurSUnit->Node;
655 // If this is a pseudo op, like copyfromreg, look to see if there is a
656 // real target node flagged to it. If so, use the target node.
657 for (unsigned i = 0, e = CurSUnit->FlaggedNodes.size();
658 FoundNode->getOpcode() < ISD::BUILTIN_OP_END && i != e; ++i)
659 FoundNode = CurSUnit->FlaggedNodes[i];
661 HazardRecognizer::HazardType HT = HazardRec->getHazardType(FoundNode);
662 if (HT == HazardRecognizer::NoHazard) {
663 FoundSUnit = CurSUnit;
667 // Remember if this is a noop hazard.
668 HasNoopHazards |= HT == HazardRecognizer::NoopHazard;
670 NotReady.push_back(CurSUnit);
673 // Add the nodes that aren't ready back onto the available list.
674 if (!NotReady.empty()) {
675 AvailableQueue->push_all(NotReady);
679 // If we found a node to schedule, do it now.
681 ScheduleNodeTopDown(FoundSUnit, CurCycle);
682 HazardRec->EmitInstruction(FoundNode);
683 FoundSUnit->isScheduled = true;
684 AvailableQueue->ScheduledNode(FoundSUnit);
686 // If this is a pseudo-op node, we don't want to increment the current
688 if (FoundSUnit->Latency) // Don't increment CurCycle for pseudo-ops!
690 } else if (!HasNoopHazards) {
691 // Otherwise, we have a pipeline stall, but no other problem, just advance
692 // the current cycle and try again.
693 DEBUG(std::cerr << "*** Advancing cycle, no work to do\n");
694 HazardRec->AdvanceCycle();
698 // Otherwise, we have no instructions to issue and we have instructions
699 // that will fault if we don't do this right. This is the case for
700 // processors without pipeline interlocks and other cases.
701 DEBUG(std::cerr << "*** Emitting noop\n");
702 HazardRec->EmitNoop();
703 Sequence.push_back(0); // NULL SUnit* -> noop
710 // Verify that all SUnits were scheduled.
711 bool AnyNotSched = false;
712 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
713 if (SUnits[i].NumPredsLeft != 0 || SUnits[i].NumChainPredsLeft != 0) {
715 std::cerr << "*** List scheduling failed! ***\n";
716 SUnits[i].dump(&DAG);
717 std::cerr << "has not been scheduled!\n";
721 assert(!AnyNotSched);
725 //===----------------------------------------------------------------------===//
726 // RegReductionPriorityQueue Implementation
727 //===----------------------------------------------------------------------===//
729 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
730 // to reduce register pressure.
733 class RegReductionPriorityQueue;
735 /// Sorting functions for the Available queue.
736 struct ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
737 RegReductionPriorityQueue *SPQ;
738 ls_rr_sort(RegReductionPriorityQueue *spq) : SPQ(spq) {}
739 ls_rr_sort(const ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
741 bool operator()(const SUnit* left, const SUnit* right) const;
743 } // end anonymous namespace
746 class RegReductionPriorityQueue : public SchedulingPriorityQueue {
747 // SUnits - The SUnits for the current graph.
748 const std::vector<SUnit> *SUnits;
750 // SethiUllmanNumbers - The SethiUllman number for each node.
751 std::vector<unsigned> SethiUllmanNumbers;
753 std::priority_queue<SUnit*, std::vector<SUnit*>, ls_rr_sort> Queue;
755 RegReductionPriorityQueue() : Queue(ls_rr_sort(this)) {
758 void initNodes(const std::vector<SUnit> &sunits) {
760 // Calculate node priorities.
761 CalculatePriorities();
763 void releaseState() {
765 SethiUllmanNumbers.clear();
768 unsigned getSethiUllmanNumber(unsigned NodeNum) const {
769 assert(NodeNum < SethiUllmanNumbers.size());
770 return SethiUllmanNumbers[NodeNum];
773 bool empty() const { return Queue.empty(); }
775 void push(SUnit *U) {
778 void push_all(const std::vector<SUnit *> &Nodes) {
779 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
780 Queue.push(Nodes[i]);
784 SUnit *V = Queue.top();
789 void CalculatePriorities();
790 unsigned CalcNodePriority(const SUnit *SU);
794 bool ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
795 unsigned LeftNum = left->NodeNum;
796 unsigned RightNum = right->NodeNum;
798 int LBonus = (int)left ->isDefNUseOperand;
799 int RBonus = (int)right->isDefNUseOperand;
801 // Special tie breaker: if two nodes share a operand, the one that
802 // use it as a def&use operand is preferred.
803 if (left->isTwoAddress && !right->isTwoAddress) {
804 SDNode *DUNode = left->Node->getOperand(0).Val;
805 if (DUNode->isOperand(right->Node))
808 if (!left->isTwoAddress && right->isTwoAddress) {
809 SDNode *DUNode = right->Node->getOperand(0).Val;
810 if (DUNode->isOperand(left->Node))
814 // Push stores up as much as possible. This really help code like this:
821 // This would make sure the scheduled code completed all computations and
822 // the stores before the next series of computation starts.
823 if (!left->isStore && right->isStore)
825 if (left->isStore && !right->isStore)
828 // Priority1 is just the number of live range genned.
829 int LPriority1 = left ->NumPredsLeft - LBonus;
830 int RPriority1 = right->NumPredsLeft - RBonus;
831 int LPriority2 = SPQ->getSethiUllmanNumber(LeftNum) + LBonus;
832 int RPriority2 = SPQ->getSethiUllmanNumber(RightNum) + RBonus;
834 if (LPriority1 > RPriority1)
836 else if (LPriority1 == RPriority1)
837 if (LPriority2 < RPriority2)
839 else if (LPriority2 == RPriority2)
840 if (left->CycleBound > right->CycleBound)
847 /// CalcNodePriority - Priority is the Sethi Ullman number.
848 /// Smaller number is the higher priority.
849 unsigned RegReductionPriorityQueue::CalcNodePriority(const SUnit *SU) {
850 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
851 if (SethiUllmanNumber != 0)
852 return SethiUllmanNumber;
854 if (SU->Preds.size() == 0) {
855 SethiUllmanNumber = 1;
858 for (std::set<std::pair<SUnit*, bool> >::const_iterator
859 I = SU->Preds.begin(), E = SU->Preds.end(); I != E; ++I) {
860 if (I->second) continue; // ignore chain preds.
861 SUnit *PredSU = I->first;
862 unsigned PredSethiUllman = CalcNodePriority(PredSU);
863 if (PredSethiUllman > SethiUllmanNumber) {
864 SethiUllmanNumber = PredSethiUllman;
866 } else if (PredSethiUllman == SethiUllmanNumber)
870 SethiUllmanNumber += Extra;
873 return SethiUllmanNumber;
876 /// CalculatePriorities - Calculate priorities of all scheduling units.
877 void RegReductionPriorityQueue::CalculatePriorities() {
878 SethiUllmanNumbers.assign(SUnits->size(), 0);
880 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
881 CalcNodePriority(&(*SUnits)[i]);
884 //===----------------------------------------------------------------------===//
885 // LatencyPriorityQueue Implementation
886 //===----------------------------------------------------------------------===//
888 // This is a SchedulingPriorityQueue that schedules using latency information to
889 // reduce the length of the critical path through the basic block.
892 class LatencyPriorityQueue;
894 /// Sorting functions for the Available queue.
895 struct latency_sort : public std::binary_function<SUnit*, SUnit*, bool> {
896 LatencyPriorityQueue *PQ;
897 latency_sort(LatencyPriorityQueue *pq) : PQ(pq) {}
898 latency_sort(const latency_sort &RHS) : PQ(RHS.PQ) {}
900 bool operator()(const SUnit* left, const SUnit* right) const;
902 } // end anonymous namespace
905 class LatencyPriorityQueue : public SchedulingPriorityQueue {
906 // SUnits - The SUnits for the current graph.
907 const std::vector<SUnit> *SUnits;
909 // Latencies - The latency (max of latency from this node to the bb exit)
911 std::vector<int> Latencies;
913 /// NumNodesSolelyBlocking - This vector contains, for every node in the
914 /// Queue, the number of nodes that the node is the sole unscheduled
915 /// predecessor for. This is used as a tie-breaker heuristic for better
917 std::vector<unsigned> NumNodesSolelyBlocking;
919 std::priority_queue<SUnit*, std::vector<SUnit*>, latency_sort> Queue;
921 LatencyPriorityQueue() : Queue(latency_sort(this)) {
924 void initNodes(const std::vector<SUnit> &sunits) {
926 // Calculate node priorities.
927 CalculatePriorities();
929 void releaseState() {
934 unsigned getLatency(unsigned NodeNum) const {
935 assert(NodeNum < Latencies.size());
936 return Latencies[NodeNum];
939 unsigned getNumSolelyBlockNodes(unsigned NodeNum) const {
940 assert(NodeNum < NumNodesSolelyBlocking.size());
941 return NumNodesSolelyBlocking[NodeNum];
944 bool empty() const { return Queue.empty(); }
946 virtual void push(SUnit *U) {
949 void push_impl(SUnit *U);
951 void push_all(const std::vector<SUnit *> &Nodes) {
952 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
957 SUnit *V = Queue.top();
962 // ScheduledNode - As nodes are scheduled, we look to see if there are any
963 // successor nodes that have a single unscheduled predecessor. If so, that
964 // single predecessor has a higher priority, since scheduling it will make
965 // the node available.
966 void ScheduledNode(SUnit *Node);
969 void CalculatePriorities();
970 int CalcLatency(const SUnit &SU);
971 void AdjustPriorityOfUnscheduledPreds(SUnit *SU);
973 /// RemoveFromPriorityQueue - This is a really inefficient way to remove a
974 /// node from a priority queue. We should roll our own heap to make this
975 /// better or something.
976 void RemoveFromPriorityQueue(SUnit *SU) {
977 std::vector<SUnit*> Temp;
979 assert(!Queue.empty() && "Not in queue!");
980 while (Queue.top() != SU) {
981 Temp.push_back(Queue.top());
983 assert(!Queue.empty() && "Not in queue!");
986 // Remove the node from the PQ.
989 // Add all the other nodes back.
990 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
996 bool latency_sort::operator()(const SUnit *LHS, const SUnit *RHS) const {
997 unsigned LHSNum = LHS->NodeNum;
998 unsigned RHSNum = RHS->NodeNum;
1000 // The most important heuristic is scheduling the critical path.
1001 unsigned LHSLatency = PQ->getLatency(LHSNum);
1002 unsigned RHSLatency = PQ->getLatency(RHSNum);
1003 if (LHSLatency < RHSLatency) return true;
1004 if (LHSLatency > RHSLatency) return false;
1006 // After that, if two nodes have identical latencies, look to see if one will
1007 // unblock more other nodes than the other.
1008 unsigned LHSBlocked = PQ->getNumSolelyBlockNodes(LHSNum);
1009 unsigned RHSBlocked = PQ->getNumSolelyBlockNodes(RHSNum);
1010 if (LHSBlocked < RHSBlocked) return true;
1011 if (LHSBlocked > RHSBlocked) return false;
1013 // Finally, just to provide a stable ordering, use the node number as a
1015 return LHSNum < RHSNum;
1019 /// CalcNodePriority - Calculate the maximal path from the node to the exit.
1021 int LatencyPriorityQueue::CalcLatency(const SUnit &SU) {
1022 int &Latency = Latencies[SU.NodeNum];
1026 int MaxSuccLatency = 0;
1027 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU.Succs.begin(),
1028 E = SU.Succs.end(); I != E; ++I)
1029 MaxSuccLatency = std::max(MaxSuccLatency, CalcLatency(*I->first));
1031 return Latency = MaxSuccLatency + SU.Latency;
1034 /// CalculatePriorities - Calculate priorities of all scheduling units.
1035 void LatencyPriorityQueue::CalculatePriorities() {
1036 Latencies.assign(SUnits->size(), -1);
1037 NumNodesSolelyBlocking.assign(SUnits->size(), 0);
1039 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1040 CalcLatency((*SUnits)[i]);
1043 /// getSingleUnscheduledPred - If there is exactly one unscheduled predecessor
1044 /// of SU, return it, otherwise return null.
1045 static SUnit *getSingleUnscheduledPred(SUnit *SU) {
1046 SUnit *OnlyAvailablePred = 0;
1047 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Preds.begin(),
1048 E = SU->Preds.end(); I != E; ++I)
1049 if (!I->first->isScheduled) {
1050 // We found an available, but not scheduled, predecessor. If it's the
1051 // only one we have found, keep track of it... otherwise give up.
1052 if (OnlyAvailablePred && OnlyAvailablePred != I->first)
1054 OnlyAvailablePred = I->first;
1057 return OnlyAvailablePred;
1060 void LatencyPriorityQueue::push_impl(SUnit *SU) {
1061 // Look at all of the successors of this node. Count the number of nodes that
1062 // this node is the sole unscheduled node for.
1063 unsigned NumNodesBlocking = 0;
1064 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
1065 E = SU->Succs.end(); I != E; ++I)
1066 if (getSingleUnscheduledPred(I->first) == SU)
1068 NumNodesSolelyBlocking[SU->NodeNum] = NumNodesBlocking;
1074 // ScheduledNode - As nodes are scheduled, we look to see if there are any
1075 // successor nodes that have a single unscheduled predecessor. If so, that
1076 // single predecessor has a higher priority, since scheduling it will make
1077 // the node available.
1078 void LatencyPriorityQueue::ScheduledNode(SUnit *SU) {
1079 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = SU->Succs.begin(),
1080 E = SU->Succs.end(); I != E; ++I)
1081 AdjustPriorityOfUnscheduledPreds(I->first);
1084 /// AdjustPriorityOfUnscheduledPreds - One of the predecessors of SU was just
1085 /// scheduled. If SU is not itself available, then there is at least one
1086 /// predecessor node that has not been scheduled yet. If SU has exactly ONE
1087 /// unscheduled predecessor, we want to increase its priority: it getting
1088 /// scheduled will make this node available, so it is better than some other
1089 /// node of the same priority that will not make a node available.
1090 void LatencyPriorityQueue::AdjustPriorityOfUnscheduledPreds(SUnit *SU) {
1091 if (SU->isPending) return; // All preds scheduled.
1093 SUnit *OnlyAvailablePred = getSingleUnscheduledPred(SU);
1094 if (OnlyAvailablePred == 0 || !OnlyAvailablePred->isAvailable) return;
1096 // Okay, we found a single predecessor that is available, but not scheduled.
1097 // Since it is available, it must be in the priority queue. First remove it.
1098 RemoveFromPriorityQueue(OnlyAvailablePred);
1100 // Reinsert the node into the priority queue, which recomputes its
1101 // NumNodesSolelyBlocking value.
1102 push(OnlyAvailablePred);
1106 //===----------------------------------------------------------------------===//
1107 // Public Constructor Functions
1108 //===----------------------------------------------------------------------===//
1110 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAG &DAG,
1111 MachineBasicBlock *BB) {
1112 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), true,
1113 new RegReductionPriorityQueue(),
1114 new HazardRecognizer());
1117 /// createTDListDAGScheduler - This creates a top-down list scheduler with the
1118 /// specified hazard recognizer.
1119 ScheduleDAG* llvm::createTDListDAGScheduler(SelectionDAG &DAG,
1120 MachineBasicBlock *BB,
1121 HazardRecognizer *HR) {
1122 return new ScheduleDAGList(DAG, BB, DAG.getTarget(), false,
1123 new LatencyPriorityQueue(),