1 //===----- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements bottom-up and top-down register pressure reduction list
11 // schedulers, using standard algorithms. The basic approach uses a priority
12 // queue of available nodes to schedule. One at a time, nodes are taken from
13 // the priority queue (thus in priority order), checked for legality to
14 // schedule, and emitted if legal.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "pre-RA-sched"
19 #include "llvm/CodeGen/ScheduleDAGSDNodes.h"
20 #include "llvm/CodeGen/SchedulerRegistry.h"
21 #include "llvm/Target/TargetRegisterInfo.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/PriorityQueue.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/CommandLine.h"
37 STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
38 STATISTIC(NumUnfolds, "Number of nodes unfolded");
39 STATISTIC(NumDups, "Number of duplicated nodes");
40 STATISTIC(NumCCCopies, "Number of cross class copies");
42 static RegisterScheduler
43 burrListDAGScheduler("list-burr",
44 "Bottom-up register reduction list scheduling",
45 createBURRListDAGScheduler);
46 static RegisterScheduler
47 tdrListrDAGScheduler("list-tdrr",
48 "Top-down register reduction list scheduling",
49 createTDRRListDAGScheduler);
52 //===----------------------------------------------------------------------===//
53 /// ScheduleDAGRRList - The actual register reduction list scheduler
54 /// implementation. This supports both top-down and bottom-up scheduling.
56 class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAGSDNodes {
58 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
62 /// AvailableQueue - The priority queue to use for the available SUnits.
63 SchedulingPriorityQueue *AvailableQueue;
65 /// LiveRegDefs - A set of physical registers and their definition
66 /// that are "live". These nodes must be scheduled before any other nodes that
67 /// modifies the registers can be scheduled.
69 std::vector<SUnit*> LiveRegDefs;
70 std::vector<unsigned> LiveRegCycles;
72 /// Topo - A topological ordering for SUnits which permits fast IsReachable
73 /// and similar queries.
74 ScheduleDAGTopologicalSort Topo;
77 ScheduleDAGRRList(SelectionDAG *dag, MachineBasicBlock *bb,
78 const TargetMachine &tm, bool isbottomup,
79 SchedulingPriorityQueue *availqueue)
80 : ScheduleDAGSDNodes(dag, bb, tm), isBottomUp(isbottomup),
81 AvailableQueue(availqueue), Topo(SUnits) {
84 ~ScheduleDAGRRList() {
85 delete AvailableQueue;
90 /// IsReachable - Checks if SU is reachable from TargetSU.
91 bool IsReachable(const SUnit *SU, const SUnit *TargetSU) {
92 return Topo.IsReachable(SU, TargetSU);
95 /// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
97 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
98 return Topo.WillCreateCycle(SU, TargetSU);
101 /// AddPred - This adds the specified node X as a predecessor of
102 /// the current node Y if not already.
103 /// This returns true if this is a new predecessor.
104 /// Updates the topological ordering if required.
105 bool AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isArtificial,
106 unsigned PhyReg = 0, int Cost = 1) {
108 return Y->addPred(X, isCtrl, isArtificial, PhyReg, Cost);
111 /// RemovePred - This removes the specified node N from the predecessors of
112 /// the current node M. Updates the topological ordering if required.
113 bool RemovePred(SUnit *M, SUnit *N, bool isCtrl, bool isArtificial) {
114 Topo.RemovePred(M, N);
115 return M->removePred(N, isCtrl, isArtificial, false);
119 void ReleasePred(SUnit *SU, SUnit *PredSU, bool isChain);
120 void ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain);
121 void CapturePred(SUnit*, SUnit*, bool);
122 void ScheduleNodeBottomUp(SUnit*, unsigned);
123 void ScheduleNodeTopDown(SUnit*, unsigned);
124 void UnscheduleNodeBottomUp(SUnit*);
125 void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
126 SUnit *CopyAndMoveSuccessors(SUnit*);
127 void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
128 const TargetRegisterClass*,
129 const TargetRegisterClass*,
130 SmallVector<SUnit*, 2>&);
131 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
132 void ListScheduleTopDown();
133 void ListScheduleBottomUp();
134 void CommuteNodesToReducePressure();
137 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
138 /// Updates the topological ordering if required.
139 SUnit *CreateNewSUnit(SDNode *N) {
140 unsigned NumSUnits = SUnits.size();
141 SUnit *NewNode = NewSUnit(N);
142 // Update the topological ordering.
143 if (NewNode->NodeNum >= NumSUnits)
144 Topo.InitDAGTopologicalSorting();
148 /// CreateClone - Creates a new SUnit from an existing one.
149 /// Updates the topological ordering if required.
150 SUnit *CreateClone(SUnit *N) {
151 unsigned NumSUnits = SUnits.size();
152 SUnit *NewNode = Clone(N);
153 // Update the topological ordering.
154 if (NewNode->NodeNum >= NumSUnits)
155 Topo.InitDAGTopologicalSorting();
159 } // end anonymous namespace
162 /// Schedule - Schedule the DAG using list scheduling.
163 void ScheduleDAGRRList::Schedule() {
164 DOUT << "********** List Scheduling **********\n";
167 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
168 LiveRegCycles.resize(TRI->getNumRegs(), 0);
170 // Build scheduling units.
173 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
174 SUnits[su].dumpAll(this));
177 Topo.InitDAGTopologicalSorting();
179 AvailableQueue->initNodes(SUnits);
181 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
183 ListScheduleBottomUp();
185 ListScheduleTopDown();
187 AvailableQueue->releaseState();
189 CommuteNodesToReducePressure();
192 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
193 /// it is not the last use of its first operand, add it to the CommuteSet if
194 /// possible. It will be commuted when it is translated to a MI.
195 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
196 SmallPtrSet<SUnit*, 4> OperandSeen;
197 for (unsigned i = Sequence.size(); i != 0; ) {
199 SUnit *SU = Sequence[i];
200 if (!SU || !SU->getNode()) continue;
201 if (SU->isCommutable) {
202 unsigned Opc = SU->getNode()->getMachineOpcode();
203 const TargetInstrDesc &TID = TII->get(Opc);
204 unsigned NumRes = TID.getNumDefs();
205 unsigned NumOps = TID.getNumOperands() - NumRes;
206 for (unsigned j = 0; j != NumOps; ++j) {
207 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
210 SDNode *OpN = SU->getNode()->getOperand(j).getNode();
211 SUnit *OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
212 if (OpSU && OperandSeen.count(OpSU) == 1) {
213 // Ok, so SU is not the last use of OpSU, but SU is two-address so
214 // it will clobber OpSU. Try to commute SU if no other source operands
216 bool DoCommute = true;
217 for (unsigned k = 0; k < NumOps; ++k) {
219 OpN = SU->getNode()->getOperand(k).getNode();
220 OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
221 if (OpSU && OperandSeen.count(OpSU) == 1) {
228 CommuteSet.insert(SU->getNode());
231 // Only look at the first use&def node for now.
236 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
239 OperandSeen.insert(I->Dep->OrigNode);
244 //===----------------------------------------------------------------------===//
245 // Bottom-Up Scheduling
246 //===----------------------------------------------------------------------===//
248 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
249 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
250 void ScheduleDAGRRList::ReleasePred(SUnit *SU, SUnit *PredSU, bool isChain) {
251 --PredSU->NumSuccsLeft;
254 if (PredSU->NumSuccsLeft < 0) {
255 cerr << "*** Scheduling failed! ***\n";
257 cerr << " has been released too many times!\n";
262 if (PredSU->NumSuccsLeft == 0) {
263 PredSU->isAvailable = true;
264 AvailableQueue->push(PredSU);
268 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
269 /// count of its predecessors. If a predecessor pending count is zero, add it to
270 /// the Available queue.
271 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
272 DOUT << "*** Scheduling [" << CurCycle << "]: ";
273 DEBUG(SU->dump(this));
275 SU->Cycle = CurCycle;
276 Sequence.push_back(SU);
278 // Bottom up: release predecessors
279 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
281 ReleasePred(SU, I->Dep, I->isCtrl);
283 // This is a physical register dependency and it's impossible or
284 // expensive to copy the register. Make sure nothing that can
285 // clobber the register is scheduled between the predecessor and
287 if (!LiveRegDefs[I->Reg]) {
289 LiveRegDefs[I->Reg] = I->Dep;
290 LiveRegCycles[I->Reg] = CurCycle;
295 // Release all the implicit physical register defs that are live.
296 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
299 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
300 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
301 assert(LiveRegDefs[I->Reg] == SU &&
302 "Physical register dependency violated?");
304 LiveRegDefs[I->Reg] = NULL;
305 LiveRegCycles[I->Reg] = 0;
310 SU->isScheduled = true;
311 AvailableQueue->ScheduledNode(SU);
314 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
315 /// unscheduled, incrcease the succ left count of its predecessors. Remove
316 /// them from AvailableQueue if necessary.
317 void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
318 if (PredSU->isAvailable) {
319 PredSU->isAvailable = false;
320 if (!PredSU->isPending)
321 AvailableQueue->remove(PredSU);
324 ++PredSU->NumSuccsLeft;
327 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
328 /// its predecessor states to reflect the change.
329 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
330 DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
331 DEBUG(SU->dump(this));
333 AvailableQueue->UnscheduledNode(SU);
335 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
337 CapturePred(I->Dep, SU, I->isCtrl);
338 if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg]) {
339 assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
340 assert(LiveRegDefs[I->Reg] == I->Dep &&
341 "Physical register dependency violated?");
343 LiveRegDefs[I->Reg] = NULL;
344 LiveRegCycles[I->Reg] = 0;
348 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
351 if (!LiveRegDefs[I->Reg]) {
352 LiveRegDefs[I->Reg] = SU;
355 if (I->Dep->Cycle < LiveRegCycles[I->Reg])
356 LiveRegCycles[I->Reg] = I->Dep->Cycle;
361 SU->isScheduled = false;
362 SU->isAvailable = true;
363 AvailableQueue->push(SU);
366 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
367 /// BTCycle in order to schedule a specific node. Returns the last unscheduled
368 /// SUnit. Also returns if a successor is unscheduled in the process.
369 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
370 unsigned &CurCycle) {
372 while (CurCycle > BtCycle) {
373 OldSU = Sequence.back();
375 if (SU->isSucc(OldSU))
376 // Don't try to remove SU from AvailableQueue.
377 SU->isAvailable = false;
378 UnscheduleNodeBottomUp(OldSU);
383 if (SU->isSucc(OldSU)) {
384 assert(false && "Something is wrong!");
391 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
392 /// successors to the newly created node.
393 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
394 if (SU->getNode()->getFlaggedNode())
397 SDNode *N = SU->getNode();
402 bool TryUnfold = false;
403 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
404 MVT VT = N->getValueType(i);
407 else if (VT == MVT::Other)
410 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
411 const SDValue &Op = N->getOperand(i);
412 MVT VT = Op.getNode()->getValueType(Op.getResNo());
418 SmallVector<SDNode*, 2> NewNodes;
419 if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
422 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
423 assert(NewNodes.size() == 2 && "Expected a load folding node!");
426 SDNode *LoadNode = NewNodes[0];
427 unsigned NumVals = N->getNumValues();
428 unsigned OldNumVals = SU->getNode()->getNumValues();
429 for (unsigned i = 0; i != NumVals; ++i)
430 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
431 DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
432 SDValue(LoadNode, 1));
434 // LoadNode may already exist. This can happen when there is another
435 // load from the same location and producing the same type of value
436 // but it has different alignment or volatileness.
437 bool isNewLoad = true;
439 if (LoadNode->getNodeId() != -1) {
440 LoadSU = &SUnits[LoadNode->getNodeId()];
443 LoadSU = CreateNewSUnit(LoadNode);
444 LoadNode->setNodeId(LoadSU->NodeNum);
446 LoadSU->Depth = SU->Depth;
447 LoadSU->Height = SU->Height;
448 ComputeLatency(LoadSU);
451 SUnit *NewSU = CreateNewSUnit(N);
452 assert(N->getNodeId() == -1 && "Node already inserted!");
453 N->setNodeId(NewSU->NodeNum);
455 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
456 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
457 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
458 NewSU->isTwoAddress = true;
462 if (TID.isCommutable())
463 NewSU->isCommutable = true;
464 // FIXME: Calculate height / depth and propagate the changes?
465 NewSU->Depth = SU->Depth;
466 NewSU->Height = SU->Height;
467 ComputeLatency(NewSU);
469 SUnit *ChainPred = NULL;
470 SmallVector<SDep, 4> ChainSuccs;
471 SmallVector<SDep, 4> LoadPreds;
472 SmallVector<SDep, 4> NodePreds;
473 SmallVector<SDep, 4> NodeSuccs;
474 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
478 else if (I->Dep->getNode() && I->Dep->getNode()->isOperandOf(LoadNode))
479 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false, false));
481 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false, false));
483 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
486 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
487 I->isCtrl, I->isArtificial, I->isAntiDep));
489 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
490 I->isCtrl, I->isArtificial, I->isAntiDep));
494 RemovePred(SU, ChainPred, true, false);
496 AddPred(LoadSU, ChainPred, true, false);
498 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
499 SDep *Pred = &LoadPreds[i];
500 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isArtificial);
502 AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isArtificial,
503 Pred->Reg, Pred->Cost);
506 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
507 SDep *Pred = &NodePreds[i];
508 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isArtificial);
509 AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isArtificial,
510 Pred->Reg, Pred->Cost);
512 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
513 SDep *Succ = &NodeSuccs[i];
514 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isArtificial);
515 AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isArtificial,
516 Succ->Reg, Succ->Cost);
518 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
519 SDep *Succ = &ChainSuccs[i];
520 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isArtificial);
522 AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isArtificial,
523 Succ->Reg, Succ->Cost);
527 AddPred(NewSU, LoadSU, false, false);
531 AvailableQueue->addNode(LoadSU);
532 AvailableQueue->addNode(NewSU);
536 if (NewSU->NumSuccsLeft == 0) {
537 NewSU->isAvailable = true;
543 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
544 NewSU = CreateClone(SU);
546 // New SUnit has the exact same predecessors.
547 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
549 if (!I->isArtificial) {
550 AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
551 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
554 // Only copy scheduled successors. Cut them from old node's successor
555 // list and move them over.
556 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
557 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
561 if (I->Dep->isScheduled) {
562 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
563 AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
564 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
567 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
568 SUnit *Succ = DelDeps[i].first;
569 bool isCtrl = DelDeps[i].second;
570 RemovePred(Succ, SU, isCtrl, false);
573 AvailableQueue->updateNode(SU);
574 AvailableQueue->addNode(NewSU);
580 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
581 /// and move all scheduled successors of the given SUnit to the last copy.
582 void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
583 const TargetRegisterClass *DestRC,
584 const TargetRegisterClass *SrcRC,
585 SmallVector<SUnit*, 2> &Copies) {
586 SUnit *CopyFromSU = CreateNewSUnit(NULL);
587 CopyFromSU->CopySrcRC = SrcRC;
588 CopyFromSU->CopyDstRC = DestRC;
589 CopyFromSU->Depth = SU->Depth;
590 CopyFromSU->Height = SU->Height;
592 SUnit *CopyToSU = CreateNewSUnit(NULL);
593 CopyToSU->CopySrcRC = DestRC;
594 CopyToSU->CopyDstRC = SrcRC;
596 // Only copy scheduled successors. Cut them from old node's successor
597 // list and move them over.
598 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
599 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
603 if (I->Dep->isScheduled) {
604 CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
605 AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
606 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
609 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
610 SUnit *Succ = DelDeps[i].first;
611 bool isCtrl = DelDeps[i].second;
612 RemovePred(Succ, SU, isCtrl, false);
615 AddPred(CopyFromSU, SU, false, false, Reg, -1);
616 AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
618 AvailableQueue->updateNode(SU);
619 AvailableQueue->addNode(CopyFromSU);
620 AvailableQueue->addNode(CopyToSU);
621 Copies.push_back(CopyFromSU);
622 Copies.push_back(CopyToSU);
627 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
628 /// definition of the specified node.
629 /// FIXME: Move to SelectionDAG?
630 static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
631 const TargetInstrInfo *TII) {
632 const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
633 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
634 unsigned NumRes = TID.getNumDefs();
635 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
640 return N->getValueType(NumRes);
643 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
644 /// scheduling of the given node to satisfy live physical register dependencies.
645 /// If the specific node is the last one that's available to schedule, do
646 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
647 bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
648 SmallVector<unsigned, 4> &LRegs){
649 if (NumLiveRegs == 0)
652 SmallSet<unsigned, 4> RegAdded;
653 // If this node would clobber any "live" register, then it's not ready.
654 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
657 unsigned Reg = I->Reg;
658 if (LiveRegDefs[Reg] && LiveRegDefs[Reg] != I->Dep) {
659 if (RegAdded.insert(Reg))
660 LRegs.push_back(Reg);
662 for (const unsigned *Alias = TRI->getAliasSet(Reg);
664 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != I->Dep) {
665 if (RegAdded.insert(*Alias))
666 LRegs.push_back(*Alias);
671 for (SDNode *Node = SU->getNode(); Node; Node = Node->getFlaggedNode()) {
672 if (!Node->isMachineOpcode())
674 const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
675 if (!TID.ImplicitDefs)
677 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
678 if (LiveRegDefs[*Reg] && LiveRegDefs[*Reg] != SU) {
679 if (RegAdded.insert(*Reg))
680 LRegs.push_back(*Reg);
682 for (const unsigned *Alias = TRI->getAliasSet(*Reg);
684 if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != SU) {
685 if (RegAdded.insert(*Alias))
686 LRegs.push_back(*Alias);
690 return !LRegs.empty();
694 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
696 void ScheduleDAGRRList::ListScheduleBottomUp() {
697 unsigned CurCycle = 0;
698 // Add root to Available queue.
699 if (!SUnits.empty()) {
700 SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
701 assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
702 RootSU->isAvailable = true;
703 AvailableQueue->push(RootSU);
706 // While Available queue is not empty, grab the node with the highest
707 // priority. If it is not ready put it back. Schedule the node.
708 SmallVector<SUnit*, 4> NotReady;
709 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
710 Sequence.reserve(SUnits.size());
711 while (!AvailableQueue->empty()) {
712 bool Delayed = false;
714 SUnit *CurSU = AvailableQueue->pop();
716 SmallVector<unsigned, 4> LRegs;
717 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
720 LRegsMap.insert(std::make_pair(CurSU, LRegs));
722 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
723 NotReady.push_back(CurSU);
724 CurSU = AvailableQueue->pop();
727 // All candidates are delayed due to live physical reg dependencies.
728 // Try backtracking, code duplication, or inserting cross class copies
730 if (Delayed && !CurSU) {
731 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
732 SUnit *TrySU = NotReady[i];
733 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
735 // Try unscheduling up to the point where it's safe to schedule
737 unsigned LiveCycle = CurCycle;
738 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
739 unsigned Reg = LRegs[j];
740 unsigned LCycle = LiveRegCycles[Reg];
741 LiveCycle = std::min(LiveCycle, LCycle);
743 SUnit *OldSU = Sequence[LiveCycle];
744 if (!WillCreateCycle(TrySU, OldSU)) {
745 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
746 // Force the current node to be scheduled before the node that
747 // requires the physical reg dep.
748 if (OldSU->isAvailable) {
749 OldSU->isAvailable = false;
750 AvailableQueue->remove(OldSU);
752 AddPred(TrySU, OldSU, true, true);
753 // If one or more successors has been unscheduled, then the current
754 // node is no longer avaialable. Schedule a successor that's now
755 // available instead.
756 if (!TrySU->isAvailable)
757 CurSU = AvailableQueue->pop();
760 TrySU->isPending = false;
761 NotReady.erase(NotReady.begin()+i);
768 // Can't backtrack. Try duplicating the nodes that produces these
769 // "expensive to copy" values to break the dependency. In case even
770 // that doesn't work, insert cross class copies.
771 SUnit *TrySU = NotReady[0];
772 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
773 assert(LRegs.size() == 1 && "Can't handle this yet!");
774 unsigned Reg = LRegs[0];
775 SUnit *LRDef = LiveRegDefs[Reg];
776 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
778 // Issue expensive cross register class copies.
779 MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
780 const TargetRegisterClass *RC =
781 TRI->getPhysicalRegisterRegClass(Reg, VT);
782 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
784 assert(false && "Don't know how to copy this physical register!");
787 SmallVector<SUnit*, 2> Copies;
788 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
789 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
790 << " to SU #" << Copies.front()->NodeNum << "\n";
791 AddPred(TrySU, Copies.front(), true, true);
792 NewDef = Copies.back();
795 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
796 << " to SU #" << TrySU->NodeNum << "\n";
797 LiveRegDefs[Reg] = NewDef;
798 AddPred(NewDef, TrySU, true, true);
799 TrySU->isAvailable = false;
804 assert(false && "Unable to resolve live physical register dependencies!");
809 // Add the nodes that aren't ready back onto the available list.
810 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
811 NotReady[i]->isPending = false;
812 // May no longer be available due to backtracking.
813 if (NotReady[i]->isAvailable)
814 AvailableQueue->push(NotReady[i]);
819 ScheduleNodeBottomUp(CurSU, CurCycle);
823 // Reverse the order if it is bottom up.
824 std::reverse(Sequence.begin(), Sequence.end());
827 VerifySchedule(isBottomUp);
831 //===----------------------------------------------------------------------===//
832 // Top-Down Scheduling
833 //===----------------------------------------------------------------------===//
835 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
836 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
837 void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain) {
838 --SuccSU->NumPredsLeft;
841 if (SuccSU->NumPredsLeft < 0) {
842 cerr << "*** Scheduling failed! ***\n";
844 cerr << " has been released too many times!\n";
849 if (SuccSU->NumPredsLeft == 0) {
850 SuccSU->isAvailable = true;
851 AvailableQueue->push(SuccSU);
855 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
856 /// count of its successors. If a successor pending count is zero, add it to
857 /// the Available queue.
858 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
859 DOUT << "*** Scheduling [" << CurCycle << "]: ";
860 DEBUG(SU->dump(this));
862 SU->Cycle = CurCycle;
863 Sequence.push_back(SU);
865 // Top down: release successors
866 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
868 ReleaseSucc(SU, I->Dep, I->isCtrl);
870 SU->isScheduled = true;
871 AvailableQueue->ScheduledNode(SU);
874 /// ListScheduleTopDown - The main loop of list scheduling for top-down
876 void ScheduleDAGRRList::ListScheduleTopDown() {
877 unsigned CurCycle = 0;
879 // All leaves to Available queue.
880 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
881 // It is available if it has no predecessors.
882 if (SUnits[i].Preds.empty()) {
883 AvailableQueue->push(&SUnits[i]);
884 SUnits[i].isAvailable = true;
888 // While Available queue is not empty, grab the node with the highest
889 // priority. If it is not ready put it back. Schedule the node.
890 Sequence.reserve(SUnits.size());
891 while (!AvailableQueue->empty()) {
892 SUnit *CurSU = AvailableQueue->pop();
895 ScheduleNodeTopDown(CurSU, CurCycle);
900 VerifySchedule(isBottomUp);
905 //===----------------------------------------------------------------------===//
906 // RegReductionPriorityQueue Implementation
907 //===----------------------------------------------------------------------===//
909 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
910 // to reduce register pressure.
914 class RegReductionPriorityQueue;
916 /// Sorting functions for the Available queue.
917 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
918 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
919 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
920 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
922 bool operator()(const SUnit* left, const SUnit* right) const;
925 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
926 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
927 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
928 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
930 bool operator()(const SUnit* left, const SUnit* right) const;
932 } // end anonymous namespace
934 static inline bool isCopyFromLiveIn(const SUnit *SU) {
935 SDNode *N = SU->getNode();
936 return N && N->getOpcode() == ISD::CopyFromReg &&
937 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
940 /// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
941 /// Smaller number is the higher priority.
943 CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
944 unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
945 if (SethiUllmanNumber != 0)
946 return SethiUllmanNumber;
949 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
951 if (I->isCtrl) continue; // ignore chain preds
952 SUnit *PredSU = I->Dep;
953 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
954 if (PredSethiUllman > SethiUllmanNumber) {
955 SethiUllmanNumber = PredSethiUllman;
957 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
961 SethiUllmanNumber += Extra;
963 if (SethiUllmanNumber == 0)
964 SethiUllmanNumber = 1;
966 return SethiUllmanNumber;
971 class VISIBILITY_HIDDEN RegReductionPriorityQueue
972 : public SchedulingPriorityQueue {
973 PriorityQueue<SUnit*, std::vector<SUnit*>, SF> Queue;
974 unsigned currentQueueId;
977 // SUnits - The SUnits for the current graph.
978 std::vector<SUnit> *SUnits;
980 const TargetInstrInfo *TII;
981 const TargetRegisterInfo *TRI;
982 ScheduleDAGRRList *scheduleDAG;
984 // SethiUllmanNumbers - The SethiUllman number for each node.
985 std::vector<unsigned> SethiUllmanNumbers;
988 RegReductionPriorityQueue(const TargetInstrInfo *tii,
989 const TargetRegisterInfo *tri) :
990 Queue(SF(this)), currentQueueId(0),
991 TII(tii), TRI(tri), scheduleDAG(NULL) {}
993 void initNodes(std::vector<SUnit> &sunits) {
995 // Add pseudo dependency edges for two-address nodes.
996 AddPseudoTwoAddrDeps();
997 // Calculate node priorities.
998 CalculateSethiUllmanNumbers();
1001 void addNode(const SUnit *SU) {
1002 unsigned SUSize = SethiUllmanNumbers.size();
1003 if (SUnits->size() > SUSize)
1004 SethiUllmanNumbers.resize(SUSize*2, 0);
1005 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1008 void updateNode(const SUnit *SU) {
1009 SethiUllmanNumbers[SU->NodeNum] = 0;
1010 CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1013 void releaseState() {
1015 SethiUllmanNumbers.clear();
1018 unsigned getNodePriority(const SUnit *SU) const {
1019 assert(SU->NodeNum < SethiUllmanNumbers.size());
1020 unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1021 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1022 // CopyFromReg should be close to its def because it restricts
1023 // allocation choices. But if it is a livein then perhaps we want it
1024 // closer to its uses so it can be coalesced.
1026 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1027 // CopyToReg should be close to its uses to facilitate coalescing and
1030 else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1031 Opc == TargetInstrInfo::INSERT_SUBREG)
1032 // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1033 // facilitate coalescing.
1035 else if (SU->NumSuccs == 0)
1036 // If SU does not have a use, i.e. it doesn't produce a value that would
1037 // be consumed (e.g. store), then it terminates a chain of computation.
1038 // Give it a large SethiUllman number so it will be scheduled right
1039 // before its predecessors that it doesn't lengthen their live ranges.
1041 else if (SU->NumPreds == 0)
1042 // If SU does not have a def, schedule it close to its uses because it
1043 // does not lengthen any live ranges.
1046 return SethiUllmanNumbers[SU->NodeNum];
1049 unsigned size() const { return Queue.size(); }
1051 bool empty() const { return Queue.empty(); }
1053 void push(SUnit *U) {
1054 assert(!U->NodeQueueId && "Node in the queue already");
1055 U->NodeQueueId = ++currentQueueId;
1059 void push_all(const std::vector<SUnit *> &Nodes) {
1060 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1065 if (empty()) return NULL;
1066 SUnit *V = Queue.top();
1072 void remove(SUnit *SU) {
1073 assert(!Queue.empty() && "Queue is empty!");
1074 assert(SU->NodeQueueId != 0 && "Not in queue!");
1075 Queue.erase_one(SU);
1076 SU->NodeQueueId = 0;
1079 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1080 scheduleDAG = scheduleDag;
1084 bool canClobber(const SUnit *SU, const SUnit *Op);
1085 void AddPseudoTwoAddrDeps();
1086 void CalculateSethiUllmanNumbers();
1089 typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1090 BURegReductionPriorityQueue;
1092 typedef RegReductionPriorityQueue<td_ls_rr_sort>
1093 TDRegReductionPriorityQueue;
1096 /// closestSucc - Returns the scheduled cycle of the successor which is
1097 /// closet to the current cycle.
1098 static unsigned closestSucc(const SUnit *SU) {
1099 unsigned MaxCycle = 0;
1100 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1102 unsigned Cycle = I->Dep->Cycle;
1103 // If there are bunch of CopyToRegs stacked up, they should be considered
1104 // to be at the same position.
1105 if (I->Dep->getNode() && I->Dep->getNode()->getOpcode() == ISD::CopyToReg)
1106 Cycle = closestSucc(I->Dep)+1;
1107 if (Cycle > MaxCycle)
1113 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1114 /// for scratch registers. Live-in operands and live-out results don't count
1115 /// since they are "fixed".
1116 static unsigned calcMaxScratches(const SUnit *SU) {
1117 unsigned Scratches = 0;
1118 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1120 if (I->isCtrl) continue; // ignore chain preds
1121 if (!I->Dep->getNode() || I->Dep->getNode()->getOpcode() != ISD::CopyFromReg)
1124 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1126 if (I->isCtrl) continue; // ignore chain succs
1127 if (!I->Dep->getNode() || I->Dep->getNode()->getOpcode() != ISD::CopyToReg)
1134 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1135 unsigned LPriority = SPQ->getNodePriority(left);
1136 unsigned RPriority = SPQ->getNodePriority(right);
1137 if (LPriority != RPriority)
1138 return LPriority > RPriority;
1140 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1145 // and the following instructions are both ready.
1149 // Then schedule t2 = op first.
1156 // This creates more short live intervals.
1157 unsigned LDist = closestSucc(left);
1158 unsigned RDist = closestSucc(right);
1160 return LDist < RDist;
1162 // Intuitively, it's good to push down instructions whose results are
1163 // liveout so their long live ranges won't conflict with other values
1164 // which are needed inside the BB. Further prioritize liveout instructions
1165 // by the number of operands which are calculated within the BB.
1166 unsigned LScratch = calcMaxScratches(left);
1167 unsigned RScratch = calcMaxScratches(right);
1168 if (LScratch != RScratch)
1169 return LScratch > RScratch;
1171 if (left->Height != right->Height)
1172 return left->Height > right->Height;
1174 if (left->Depth != right->Depth)
1175 return left->Depth < right->Depth;
1177 assert(left->NodeQueueId && right->NodeQueueId &&
1178 "NodeQueueId cannot be zero");
1179 return (left->NodeQueueId > right->NodeQueueId);
1184 RegReductionPriorityQueue<SF>::canClobber(const SUnit *SU, const SUnit *Op) {
1185 if (SU->isTwoAddress) {
1186 unsigned Opc = SU->getNode()->getMachineOpcode();
1187 const TargetInstrDesc &TID = TII->get(Opc);
1188 unsigned NumRes = TID.getNumDefs();
1189 unsigned NumOps = TID.getNumOperands() - NumRes;
1190 for (unsigned i = 0; i != NumOps; ++i) {
1191 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1192 SDNode *DU = SU->getNode()->getOperand(i).getNode();
1193 if (DU->getNodeId() != -1 &&
1194 Op->OrigNode == &(*SUnits)[DU->getNodeId()])
1203 /// hasCopyToRegUse - Return true if SU has a value successor that is a
1205 static bool hasCopyToRegUse(const SUnit *SU) {
1206 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1208 if (I->isCtrl) continue;
1209 const SUnit *SuccSU = I->Dep;
1210 if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg)
1216 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1217 /// physical register defs.
1218 static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
1219 const TargetInstrInfo *TII,
1220 const TargetRegisterInfo *TRI) {
1221 SDNode *N = SuccSU->getNode();
1222 unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1223 const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
1224 assert(ImpDefs && "Caller should check hasPhysRegDefs");
1225 const unsigned *SUImpDefs =
1226 TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
1229 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1230 MVT VT = N->getValueType(i);
1231 if (VT == MVT::Flag || VT == MVT::Other)
1233 if (!N->hasAnyUseOfValue(i))
1235 unsigned Reg = ImpDefs[i - NumDefs];
1236 for (;*SUImpDefs; ++SUImpDefs) {
1237 unsigned SUReg = *SUImpDefs;
1238 if (TRI->regsOverlap(Reg, SUReg))
1245 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1246 /// it as a def&use operand. Add a pseudo control edge from it to the other
1247 /// node (if it won't create a cycle) so the two-address one will be scheduled
1248 /// first (lower in the schedule). If both nodes are two-address, favor the
1249 /// one that has a CopyToReg use (more likely to be a loop induction update).
1250 /// If both are two-address, but one is commutable while the other is not
1251 /// commutable, favor the one that's not commutable.
1253 void RegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
1254 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1255 SUnit *SU = &(*SUnits)[i];
1256 if (!SU->isTwoAddress)
1259 SDNode *Node = SU->getNode();
1260 if (!Node || !Node->isMachineOpcode() || SU->getNode()->getFlaggedNode())
1263 unsigned Opc = Node->getMachineOpcode();
1264 const TargetInstrDesc &TID = TII->get(Opc);
1265 unsigned NumRes = TID.getNumDefs();
1266 unsigned NumOps = TID.getNumOperands() - NumRes;
1267 for (unsigned j = 0; j != NumOps; ++j) {
1268 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
1270 SDNode *DU = SU->getNode()->getOperand(j).getNode();
1271 if (DU->getNodeId() == -1)
1273 const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
1274 if (!DUSU) continue;
1275 for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
1276 E = DUSU->Succs.end(); I != E; ++I) {
1277 if (I->isCtrl) continue;
1278 SUnit *SuccSU = I->Dep;
1281 // Be conservative. Ignore if nodes aren't at roughly the same
1282 // depth and height.
1283 if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1285 if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
1287 // Don't constrain nodes with physical register defs if the
1288 // predecessor can clobber them.
1289 if (SuccSU->hasPhysRegDefs) {
1290 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1293 // Don't constraint extract_subreg / insert_subreg these may be
1294 // coalesced away. We don't them close to their uses.
1295 unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
1296 if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1297 SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1299 if ((!canClobber(SuccSU, DUSU) ||
1300 (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1301 (!SU->isCommutable && SuccSU->isCommutable)) &&
1302 !scheduleDAG->IsReachable(SuccSU, SU)) {
1303 DOUT << "Adding an edge from SU # " << SU->NodeNum
1304 << " to SU #" << SuccSU->NodeNum << "\n";
1305 scheduleDAG->AddPred(SU, SuccSU, true, true);
1312 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1313 /// scheduling units.
1315 void RegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
1316 SethiUllmanNumbers.assign(SUnits->size(), 0);
1318 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1319 CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1322 /// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
1323 /// predecessors of the successors of the SUnit SU. Stop when the provided
1324 /// limit is exceeded.
1325 static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
1328 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1330 const SUnit *SuccSU = I->Dep;
1331 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1332 EE = SuccSU->Preds.end(); II != EE; ++II) {
1333 SUnit *PredSU = II->Dep;
1334 if (!PredSU->isScheduled)
1344 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1345 unsigned LPriority = SPQ->getNodePriority(left);
1346 unsigned RPriority = SPQ->getNodePriority(right);
1347 bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
1348 bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
1349 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1350 bool RIsFloater = RIsTarget && right->NumPreds == 0;
1351 unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1352 unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
1354 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1356 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1363 if (left->NumSuccs == 1)
1365 if (right->NumSuccs == 1)
1368 if (LPriority+LBonus != RPriority+RBonus)
1369 return LPriority+LBonus < RPriority+RBonus;
1371 if (left->Depth != right->Depth)
1372 return left->Depth < right->Depth;
1374 if (left->NumSuccsLeft != right->NumSuccsLeft)
1375 return left->NumSuccsLeft > right->NumSuccsLeft;
1377 assert(left->NodeQueueId && right->NodeQueueId &&
1378 "NodeQueueId cannot be zero");
1379 return (left->NodeQueueId > right->NodeQueueId);
1382 //===----------------------------------------------------------------------===//
1383 // Public Constructor Functions
1384 //===----------------------------------------------------------------------===//
1386 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1388 const TargetMachine *TM,
1389 MachineBasicBlock *BB,
1391 const TargetInstrInfo *TII = TM->getInstrInfo();
1392 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
1394 BURegReductionPriorityQueue *PQ = new BURegReductionPriorityQueue(TII, TRI);
1396 ScheduleDAGRRList *SD =
1397 new ScheduleDAGRRList(DAG, BB, *TM, true, PQ);
1398 PQ->setScheduleDAG(SD);
1402 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1404 const TargetMachine *TM,
1405 MachineBasicBlock *BB,
1407 const TargetInstrInfo *TII = TM->getInstrInfo();
1408 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
1410 TDRegReductionPriorityQueue *PQ = new TDRegReductionPriorityQueue(TII, TRI);
1412 ScheduleDAGRRList *SD = new ScheduleDAGRRList(DAG, BB, *TM, false, PQ);
1413 PQ->setScheduleDAG(SD);