1 //===----- ScheduleDAGList.cpp - Reg pressure reduction list scheduler ----===//
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 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/ScheduleDAG.h"
20 #include "llvm/CodeGen/SchedulerRegistry.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/Target/MRegisterInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/CommandLine.h"
36 STATISTIC(NumBacktracks, "Number of times scheduler backtraced");
37 STATISTIC(NumUnfolds, "Number of nodes unfolded");
38 STATISTIC(NumDups, "Number of duplicated nodes");
39 STATISTIC(NumCCCopies, "Number of cross class copies");
41 static RegisterScheduler
42 burrListDAGScheduler("list-burr",
43 " Bottom-up register reduction list scheduling",
44 createBURRListDAGScheduler);
45 static RegisterScheduler
46 tdrListrDAGScheduler("list-tdrr",
47 " Top-down register reduction list scheduling",
48 createTDRRListDAGScheduler);
51 //===----------------------------------------------------------------------===//
52 /// ScheduleDAGRRList - The actual register reduction list scheduler
53 /// implementation. This supports both top-down and bottom-up scheduling.
55 class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAG {
57 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
61 /// AvailableQueue - The priority queue to use for the available SUnits.
63 SchedulingPriorityQueue *AvailableQueue;
65 /// LiveRegs / 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.
68 SmallSet<unsigned, 4> LiveRegs;
69 std::vector<SUnit*> LiveRegDefs;
70 std::vector<unsigned> LiveRegCycles;
73 ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
74 const TargetMachine &tm, bool isbottomup,
75 SchedulingPriorityQueue *availqueue)
76 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
77 AvailableQueue(availqueue) {
80 ~ScheduleDAGRRList() {
81 delete AvailableQueue;
87 void ReleasePred(SUnit*, bool, unsigned);
88 void ReleaseSucc(SUnit*, bool isChain, unsigned);
89 void CapturePred(SUnit*, SUnit*, bool);
90 void ScheduleNodeBottomUp(SUnit*, unsigned);
91 void ScheduleNodeTopDown(SUnit*, unsigned);
92 void UnscheduleNodeBottomUp(SUnit*);
93 void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
94 SUnit *CopyAndMoveSuccessors(SUnit*);
95 void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
96 const TargetRegisterClass*,
97 const TargetRegisterClass*,
98 SmallVector<SUnit*, 2>&);
99 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
100 void ListScheduleTopDown();
101 void ListScheduleBottomUp();
102 void CommuteNodesToReducePressure();
104 } // end anonymous namespace
107 /// Schedule - Schedule the DAG using list scheduling.
108 void ScheduleDAGRRList::Schedule() {
109 DOUT << "********** List Scheduling **********\n";
111 LiveRegDefs.resize(MRI->getNumRegs(), NULL);
112 LiveRegCycles.resize(MRI->getNumRegs(), 0);
114 // Build scheduling units.
117 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
118 SUnits[su].dumpAll(&DAG));
122 AvailableQueue->initNodes(SUnitMap, SUnits);
124 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
126 ListScheduleBottomUp();
128 ListScheduleTopDown();
130 AvailableQueue->releaseState();
132 CommuteNodesToReducePressure();
134 DOUT << "*** Final schedule ***\n";
135 DEBUG(dumpSchedule());
138 // Emit in scheduled order
142 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
143 /// it is not the last use of its first operand, add it to the CommuteSet if
144 /// possible. It will be commuted when it is translated to a MI.
145 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
146 SmallPtrSet<SUnit*, 4> OperandSeen;
147 for (unsigned i = Sequence.size()-1; i != 0; --i) { // Ignore first node.
148 SUnit *SU = Sequence[i];
149 if (!SU || !SU->Node) continue;
150 if (SU->isCommutable) {
151 unsigned Opc = SU->Node->getTargetOpcode();
152 unsigned NumRes = TII->getNumDefs(Opc);
153 unsigned NumOps = CountOperands(SU->Node);
154 for (unsigned j = 0; j != NumOps; ++j) {
155 if (TII->getOperandConstraint(Opc, j+NumRes, TOI::TIED_TO) == -1)
158 SDNode *OpN = SU->Node->getOperand(j).Val;
159 SUnit *OpSU = SUnitMap[OpN][SU->InstanceNo];
160 if (OpSU && OperandSeen.count(OpSU) == 1) {
161 // Ok, so SU is not the last use of OpSU, but SU is two-address so
162 // it will clobber OpSU. Try to commute SU if no other source operands
164 bool DoCommute = true;
165 for (unsigned k = 0; k < NumOps; ++k) {
167 OpN = SU->Node->getOperand(k).Val;
168 OpSU = SUnitMap[OpN][SU->InstanceNo];
169 if (OpSU && OperandSeen.count(OpSU) == 1) {
176 CommuteSet.insert(SU->Node);
179 // Only look at the first use&def node for now.
184 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
187 OperandSeen.insert(I->Dep);
192 //===----------------------------------------------------------------------===//
193 // Bottom-Up Scheduling
194 //===----------------------------------------------------------------------===//
196 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
197 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
198 void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
200 // FIXME: the distance between two nodes is not always == the predecessor's
201 // latency. For example, the reader can very well read the register written
202 // by the predecessor later than the issue cycle. It also depends on the
203 // interrupt model (drain vs. freeze).
204 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
206 --PredSU->NumSuccsLeft;
209 if (PredSU->NumSuccsLeft < 0) {
210 cerr << "*** List scheduling failed! ***\n";
212 cerr << " has been released too many times!\n";
217 if (PredSU->NumSuccsLeft == 0) {
218 // EntryToken has to go last! Special case it here.
219 if (!PredSU->Node || PredSU->Node->getOpcode() != ISD::EntryToken) {
220 PredSU->isAvailable = true;
221 AvailableQueue->push(PredSU);
226 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
227 /// count of its predecessors. If a predecessor pending count is zero, add it to
228 /// the Available queue.
229 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
230 DOUT << "*** Scheduling [" << CurCycle << "]: ";
231 DEBUG(SU->dump(&DAG));
232 SU->Cycle = CurCycle;
234 AvailableQueue->ScheduledNode(SU);
236 // Bottom up: release predecessors
237 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
239 ReleasePred(I->Dep, I->isCtrl, CurCycle);
241 // This is a physical register dependency and it's impossible or
242 // expensive to copy the register. Make sure nothing that can
243 // clobber the register is scheduled between the predecessor and
245 if (LiveRegs.insert(I->Reg)) {
246 LiveRegDefs[I->Reg] = I->Dep;
247 LiveRegCycles[I->Reg] = CurCycle;
252 // Release all the implicit physical register defs that are live.
253 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
256 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
257 LiveRegs.erase(I->Reg);
258 assert(LiveRegDefs[I->Reg] == SU &&
259 "Physical register dependency violated?");
260 LiveRegDefs[I->Reg] = NULL;
261 LiveRegCycles[I->Reg] = 0;
266 SU->isScheduled = true;
269 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
270 /// unscheduled, incrcease the succ left count of its predecessors. Remove
271 /// them from AvailableQueue if necessary.
272 void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
273 PredSU->CycleBound = 0;
274 for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
278 PredSU->CycleBound = std::max(PredSU->CycleBound,
279 I->Dep->Cycle + PredSU->Latency);
282 if (PredSU->isAvailable) {
283 PredSU->isAvailable = false;
284 if (!PredSU->isPending)
285 AvailableQueue->remove(PredSU);
288 ++PredSU->NumSuccsLeft;
291 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
292 /// its predecessor states to reflect the change.
293 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
294 DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
295 DEBUG(SU->dump(&DAG));
297 AvailableQueue->UnscheduledNode(SU);
299 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
301 CapturePred(I->Dep, SU, I->isCtrl);
302 if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg]) {
303 LiveRegs.erase(I->Reg);
304 assert(LiveRegDefs[I->Reg] == I->Dep &&
305 "Physical register dependency violated?");
306 LiveRegDefs[I->Reg] = NULL;
307 LiveRegCycles[I->Reg] = 0;
311 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
314 if (LiveRegs.insert(I->Reg)) {
315 assert(!LiveRegDefs[I->Reg] &&
316 "Physical register dependency violated?");
317 LiveRegDefs[I->Reg] = SU;
319 if (I->Dep->Cycle < LiveRegCycles[I->Reg])
320 LiveRegCycles[I->Reg] = I->Dep->Cycle;
325 SU->isScheduled = false;
326 SU->isAvailable = true;
327 AvailableQueue->push(SU);
330 // FIXME: This is probably too slow!
331 static void isReachable(SUnit *SU, SUnit *TargetSU,
332 SmallPtrSet<SUnit*, 32> &Visited, bool &Reached) {
334 if (SU == TargetSU) {
338 if (!Visited.insert(SU)) return;
340 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); I != E;
342 isReachable(I->Dep, TargetSU, Visited, Reached);
345 static bool isReachable(SUnit *SU, SUnit *TargetSU) {
346 SmallPtrSet<SUnit*, 32> Visited;
347 bool Reached = false;
348 isReachable(SU, TargetSU, Visited, Reached);
352 /// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
354 static bool WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
355 if (isReachable(TargetSU, SU))
357 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
359 if (I->Cost < 0 && isReachable(TargetSU, I->Dep))
364 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
365 /// BTCycle in order to schedule a specific node. Returns the last unscheduled
366 /// SUnit. Also returns if a successor is unscheduled in the process.
367 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
368 unsigned &CurCycle) {
370 while (CurCycle > BtCycle) {
371 OldSU = Sequence.back();
373 if (SU->isSucc(OldSU))
374 // Don't try to remove SU from AvailableQueue.
375 SU->isAvailable = false;
376 UnscheduleNodeBottomUp(OldSU);
381 if (SU->isSucc(OldSU)) {
382 assert(false && "Something is wrong!");
389 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
390 /// successors to the newly created node.
391 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
392 if (SU->FlaggedNodes.size())
395 SDNode *N = SU->Node;
400 bool TryUnfold = false;
401 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
402 MVT::ValueType VT = N->getValueType(i);
405 else if (VT == MVT::Other)
408 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
409 const SDOperand &Op = N->getOperand(i);
410 MVT::ValueType VT = Op.Val->getValueType(Op.ResNo);
416 SmallVector<SDNode*, 4> NewNodes;
417 if (!MRI->unfoldMemoryOperand(DAG, N, NewNodes))
420 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
421 assert(NewNodes.size() == 2 && "Expected a load folding node!");
424 SDNode *LoadNode = NewNodes[0];
425 std::vector<SDNode*> Deleted;
426 unsigned NumVals = N->getNumValues();
427 unsigned OldNumVals = SU->Node->getNumValues();
428 for (unsigned i = 0; i != NumVals; ++i)
429 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, i),
430 SDOperand(N, i), Deleted);
431 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, OldNumVals-1),
432 SDOperand(LoadNode, 1), Deleted);
434 SUnit *LoadSU = NewSUnit(LoadNode);
435 SUnit *NewSU = NewSUnit(N);
436 SUnitMap[LoadNode].push_back(LoadSU);
437 SUnitMap[N].push_back(NewSU);
438 const TargetInstrDescriptor *TID = &TII->get(LoadNode->getTargetOpcode());
439 for (unsigned i = 0; i != TID->numOperands; ++i) {
440 if (TID->getOperandConstraint(i, TOI::TIED_TO) != -1) {
441 LoadSU->isTwoAddress = true;
445 if (TID->Flags & M_COMMUTABLE)
446 LoadSU->isCommutable = true;
448 TID = &TII->get(N->getTargetOpcode());
449 for (unsigned i = 0; i != TID->numOperands; ++i) {
450 if (TID->getOperandConstraint(i, TOI::TIED_TO) != -1) {
451 NewSU->isTwoAddress = true;
455 if (TID->Flags & M_COMMUTABLE)
456 NewSU->isCommutable = true;
458 // FIXME: Calculate height / depth and propagate the changes?
459 LoadSU->Depth = NewSU->Depth = SU->Depth;
460 LoadSU->Height = NewSU->Height = SU->Height;
461 ComputeLatency(LoadSU);
462 ComputeLatency(NewSU);
464 SUnit *ChainPred = NULL;
465 SmallVector<SDep, 4> ChainSuccs;
466 SmallVector<SDep, 4> LoadPreds;
467 SmallVector<SDep, 4> NodePreds;
468 SmallVector<SDep, 4> NodeSuccs;
469 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
473 else if (I->Dep->Node && I->Dep->Node->isOperand(LoadNode))
474 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
476 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
478 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
481 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
482 I->isCtrl, I->isSpecial));
484 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
485 I->isCtrl, I->isSpecial));
488 SU->removePred(ChainPred, true, false);
489 LoadSU->addPred(ChainPred, true, false);
490 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
491 SDep *Pred = &LoadPreds[i];
492 SU->removePred(Pred->Dep, Pred->isCtrl, Pred->isSpecial);
493 LoadSU->addPred(Pred->Dep, Pred->isCtrl, Pred->isSpecial,
494 Pred->Reg, Pred->Cost);
496 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
497 SDep *Pred = &NodePreds[i];
498 SU->removePred(Pred->Dep, Pred->isCtrl, Pred->isSpecial);
499 NewSU->addPred(Pred->Dep, Pred->isCtrl, Pred->isSpecial,
500 Pred->Reg, Pred->Cost);
502 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
503 SDep *Succ = &NodeSuccs[i];
504 Succ->Dep->removePred(SU, Succ->isCtrl, Succ->isSpecial);
505 Succ->Dep->addPred(NewSU, Succ->isCtrl, Succ->isSpecial,
506 Succ->Reg, Succ->Cost);
508 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
509 SDep *Succ = &ChainSuccs[i];
510 Succ->Dep->removePred(SU, Succ->isCtrl, Succ->isSpecial);
511 Succ->Dep->addPred(LoadSU, Succ->isCtrl, Succ->isSpecial,
512 Succ->Reg, Succ->Cost);
514 NewSU->addPred(LoadSU, false, false);
516 AvailableQueue->addNode(LoadSU);
517 AvailableQueue->addNode(NewSU);
521 if (NewSU->NumSuccsLeft == 0) {
522 NewSU->isAvailable = true;
528 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
531 // New SUnit has the exact same predecessors.
532 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
535 NewSU->addPred(I->Dep, I->isCtrl, false, I->Reg, I->Cost);
536 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
539 // Only copy scheduled successors. Cut them from old node's successor
540 // list and move them over.
541 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
542 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
546 if (I->Dep->isScheduled) {
547 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
548 I->Dep->addPred(NewSU, I->isCtrl, false, I->Reg, I->Cost);
549 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
552 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
553 SUnit *Succ = DelDeps[i].first;
554 bool isCtrl = DelDeps[i].second;
555 Succ->removePred(SU, isCtrl, false);
558 AvailableQueue->updateNode(SU);
559 AvailableQueue->addNode(NewSU);
565 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
566 /// and move all scheduled successors of the given SUnit to the last copy.
567 void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
568 const TargetRegisterClass *DestRC,
569 const TargetRegisterClass *SrcRC,
570 SmallVector<SUnit*, 2> &Copies) {
571 SUnit *CopyFromSU = NewSUnit(NULL);
572 CopyFromSU->CopySrcRC = SrcRC;
573 CopyFromSU->CopyDstRC = DestRC;
574 CopyFromSU->Depth = SU->Depth;
575 CopyFromSU->Height = SU->Height;
577 SUnit *CopyToSU = NewSUnit(NULL);
578 CopyToSU->CopySrcRC = DestRC;
579 CopyToSU->CopyDstRC = SrcRC;
581 // Only copy scheduled successors. Cut them from old node's successor
582 // list and move them over.
583 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
584 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
588 if (I->Dep->isScheduled) {
589 CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
590 I->Dep->addPred(CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
591 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
594 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
595 SUnit *Succ = DelDeps[i].first;
596 bool isCtrl = DelDeps[i].second;
597 Succ->removePred(SU, isCtrl, false);
600 CopyFromSU->addPred(SU, false, false, Reg, -1);
601 CopyToSU->addPred(CopyFromSU, false, false, Reg, 1);
603 AvailableQueue->updateNode(SU);
604 AvailableQueue->addNode(CopyFromSU);
605 AvailableQueue->addNode(CopyToSU);
606 Copies.push_back(CopyFromSU);
607 Copies.push_back(CopyToSU);
612 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
613 /// definition of the specified node.
614 /// FIXME: Move to SelectionDAG?
615 static MVT::ValueType getPhysicalRegisterVT(SDNode *N, unsigned Reg,
616 const TargetInstrInfo *TII) {
617 const TargetInstrDescriptor &TID = TII->get(N->getTargetOpcode());
618 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
619 unsigned NumRes = TID.numDefs;
620 for (const unsigned *ImpDef = TID.ImplicitDefs; *ImpDef; ++ImpDef) {
625 return N->getValueType(NumRes);
628 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
629 /// scheduling of the given node to satisfy live physical register dependencies.
630 /// If the specific node is the last one that's available to schedule, do
631 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
632 bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
633 SmallVector<unsigned, 4> &LRegs){
634 if (LiveRegs.empty())
637 SmallSet<unsigned, 4> RegAdded;
638 // If this node would clobber any "live" register, then it's not ready.
639 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
642 unsigned Reg = I->Reg;
643 if (LiveRegs.count(Reg) && LiveRegDefs[Reg] != I->Dep) {
644 if (RegAdded.insert(Reg))
645 LRegs.push_back(Reg);
647 for (const unsigned *Alias = MRI->getAliasSet(Reg);
649 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != I->Dep) {
650 if (RegAdded.insert(*Alias))
651 LRegs.push_back(*Alias);
656 for (unsigned i = 0, e = SU->FlaggedNodes.size()+1; i != e; ++i) {
657 SDNode *Node = (i == 0) ? SU->Node : SU->FlaggedNodes[i-1];
658 if (!Node || !Node->isTargetOpcode())
660 const TargetInstrDescriptor &TID = TII->get(Node->getTargetOpcode());
661 if (!TID.ImplicitDefs)
663 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
664 if (LiveRegs.count(*Reg) && LiveRegDefs[*Reg] != SU) {
665 if (RegAdded.insert(*Reg))
666 LRegs.push_back(*Reg);
668 for (const unsigned *Alias = MRI->getAliasSet(*Reg);
670 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != SU) {
671 if (RegAdded.insert(*Alias))
672 LRegs.push_back(*Alias);
676 return !LRegs.empty();
680 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
682 void ScheduleDAGRRList::ListScheduleBottomUp() {
683 unsigned CurCycle = 0;
684 // Add root to Available queue.
685 SUnit *RootSU = SUnitMap[DAG.getRoot().Val].front();
686 RootSU->isAvailable = true;
687 AvailableQueue->push(RootSU);
689 // While Available queue is not empty, grab the node with the highest
690 // priority. If it is not ready put it back. Schedule the node.
691 SmallVector<SUnit*, 4> NotReady;
692 while (!AvailableQueue->empty()) {
693 bool Delayed = false;
694 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
695 SUnit *CurSU = AvailableQueue->pop();
697 if (CurSU->CycleBound <= CurCycle) {
698 SmallVector<unsigned, 4> LRegs;
699 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
702 LRegsMap.insert(std::make_pair(CurSU, LRegs));
705 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
706 NotReady.push_back(CurSU);
707 CurSU = AvailableQueue->pop();
710 // All candidates are delayed due to live physical reg dependencies.
711 // Try backtracking, code duplication, or inserting cross class copies
713 if (Delayed && !CurSU) {
714 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
715 SUnit *TrySU = NotReady[i];
716 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
718 // Try unscheduling up to the point where it's safe to schedule
720 unsigned LiveCycle = CurCycle;
721 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
722 unsigned Reg = LRegs[j];
723 unsigned LCycle = LiveRegCycles[Reg];
724 LiveCycle = std::min(LiveCycle, LCycle);
726 SUnit *OldSU = Sequence[LiveCycle];
727 if (!WillCreateCycle(TrySU, OldSU)) {
728 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
729 // Force the current node to be scheduled before the node that
730 // requires the physical reg dep.
731 if (OldSU->isAvailable) {
732 OldSU->isAvailable = false;
733 AvailableQueue->remove(OldSU);
735 TrySU->addPred(OldSU, true, true);
736 // If one or more successors has been unscheduled, then the current
737 // node is no longer avaialable. Schedule a successor that's now
738 // available instead.
739 if (!TrySU->isAvailable)
740 CurSU = AvailableQueue->pop();
743 TrySU->isPending = false;
744 NotReady.erase(NotReady.begin()+i);
751 // Can't backtrace. Try duplicating the nodes that produces these
752 // "expensive to copy" values to break the dependency. In case even
753 // that doesn't work, insert cross class copies.
754 SUnit *TrySU = NotReady[0];
755 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
756 assert(LRegs.size() == 1 && "Can't handle this yet!");
757 unsigned Reg = LRegs[0];
758 SUnit *LRDef = LiveRegDefs[Reg];
759 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
761 // Issue expensive cross register class copies.
762 MVT::ValueType VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
763 const TargetRegisterClass *RC =
764 MRI->getPhysicalRegisterRegClass(VT, Reg);
765 const TargetRegisterClass *DestRC = MRI->getCrossCopyRegClass(RC);
767 assert(false && "Don't know how to copy this physical register!");
770 SmallVector<SUnit*, 2> Copies;
771 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
772 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
773 << " to SU #" << Copies.front()->NodeNum << "\n";
774 TrySU->addPred(Copies.front(), true, true);
775 NewDef = Copies.back();
778 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
779 << " to SU #" << TrySU->NodeNum << "\n";
780 LiveRegDefs[Reg] = NewDef;
781 NewDef->addPred(TrySU, true, true);
782 TrySU->isAvailable = false;
787 assert(false && "Unable to resolve live physical register dependencies!");
792 // Add the nodes that aren't ready back onto the available list.
793 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
794 NotReady[i]->isPending = false;
795 // May no longer be available due to backtracking.
796 if (NotReady[i]->isAvailable)
797 AvailableQueue->push(NotReady[i]);
802 Sequence.push_back(0);
804 ScheduleNodeBottomUp(CurSU, CurCycle);
805 Sequence.push_back(CurSU);
810 // Add entry node last
811 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
812 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
813 Sequence.push_back(Entry);
816 // Reverse the order if it is bottom up.
817 std::reverse(Sequence.begin(), Sequence.end());
821 // Verify that all SUnits were scheduled.
822 bool AnyNotSched = false;
823 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
824 if (SUnits[i].NumSuccsLeft != 0) {
826 cerr << "*** List scheduling failed! ***\n";
827 SUnits[i].dump(&DAG);
828 cerr << "has not been scheduled!\n";
832 assert(!AnyNotSched);
836 //===----------------------------------------------------------------------===//
837 // Top-Down Scheduling
838 //===----------------------------------------------------------------------===//
840 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
841 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
842 void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
844 // FIXME: the distance between two nodes is not always == the predecessor's
845 // latency. For example, the reader can very well read the register written
846 // by the predecessor later than the issue cycle. It also depends on the
847 // interrupt model (drain vs. freeze).
848 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
850 --SuccSU->NumPredsLeft;
853 if (SuccSU->NumPredsLeft < 0) {
854 cerr << "*** List scheduling failed! ***\n";
856 cerr << " has been released too many times!\n";
861 if (SuccSU->NumPredsLeft == 0) {
862 SuccSU->isAvailable = true;
863 AvailableQueue->push(SuccSU);
868 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
869 /// count of its successors. If a successor pending count is zero, add it to
870 /// the Available queue.
871 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
872 DOUT << "*** Scheduling [" << CurCycle << "]: ";
873 DEBUG(SU->dump(&DAG));
874 SU->Cycle = CurCycle;
876 AvailableQueue->ScheduledNode(SU);
878 // Top down: release successors
879 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
881 ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
882 SU->isScheduled = true;
885 /// ListScheduleTopDown - The main loop of list scheduling for top-down
887 void ScheduleDAGRRList::ListScheduleTopDown() {
888 unsigned CurCycle = 0;
889 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
891 // All leaves to Available queue.
892 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
893 // It is available if it has no predecessors.
894 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
895 AvailableQueue->push(&SUnits[i]);
896 SUnits[i].isAvailable = true;
900 // Emit the entry node first.
901 ScheduleNodeTopDown(Entry, CurCycle);
902 Sequence.push_back(Entry);
905 // While Available queue is not empty, grab the node with the highest
906 // priority. If it is not ready put it back. Schedule the node.
907 std::vector<SUnit*> NotReady;
908 while (!AvailableQueue->empty()) {
909 SUnit *CurSU = AvailableQueue->pop();
910 while (CurSU && CurSU->CycleBound > CurCycle) {
911 NotReady.push_back(CurSU);
912 CurSU = AvailableQueue->pop();
915 // Add the nodes that aren't ready back onto the available list.
916 AvailableQueue->push_all(NotReady);
920 Sequence.push_back(0);
922 ScheduleNodeTopDown(CurSU, CurCycle);
923 Sequence.push_back(CurSU);
930 // Verify that all SUnits were scheduled.
931 bool AnyNotSched = false;
932 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
933 if (!SUnits[i].isScheduled) {
935 cerr << "*** List scheduling failed! ***\n";
936 SUnits[i].dump(&DAG);
937 cerr << "has not been scheduled!\n";
941 assert(!AnyNotSched);
947 //===----------------------------------------------------------------------===//
948 // RegReductionPriorityQueue Implementation
949 //===----------------------------------------------------------------------===//
951 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
952 // to reduce register pressure.
956 class RegReductionPriorityQueue;
958 /// Sorting functions for the Available queue.
959 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
960 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
961 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
962 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
964 bool operator()(const SUnit* left, const SUnit* right) const;
967 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
968 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
969 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
970 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
972 bool operator()(const SUnit* left, const SUnit* right) const;
974 } // end anonymous namespace
976 static inline bool isCopyFromLiveIn(const SUnit *SU) {
977 SDNode *N = SU->Node;
978 return N && N->getOpcode() == ISD::CopyFromReg &&
979 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
984 class VISIBILITY_HIDDEN RegReductionPriorityQueue
985 : public SchedulingPriorityQueue {
986 std::priority_queue<SUnit*, std::vector<SUnit*>, SF> Queue;
989 RegReductionPriorityQueue() :
992 virtual void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
993 std::vector<SUnit> &sunits) {}
995 virtual void addNode(const SUnit *SU) {}
997 virtual void updateNode(const SUnit *SU) {}
999 virtual void releaseState() {}
1001 virtual unsigned getNodePriority(const SUnit *SU) const {
1005 unsigned size() const { return Queue.size(); }
1007 bool empty() const { return Queue.empty(); }
1009 void push(SUnit *U) {
1012 void push_all(const std::vector<SUnit *> &Nodes) {
1013 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1014 Queue.push(Nodes[i]);
1018 if (empty()) return NULL;
1019 SUnit *V = Queue.top();
1024 /// remove - This is a really inefficient way to remove a node from a
1025 /// priority queue. We should roll our own heap to make this better or
1027 void remove(SUnit *SU) {
1028 std::vector<SUnit*> Temp;
1030 assert(!Queue.empty() && "Not in queue!");
1031 while (Queue.top() != SU) {
1032 Temp.push_back(Queue.top());
1034 assert(!Queue.empty() && "Not in queue!");
1037 // Remove the node from the PQ.
1040 // Add all the other nodes back.
1041 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
1042 Queue.push(Temp[i]);
1047 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
1048 : public RegReductionPriorityQueue<SF> {
1049 // SUnitMap SDNode to SUnit mapping (n -> n).
1050 DenseMap<SDNode*, std::vector<SUnit*> > *SUnitMap;
1052 // SUnits - The SUnits for the current graph.
1053 const std::vector<SUnit> *SUnits;
1055 // SethiUllmanNumbers - The SethiUllman number for each node.
1056 std::vector<unsigned> SethiUllmanNumbers;
1058 const TargetInstrInfo *TII;
1060 explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii)
1063 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
1064 std::vector<SUnit> &sunits) {
1067 // Add pseudo dependency edges for two-address nodes.
1068 AddPseudoTwoAddrDeps();
1069 // Calculate node priorities.
1070 CalculateSethiUllmanNumbers();
1073 void addNode(const SUnit *SU) {
1074 SethiUllmanNumbers.resize(SUnits->size(), 0);
1075 CalcNodeSethiUllmanNumber(SU);
1078 void updateNode(const SUnit *SU) {
1079 SethiUllmanNumbers[SU->NodeNum] = 0;
1080 CalcNodeSethiUllmanNumber(SU);
1083 void releaseState() {
1085 SethiUllmanNumbers.clear();
1088 unsigned getNodePriority(const SUnit *SU) const {
1089 assert(SU->NodeNum < SethiUllmanNumbers.size());
1090 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1091 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1092 // CopyFromReg should be close to its def because it restricts
1093 // allocation choices. But if it is a livein then perhaps we want it
1094 // closer to its uses so it can be coalesced.
1096 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1097 // CopyToReg should be close to its uses to facilitate coalescing and
1100 else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1101 Opc == TargetInstrInfo::INSERT_SUBREG)
1102 // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1103 // facilitate coalescing.
1105 else if (SU->NumSuccs == 0)
1106 // If SU does not have a use, i.e. it doesn't produce a value that would
1107 // be consumed (e.g. store), then it terminates a chain of computation.
1108 // Give it a large SethiUllman number so it will be scheduled right
1109 // before its predecessors that it doesn't lengthen their live ranges.
1111 else if (SU->NumPreds == 0)
1112 // If SU does not have a def, schedule it close to its uses because it
1113 // does not lengthen any live ranges.
1116 return SethiUllmanNumbers[SU->NodeNum];
1120 bool canClobber(SUnit *SU, SUnit *Op);
1121 void AddPseudoTwoAddrDeps();
1122 void CalculateSethiUllmanNumbers();
1123 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
1128 class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
1129 : public RegReductionPriorityQueue<SF> {
1130 // SUnitMap SDNode to SUnit mapping (n -> n).
1131 DenseMap<SDNode*, std::vector<SUnit*> > *SUnitMap;
1133 // SUnits - The SUnits for the current graph.
1134 const std::vector<SUnit> *SUnits;
1136 // SethiUllmanNumbers - The SethiUllman number for each node.
1137 std::vector<unsigned> SethiUllmanNumbers;
1140 TDRegReductionPriorityQueue() {}
1142 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
1143 std::vector<SUnit> &sunits) {
1146 // Calculate node priorities.
1147 CalculateSethiUllmanNumbers();
1150 void addNode(const SUnit *SU) {
1151 SethiUllmanNumbers.resize(SUnits->size(), 0);
1152 CalcNodeSethiUllmanNumber(SU);
1155 void updateNode(const SUnit *SU) {
1156 SethiUllmanNumbers[SU->NodeNum] = 0;
1157 CalcNodeSethiUllmanNumber(SU);
1160 void releaseState() {
1162 SethiUllmanNumbers.clear();
1165 unsigned getNodePriority(const SUnit *SU) const {
1166 assert(SU->NodeNum < SethiUllmanNumbers.size());
1167 return SethiUllmanNumbers[SU->NodeNum];
1171 void CalculateSethiUllmanNumbers();
1172 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
1176 /// closestSucc - Returns the scheduled cycle of the successor which is
1177 /// closet to the current cycle.
1178 static unsigned closestSucc(const SUnit *SU) {
1179 unsigned MaxCycle = 0;
1180 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1182 unsigned Cycle = I->Dep->Cycle;
1183 // If there are bunch of CopyToRegs stacked up, they should be considered
1184 // to be at the same position.
1185 if (I->Dep->Node && I->Dep->Node->getOpcode() == ISD::CopyToReg)
1186 Cycle = closestSucc(I->Dep)+1;
1187 if (Cycle > MaxCycle)
1194 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1195 // There used to be a special tie breaker here that looked for
1196 // two-address instructions and preferred the instruction with a
1197 // def&use operand. The special case triggered diagnostics when
1198 // _GLIBCXX_DEBUG was enabled because it broke the strict weak
1199 // ordering that priority_queue requires. It didn't help much anyway
1200 // because AddPseudoTwoAddrDeps already covers many of the cases
1201 // where it would have applied. In addition, it's counter-intuitive
1202 // that a tie breaker would be the first thing attempted. There's a
1203 // "real" tie breaker below that is the operation of last resort.
1204 // The fact that the "special tie breaker" would trigger when there
1205 // wasn't otherwise a tie is what broke the strict weak ordering
1208 unsigned LPriority = SPQ->getNodePriority(left);
1209 unsigned RPriority = SPQ->getNodePriority(right);
1210 if (LPriority > RPriority)
1212 else if (LPriority == RPriority) {
1213 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1218 // and the following instructions are both ready.
1222 // Then schedule t2 = op first.
1229 // This creates more short live intervals.
1230 unsigned LDist = closestSucc(left);
1231 unsigned RDist = closestSucc(right);
1234 else if (LDist == RDist) {
1235 if (left->Height > right->Height)
1237 else if (left->Height == right->Height)
1238 if (left->Depth < right->Depth)
1240 else if (left->Depth == right->Depth)
1241 if (left->CycleBound > right->CycleBound)
1249 bool BURegReductionPriorityQueue<SF>::canClobber(SUnit *SU, SUnit *Op) {
1250 if (SU->isTwoAddress) {
1251 unsigned Opc = SU->Node->getTargetOpcode();
1252 unsigned NumRes = TII->getNumDefs(Opc);
1253 unsigned NumOps = ScheduleDAG::CountOperands(SU->Node);
1254 for (unsigned i = 0; i != NumOps; ++i) {
1255 if (TII->getOperandConstraint(Opc, i+NumRes, TOI::TIED_TO) != -1) {
1256 SDNode *DU = SU->Node->getOperand(i).Val;
1257 if (Op == (*SUnitMap)[DU][SU->InstanceNo])
1266 /// hasCopyToRegUse - Return true if SU has a value successor that is a
1268 static bool hasCopyToRegUse(SUnit *SU) {
1269 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1271 if (I->isCtrl) continue;
1272 SUnit *SuccSU = I->Dep;
1273 if (SuccSU->Node && SuccSU->Node->getOpcode() == ISD::CopyToReg)
1279 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1280 /// it as a def&use operand. Add a pseudo control edge from it to the other
1281 /// node (if it won't create a cycle) so the two-address one will be scheduled
1282 /// first (lower in the schedule). If both nodes are two-address, favor the
1283 /// one that has a CopyToReg use (more likely to be a loop induction update).
1284 /// If both are two-address, but one is commutable while the other is not
1285 /// commutable, favor the one that's not commutable.
1287 void BURegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
1288 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1289 SUnit *SU = (SUnit *)&((*SUnits)[i]);
1290 if (!SU->isTwoAddress)
1293 SDNode *Node = SU->Node;
1294 if (!Node || !Node->isTargetOpcode() || SU->FlaggedNodes.size() > 0)
1297 unsigned Opc = Node->getTargetOpcode();
1298 unsigned NumRes = TII->getNumDefs(Opc);
1299 unsigned NumOps = ScheduleDAG::CountOperands(Node);
1300 for (unsigned j = 0; j != NumOps; ++j) {
1301 if (TII->getOperandConstraint(Opc, j+NumRes, TOI::TIED_TO) != -1) {
1302 SDNode *DU = SU->Node->getOperand(j).Val;
1303 SUnit *DUSU = (*SUnitMap)[DU][SU->InstanceNo];
1304 if (!DUSU) continue;
1305 for (SUnit::succ_iterator I = DUSU->Succs.begin(),E = DUSU->Succs.end();
1307 if (I->isCtrl) continue;
1308 SUnit *SuccSU = I->Dep;
1309 // Don't constrain nodes with implicit defs. It can create cycles
1310 // plus it may increase register pressures.
1311 if (SuccSU == SU || SuccSU->hasPhysRegDefs)
1313 // Be conservative. Ignore if nodes aren't at the same depth.
1314 if (SuccSU->Depth != SU->Depth)
1316 if (!SuccSU->Node || !SuccSU->Node->isTargetOpcode())
1318 // Don't constraint extract_subreg / insert_subreg these may be
1319 // coalesced away. We don't them close to their uses.
1320 unsigned SuccOpc = SuccSU->Node->getTargetOpcode();
1321 if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1322 SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1324 if ((!canClobber(SuccSU, DUSU) ||
1325 (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1326 (!SU->isCommutable && SuccSU->isCommutable)) &&
1327 !isReachable(SuccSU, SU)) {
1328 DOUT << "Adding an edge from SU # " << SU->NodeNum
1329 << " to SU #" << SuccSU->NodeNum << "\n";
1330 SU->addPred(SuccSU, true, true);
1338 /// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
1339 /// Smaller number is the higher priority.
1341 unsigned BURegReductionPriorityQueue<SF>::
1342 CalcNodeSethiUllmanNumber(const SUnit *SU) {
1343 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
1344 if (SethiUllmanNumber != 0)
1345 return SethiUllmanNumber;
1348 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1350 if (I->isCtrl) continue; // ignore chain preds
1351 SUnit *PredSU = I->Dep;
1352 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
1353 if (PredSethiUllman > SethiUllmanNumber) {
1354 SethiUllmanNumber = PredSethiUllman;
1356 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1360 SethiUllmanNumber += Extra;
1362 if (SethiUllmanNumber == 0)
1363 SethiUllmanNumber = 1;
1365 return SethiUllmanNumber;
1368 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1369 /// scheduling units.
1371 void BURegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
1372 SethiUllmanNumbers.assign(SUnits->size(), 0);
1374 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1375 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
1378 static unsigned SumOfUnscheduledPredsOfSuccs(const SUnit *SU) {
1380 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1382 SUnit *SuccSU = I->Dep;
1383 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1384 EE = SuccSU->Preds.end(); II != EE; ++II) {
1385 SUnit *PredSU = II->Dep;
1386 if (!PredSU->isScheduled)
1396 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1397 unsigned LPriority = SPQ->getNodePriority(left);
1398 unsigned RPriority = SPQ->getNodePriority(right);
1399 bool LIsTarget = left->Node && left->Node->isTargetOpcode();
1400 bool RIsTarget = right->Node && right->Node->isTargetOpcode();
1401 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1402 bool RIsFloater = RIsTarget && right->NumPreds == 0;
1403 unsigned LBonus = (SumOfUnscheduledPredsOfSuccs(left) == 1) ? 2 : 0;
1404 unsigned RBonus = (SumOfUnscheduledPredsOfSuccs(right) == 1) ? 2 : 0;
1406 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1408 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1411 // Special tie breaker: if two nodes share a operand, the one that use it
1412 // as a def&use operand is preferred.
1413 if (LIsTarget && RIsTarget) {
1414 if (left->isTwoAddress && !right->isTwoAddress) {
1415 SDNode *DUNode = left->Node->getOperand(0).Val;
1416 if (DUNode->isOperand(right->Node))
1419 if (!left->isTwoAddress && right->isTwoAddress) {
1420 SDNode *DUNode = right->Node->getOperand(0).Val;
1421 if (DUNode->isOperand(left->Node))
1429 if (left->NumSuccs == 1)
1431 if (right->NumSuccs == 1)
1434 if (LPriority+LBonus < RPriority+RBonus)
1436 else if (LPriority == RPriority)
1437 if (left->Depth < right->Depth)
1439 else if (left->Depth == right->Depth)
1440 if (left->NumSuccsLeft > right->NumSuccsLeft)
1442 else if (left->NumSuccsLeft == right->NumSuccsLeft)
1443 if (left->CycleBound > right->CycleBound)
1448 /// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
1449 /// Smaller number is the higher priority.
1451 unsigned TDRegReductionPriorityQueue<SF>::
1452 CalcNodeSethiUllmanNumber(const SUnit *SU) {
1453 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
1454 if (SethiUllmanNumber != 0)
1455 return SethiUllmanNumber;
1457 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1458 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1459 SethiUllmanNumber = 0xffff;
1460 else if (SU->NumSuccsLeft == 0)
1461 // If SU does not have a use, i.e. it doesn't produce a value that would
1462 // be consumed (e.g. store), then it terminates a chain of computation.
1463 // Give it a small SethiUllman number so it will be scheduled right before
1464 // its predecessors that it doesn't lengthen their live ranges.
1465 SethiUllmanNumber = 0;
1466 else if (SU->NumPredsLeft == 0 &&
1467 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
1468 SethiUllmanNumber = 0xffff;
1471 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1473 if (I->isCtrl) continue; // ignore chain preds
1474 SUnit *PredSU = I->Dep;
1475 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
1476 if (PredSethiUllman > SethiUllmanNumber) {
1477 SethiUllmanNumber = PredSethiUllman;
1479 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1483 SethiUllmanNumber += Extra;
1486 return SethiUllmanNumber;
1489 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1490 /// scheduling units.
1492 void TDRegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
1493 SethiUllmanNumbers.assign(SUnits->size(), 0);
1495 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1496 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
1499 //===----------------------------------------------------------------------===//
1500 // Public Constructor Functions
1501 //===----------------------------------------------------------------------===//
1503 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1505 MachineBasicBlock *BB) {
1506 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
1507 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true,
1508 new BURegReductionPriorityQueue<bu_ls_rr_sort>(TII));
1511 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1513 MachineBasicBlock *BB) {
1514 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false,
1515 new TDRegReductionPriorityQueue<td_ls_rr_sort>());