1 //===----- ScheduleDAGList.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/ScheduleDAG.h"
20 #include "llvm/CodeGen/SchedulerRegistry.h"
21 #include "llvm/Target/MRegisterInfo.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/SmallPtrSet.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Support/CommandLine.h"
35 STATISTIC(NumBacktracks, "Number of times scheduler backtraced");
36 STATISTIC(NumUnfolds, "Number of nodes unfolded");
37 STATISTIC(NumDups, "Number of duplicated nodes");
38 STATISTIC(NumCCCopies, "Number of cross class copies");
40 static RegisterScheduler
41 burrListDAGScheduler("list-burr",
42 " Bottom-up register reduction list scheduling",
43 createBURRListDAGScheduler);
44 static RegisterScheduler
45 tdrListrDAGScheduler("list-tdrr",
46 " Top-down register reduction list scheduling",
47 createTDRRListDAGScheduler);
50 //===----------------------------------------------------------------------===//
51 /// ScheduleDAGRRList - The actual register reduction list scheduler
52 /// implementation. This supports both top-down and bottom-up scheduling.
54 class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAG {
56 /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
60 /// AvailableQueue - The priority queue to use for the available SUnits.
62 SchedulingPriorityQueue *AvailableQueue;
64 /// LiveRegs / LiveRegDefs - A set of physical registers and their definition
65 /// that are "live". These nodes must be scheduled before any other nodes that
66 /// modifies the registers can be scheduled.
67 SmallSet<unsigned, 4> LiveRegs;
68 std::vector<SUnit*> LiveRegDefs;
69 std::vector<unsigned> LiveRegCycles;
72 ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
73 const TargetMachine &tm, bool isbottomup,
74 SchedulingPriorityQueue *availqueue)
75 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
76 AvailableQueue(availqueue) {
79 ~ScheduleDAGRRList() {
80 delete AvailableQueue;
86 void ReleasePred(SUnit*, bool, unsigned);
87 void ReleaseSucc(SUnit*, bool isChain, unsigned);
88 void CapturePred(SUnit*, SUnit*, bool);
89 void ScheduleNodeBottomUp(SUnit*, unsigned);
90 void ScheduleNodeTopDown(SUnit*, unsigned);
91 void UnscheduleNodeBottomUp(SUnit*);
92 void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
93 SUnit *CopyAndMoveSuccessors(SUnit*);
94 void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
95 const TargetRegisterClass*,
96 const TargetRegisterClass*,
97 SmallVector<SUnit*, 2>&);
98 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
99 void ListScheduleTopDown();
100 void ListScheduleBottomUp();
101 void CommuteNodesToReducePressure();
103 } // end anonymous namespace
106 /// Schedule - Schedule the DAG using list scheduling.
107 void ScheduleDAGRRList::Schedule() {
108 DOUT << "********** List Scheduling **********\n";
110 LiveRegDefs.resize(MRI->getNumRegs(), NULL);
111 LiveRegCycles.resize(MRI->getNumRegs(), 0);
113 // Build scheduling units.
116 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
117 SUnits[su].dumpAll(&DAG));
121 AvailableQueue->initNodes(SUnitMap, SUnits);
123 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
125 ListScheduleBottomUp();
127 ListScheduleTopDown();
129 AvailableQueue->releaseState();
131 CommuteNodesToReducePressure();
133 DOUT << "*** Final schedule ***\n";
134 DEBUG(dumpSchedule());
137 // Emit in scheduled order
141 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
142 /// it is not the last use of its first operand, add it to the CommuteSet if
143 /// possible. It will be commuted when it is translated to a MI.
144 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
145 SmallPtrSet<SUnit*, 4> OperandSeen;
146 for (unsigned i = Sequence.size()-1; i != 0; --i) { // Ignore first node.
147 SUnit *SU = Sequence[i];
148 if (!SU || !SU->Node) continue;
149 if (SU->isCommutable) {
150 unsigned Opc = SU->Node->getTargetOpcode();
151 const TargetInstrDesc &TID = TII->get(Opc);
152 unsigned NumRes = TID.getNumDefs();
153 unsigned NumOps = CountOperands(SU->Node);
154 for (unsigned j = 0; j != NumOps; ++j) {
155 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
158 SDNode *OpN = SU->Node->getOperand(j).Val;
159 SUnit *OpSU = isPassiveNode(OpN) ? NULL : 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 = isPassiveNode(OpN) ? NULL : 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 (!TII->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 unsigned NumVals = N->getNumValues();
426 unsigned OldNumVals = SU->Node->getNumValues();
427 for (unsigned i = 0; i != NumVals; ++i)
428 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, i), SDOperand(N, i));
429 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, OldNumVals-1),
430 SDOperand(LoadNode, 1));
432 SUnit *NewSU = NewSUnit(N);
433 SUnitMap[N].push_back(NewSU);
434 const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
435 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
436 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
437 NewSU->isTwoAddress = true;
441 if (TID.isCommutable())
442 NewSU->isCommutable = true;
443 // FIXME: Calculate height / depth and propagate the changes?
444 NewSU->Depth = SU->Depth;
445 NewSU->Height = SU->Height;
446 ComputeLatency(NewSU);
448 // LoadNode may already exist. This can happen when there is another
449 // load from the same location and producing the same type of value
450 // but it has different alignment or volatileness.
451 bool isNewLoad = true;
453 DenseMap<SDNode*, std::vector<SUnit*> >::iterator SMI =
454 SUnitMap.find(LoadNode);
455 if (SMI != SUnitMap.end()) {
456 LoadSU = SMI->second.front();
459 LoadSU = NewSUnit(LoadNode);
460 SUnitMap[LoadNode].push_back(LoadSU);
462 LoadSU->Depth = SU->Depth;
463 LoadSU->Height = SU->Height;
464 ComputeLatency(LoadSU);
467 SUnit *ChainPred = NULL;
468 SmallVector<SDep, 4> ChainSuccs;
469 SmallVector<SDep, 4> LoadPreds;
470 SmallVector<SDep, 4> NodePreds;
471 SmallVector<SDep, 4> NodeSuccs;
472 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
476 else if (I->Dep->Node && I->Dep->Node->isOperand(LoadNode))
477 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
479 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
481 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
484 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
485 I->isCtrl, I->isSpecial));
487 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
488 I->isCtrl, I->isSpecial));
491 SU->removePred(ChainPred, true, false);
493 LoadSU->addPred(ChainPred, true, false);
494 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
495 SDep *Pred = &LoadPreds[i];
496 SU->removePred(Pred->Dep, Pred->isCtrl, Pred->isSpecial);
498 LoadSU->addPred(Pred->Dep, Pred->isCtrl, Pred->isSpecial,
499 Pred->Reg, Pred->Cost);
501 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
502 SDep *Pred = &NodePreds[i];
503 SU->removePred(Pred->Dep, Pred->isCtrl, Pred->isSpecial);
504 NewSU->addPred(Pred->Dep, Pred->isCtrl, Pred->isSpecial,
505 Pred->Reg, Pred->Cost);
507 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
508 SDep *Succ = &NodeSuccs[i];
509 Succ->Dep->removePred(SU, Succ->isCtrl, Succ->isSpecial);
510 Succ->Dep->addPred(NewSU, Succ->isCtrl, Succ->isSpecial,
511 Succ->Reg, Succ->Cost);
513 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
514 SDep *Succ = &ChainSuccs[i];
515 Succ->Dep->removePred(SU, Succ->isCtrl, Succ->isSpecial);
517 Succ->Dep->addPred(LoadSU, Succ->isCtrl, Succ->isSpecial,
518 Succ->Reg, Succ->Cost);
521 NewSU->addPred(LoadSU, false, false);
524 AvailableQueue->addNode(LoadSU);
525 AvailableQueue->addNode(NewSU);
529 if (NewSU->NumSuccsLeft == 0) {
530 NewSU->isAvailable = true;
536 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
539 // New SUnit has the exact same predecessors.
540 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
543 NewSU->addPred(I->Dep, I->isCtrl, false, I->Reg, I->Cost);
544 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
547 // Only copy scheduled successors. Cut them from old node's successor
548 // list and move them over.
549 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
550 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
554 if (I->Dep->isScheduled) {
555 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
556 I->Dep->addPred(NewSU, I->isCtrl, false, I->Reg, I->Cost);
557 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
560 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
561 SUnit *Succ = DelDeps[i].first;
562 bool isCtrl = DelDeps[i].second;
563 Succ->removePred(SU, isCtrl, false);
566 AvailableQueue->updateNode(SU);
567 AvailableQueue->addNode(NewSU);
573 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
574 /// and move all scheduled successors of the given SUnit to the last copy.
575 void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
576 const TargetRegisterClass *DestRC,
577 const TargetRegisterClass *SrcRC,
578 SmallVector<SUnit*, 2> &Copies) {
579 SUnit *CopyFromSU = NewSUnit(NULL);
580 CopyFromSU->CopySrcRC = SrcRC;
581 CopyFromSU->CopyDstRC = DestRC;
582 CopyFromSU->Depth = SU->Depth;
583 CopyFromSU->Height = SU->Height;
585 SUnit *CopyToSU = NewSUnit(NULL);
586 CopyToSU->CopySrcRC = DestRC;
587 CopyToSU->CopyDstRC = SrcRC;
589 // Only copy scheduled successors. Cut them from old node's successor
590 // list and move them over.
591 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
592 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
596 if (I->Dep->isScheduled) {
597 CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
598 I->Dep->addPred(CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
599 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
602 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
603 SUnit *Succ = DelDeps[i].first;
604 bool isCtrl = DelDeps[i].second;
605 Succ->removePred(SU, isCtrl, false);
608 CopyFromSU->addPred(SU, false, false, Reg, -1);
609 CopyToSU->addPred(CopyFromSU, false, false, Reg, 1);
611 AvailableQueue->updateNode(SU);
612 AvailableQueue->addNode(CopyFromSU);
613 AvailableQueue->addNode(CopyToSU);
614 Copies.push_back(CopyFromSU);
615 Copies.push_back(CopyToSU);
620 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
621 /// definition of the specified node.
622 /// FIXME: Move to SelectionDAG?
623 static MVT::ValueType getPhysicalRegisterVT(SDNode *N, unsigned Reg,
624 const TargetInstrInfo *TII) {
625 const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
626 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
627 unsigned NumRes = TID.getNumDefs();
628 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
633 return N->getValueType(NumRes);
636 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
637 /// scheduling of the given node to satisfy live physical register dependencies.
638 /// If the specific node is the last one that's available to schedule, do
639 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
640 bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
641 SmallVector<unsigned, 4> &LRegs){
642 if (LiveRegs.empty())
645 SmallSet<unsigned, 4> RegAdded;
646 // If this node would clobber any "live" register, then it's not ready.
647 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
650 unsigned Reg = I->Reg;
651 if (LiveRegs.count(Reg) && LiveRegDefs[Reg] != I->Dep) {
652 if (RegAdded.insert(Reg))
653 LRegs.push_back(Reg);
655 for (const unsigned *Alias = MRI->getAliasSet(Reg);
657 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != I->Dep) {
658 if (RegAdded.insert(*Alias))
659 LRegs.push_back(*Alias);
664 for (unsigned i = 0, e = SU->FlaggedNodes.size()+1; i != e; ++i) {
665 SDNode *Node = (i == 0) ? SU->Node : SU->FlaggedNodes[i-1];
666 if (!Node || !Node->isTargetOpcode())
668 const TargetInstrDesc &TID = TII->get(Node->getTargetOpcode());
669 if (!TID.ImplicitDefs)
671 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
672 if (LiveRegs.count(*Reg) && LiveRegDefs[*Reg] != SU) {
673 if (RegAdded.insert(*Reg))
674 LRegs.push_back(*Reg);
676 for (const unsigned *Alias = MRI->getAliasSet(*Reg);
678 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != SU) {
679 if (RegAdded.insert(*Alias))
680 LRegs.push_back(*Alias);
684 return !LRegs.empty();
688 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
690 void ScheduleDAGRRList::ListScheduleBottomUp() {
691 unsigned CurCycle = 0;
692 // Add root to Available queue.
693 SUnit *RootSU = SUnitMap[DAG.getRoot().Val].front();
694 RootSU->isAvailable = true;
695 AvailableQueue->push(RootSU);
697 // While Available queue is not empty, grab the node with the highest
698 // priority. If it is not ready put it back. Schedule the node.
699 SmallVector<SUnit*, 4> NotReady;
700 while (!AvailableQueue->empty()) {
701 bool Delayed = false;
702 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
703 SUnit *CurSU = AvailableQueue->pop();
705 if (CurSU->CycleBound <= CurCycle) {
706 SmallVector<unsigned, 4> LRegs;
707 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
710 LRegsMap.insert(std::make_pair(CurSU, LRegs));
713 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
714 NotReady.push_back(CurSU);
715 CurSU = AvailableQueue->pop();
718 // All candidates are delayed due to live physical reg dependencies.
719 // Try backtracking, code duplication, or inserting cross class copies
721 if (Delayed && !CurSU) {
722 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
723 SUnit *TrySU = NotReady[i];
724 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
726 // Try unscheduling up to the point where it's safe to schedule
728 unsigned LiveCycle = CurCycle;
729 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
730 unsigned Reg = LRegs[j];
731 unsigned LCycle = LiveRegCycles[Reg];
732 LiveCycle = std::min(LiveCycle, LCycle);
734 SUnit *OldSU = Sequence[LiveCycle];
735 if (!WillCreateCycle(TrySU, OldSU)) {
736 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
737 // Force the current node to be scheduled before the node that
738 // requires the physical reg dep.
739 if (OldSU->isAvailable) {
740 OldSU->isAvailable = false;
741 AvailableQueue->remove(OldSU);
743 TrySU->addPred(OldSU, true, true);
744 // If one or more successors has been unscheduled, then the current
745 // node is no longer avaialable. Schedule a successor that's now
746 // available instead.
747 if (!TrySU->isAvailable)
748 CurSU = AvailableQueue->pop();
751 TrySU->isPending = false;
752 NotReady.erase(NotReady.begin()+i);
759 // Can't backtrace. Try duplicating the nodes that produces these
760 // "expensive to copy" values to break the dependency. In case even
761 // that doesn't work, insert cross class copies.
762 SUnit *TrySU = NotReady[0];
763 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
764 assert(LRegs.size() == 1 && "Can't handle this yet!");
765 unsigned Reg = LRegs[0];
766 SUnit *LRDef = LiveRegDefs[Reg];
767 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
769 // Issue expensive cross register class copies.
770 MVT::ValueType VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
771 const TargetRegisterClass *RC =
772 MRI->getPhysicalRegisterRegClass(VT, Reg);
773 const TargetRegisterClass *DestRC = MRI->getCrossCopyRegClass(RC);
775 assert(false && "Don't know how to copy this physical register!");
778 SmallVector<SUnit*, 2> Copies;
779 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
780 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
781 << " to SU #" << Copies.front()->NodeNum << "\n";
782 TrySU->addPred(Copies.front(), true, true);
783 NewDef = Copies.back();
786 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
787 << " to SU #" << TrySU->NodeNum << "\n";
788 LiveRegDefs[Reg] = NewDef;
789 NewDef->addPred(TrySU, true, true);
790 TrySU->isAvailable = false;
795 assert(false && "Unable to resolve live physical register dependencies!");
800 // Add the nodes that aren't ready back onto the available list.
801 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
802 NotReady[i]->isPending = false;
803 // May no longer be available due to backtracking.
804 if (NotReady[i]->isAvailable)
805 AvailableQueue->push(NotReady[i]);
810 Sequence.push_back(0);
812 ScheduleNodeBottomUp(CurSU, CurCycle);
813 Sequence.push_back(CurSU);
818 // Add entry node last
819 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
820 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
821 Sequence.push_back(Entry);
824 // Reverse the order if it is bottom up.
825 std::reverse(Sequence.begin(), Sequence.end());
829 // Verify that all SUnits were scheduled.
830 bool AnyNotSched = false;
831 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
832 if (SUnits[i].NumSuccsLeft != 0) {
834 cerr << "*** List scheduling failed! ***\n";
835 SUnits[i].dump(&DAG);
836 cerr << "has not been scheduled!\n";
840 assert(!AnyNotSched);
844 //===----------------------------------------------------------------------===//
845 // Top-Down Scheduling
846 //===----------------------------------------------------------------------===//
848 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
849 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
850 void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
852 // FIXME: the distance between two nodes is not always == the predecessor's
853 // latency. For example, the reader can very well read the register written
854 // by the predecessor later than the issue cycle. It also depends on the
855 // interrupt model (drain vs. freeze).
856 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
858 --SuccSU->NumPredsLeft;
861 if (SuccSU->NumPredsLeft < 0) {
862 cerr << "*** List scheduling failed! ***\n";
864 cerr << " has been released too many times!\n";
869 if (SuccSU->NumPredsLeft == 0) {
870 SuccSU->isAvailable = true;
871 AvailableQueue->push(SuccSU);
876 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
877 /// count of its successors. If a successor pending count is zero, add it to
878 /// the Available queue.
879 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
880 DOUT << "*** Scheduling [" << CurCycle << "]: ";
881 DEBUG(SU->dump(&DAG));
882 SU->Cycle = CurCycle;
884 AvailableQueue->ScheduledNode(SU);
886 // Top down: release successors
887 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
889 ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
890 SU->isScheduled = true;
893 /// ListScheduleTopDown - The main loop of list scheduling for top-down
895 void ScheduleDAGRRList::ListScheduleTopDown() {
896 unsigned CurCycle = 0;
897 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
899 // All leaves to Available queue.
900 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
901 // It is available if it has no predecessors.
902 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
903 AvailableQueue->push(&SUnits[i]);
904 SUnits[i].isAvailable = true;
908 // Emit the entry node first.
909 ScheduleNodeTopDown(Entry, CurCycle);
910 Sequence.push_back(Entry);
913 // While Available queue is not empty, grab the node with the highest
914 // priority. If it is not ready put it back. Schedule the node.
915 std::vector<SUnit*> NotReady;
916 while (!AvailableQueue->empty()) {
917 SUnit *CurSU = AvailableQueue->pop();
918 while (CurSU && CurSU->CycleBound > CurCycle) {
919 NotReady.push_back(CurSU);
920 CurSU = AvailableQueue->pop();
923 // Add the nodes that aren't ready back onto the available list.
924 AvailableQueue->push_all(NotReady);
928 Sequence.push_back(0);
930 ScheduleNodeTopDown(CurSU, CurCycle);
931 Sequence.push_back(CurSU);
938 // Verify that all SUnits were scheduled.
939 bool AnyNotSched = false;
940 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
941 if (!SUnits[i].isScheduled) {
943 cerr << "*** List scheduling failed! ***\n";
944 SUnits[i].dump(&DAG);
945 cerr << "has not been scheduled!\n";
949 assert(!AnyNotSched);
955 //===----------------------------------------------------------------------===//
956 // RegReductionPriorityQueue Implementation
957 //===----------------------------------------------------------------------===//
959 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
960 // to reduce register pressure.
964 class RegReductionPriorityQueue;
966 /// Sorting functions for the Available queue.
967 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
968 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
969 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
970 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
972 bool operator()(const SUnit* left, const SUnit* right) const;
975 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
976 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
977 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
978 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
980 bool operator()(const SUnit* left, const SUnit* right) const;
982 } // end anonymous namespace
984 static inline bool isCopyFromLiveIn(const SUnit *SU) {
985 SDNode *N = SU->Node;
986 return N && N->getOpcode() == ISD::CopyFromReg &&
987 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
992 class VISIBILITY_HIDDEN RegReductionPriorityQueue
993 : public SchedulingPriorityQueue {
994 std::priority_queue<SUnit*, std::vector<SUnit*>, SF> Queue;
997 RegReductionPriorityQueue() :
1000 virtual void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
1001 std::vector<SUnit> &sunits) {}
1003 virtual void addNode(const SUnit *SU) {}
1005 virtual void updateNode(const SUnit *SU) {}
1007 virtual void releaseState() {}
1009 virtual unsigned getNodePriority(const SUnit *SU) const {
1013 unsigned size() const { return Queue.size(); }
1015 bool empty() const { return Queue.empty(); }
1017 void push(SUnit *U) {
1020 void push_all(const std::vector<SUnit *> &Nodes) {
1021 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1022 Queue.push(Nodes[i]);
1026 if (empty()) return NULL;
1027 SUnit *V = Queue.top();
1032 /// remove - This is a really inefficient way to remove a node from a
1033 /// priority queue. We should roll our own heap to make this better or
1035 void remove(SUnit *SU) {
1036 std::vector<SUnit*> Temp;
1038 assert(!Queue.empty() && "Not in queue!");
1039 while (Queue.top() != SU) {
1040 Temp.push_back(Queue.top());
1042 assert(!Queue.empty() && "Not in queue!");
1045 // Remove the node from the PQ.
1048 // Add all the other nodes back.
1049 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
1050 Queue.push(Temp[i]);
1055 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
1056 : public RegReductionPriorityQueue<SF> {
1057 // SUnitMap SDNode to SUnit mapping (n -> n).
1058 DenseMap<SDNode*, std::vector<SUnit*> > *SUnitMap;
1060 // SUnits - The SUnits for the current graph.
1061 const std::vector<SUnit> *SUnits;
1063 // SethiUllmanNumbers - The SethiUllman number for each node.
1064 std::vector<unsigned> SethiUllmanNumbers;
1066 const TargetInstrInfo *TII;
1067 const MRegisterInfo *MRI;
1069 explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii,
1070 const MRegisterInfo *mri)
1071 : TII(tii), MRI(mri) {}
1073 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
1074 std::vector<SUnit> &sunits) {
1077 // Add pseudo dependency edges for two-address nodes.
1078 AddPseudoTwoAddrDeps();
1079 // Calculate node priorities.
1080 CalculateSethiUllmanNumbers();
1083 void addNode(const SUnit *SU) {
1084 SethiUllmanNumbers.resize(SUnits->size(), 0);
1085 CalcNodeSethiUllmanNumber(SU);
1088 void updateNode(const SUnit *SU) {
1089 SethiUllmanNumbers[SU->NodeNum] = 0;
1090 CalcNodeSethiUllmanNumber(SU);
1093 void releaseState() {
1095 SethiUllmanNumbers.clear();
1098 unsigned getNodePriority(const SUnit *SU) const {
1099 assert(SU->NodeNum < SethiUllmanNumbers.size());
1100 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1101 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1102 // CopyFromReg should be close to its def because it restricts
1103 // allocation choices. But if it is a livein then perhaps we want it
1104 // closer to its uses so it can be coalesced.
1106 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1107 // CopyToReg should be close to its uses to facilitate coalescing and
1110 else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1111 Opc == TargetInstrInfo::INSERT_SUBREG)
1112 // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1113 // facilitate coalescing.
1115 else if (SU->NumSuccs == 0)
1116 // If SU does not have a use, i.e. it doesn't produce a value that would
1117 // be consumed (e.g. store), then it terminates a chain of computation.
1118 // Give it a large SethiUllman number so it will be scheduled right
1119 // before its predecessors that it doesn't lengthen their live ranges.
1121 else if (SU->NumPreds == 0)
1122 // If SU does not have a def, schedule it close to its uses because it
1123 // does not lengthen any live ranges.
1126 return SethiUllmanNumbers[SU->NodeNum];
1130 bool canClobber(SUnit *SU, SUnit *Op);
1131 void AddPseudoTwoAddrDeps();
1132 void CalculateSethiUllmanNumbers();
1133 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
1138 class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
1139 : public RegReductionPriorityQueue<SF> {
1140 // SUnitMap SDNode to SUnit mapping (n -> n).
1141 DenseMap<SDNode*, std::vector<SUnit*> > *SUnitMap;
1143 // SUnits - The SUnits for the current graph.
1144 const std::vector<SUnit> *SUnits;
1146 // SethiUllmanNumbers - The SethiUllman number for each node.
1147 std::vector<unsigned> SethiUllmanNumbers;
1150 TDRegReductionPriorityQueue() {}
1152 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
1153 std::vector<SUnit> &sunits) {
1156 // Calculate node priorities.
1157 CalculateSethiUllmanNumbers();
1160 void addNode(const SUnit *SU) {
1161 SethiUllmanNumbers.resize(SUnits->size(), 0);
1162 CalcNodeSethiUllmanNumber(SU);
1165 void updateNode(const SUnit *SU) {
1166 SethiUllmanNumbers[SU->NodeNum] = 0;
1167 CalcNodeSethiUllmanNumber(SU);
1170 void releaseState() {
1172 SethiUllmanNumbers.clear();
1175 unsigned getNodePriority(const SUnit *SU) const {
1176 assert(SU->NodeNum < SethiUllmanNumbers.size());
1177 return SethiUllmanNumbers[SU->NodeNum];
1181 void CalculateSethiUllmanNumbers();
1182 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
1186 /// closestSucc - Returns the scheduled cycle of the successor which is
1187 /// closet to the current cycle.
1188 static unsigned closestSucc(const SUnit *SU) {
1189 unsigned MaxCycle = 0;
1190 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1192 unsigned Cycle = I->Dep->Cycle;
1193 // If there are bunch of CopyToRegs stacked up, they should be considered
1194 // to be at the same position.
1195 if (I->Dep->Node && I->Dep->Node->getOpcode() == ISD::CopyToReg)
1196 Cycle = closestSucc(I->Dep)+1;
1197 if (Cycle > MaxCycle)
1203 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1204 /// for scratch registers. Live-in operands and live-out results don't count
1205 /// since they are "fixed".
1206 static unsigned calcMaxScratches(const SUnit *SU) {
1207 unsigned Scratches = 0;
1208 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1210 if (I->isCtrl) continue; // ignore chain preds
1211 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyFromReg)
1214 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1216 if (I->isCtrl) continue; // ignore chain succs
1217 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyToReg)
1224 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1225 // There used to be a special tie breaker here that looked for
1226 // two-address instructions and preferred the instruction with a
1227 // def&use operand. The special case triggered diagnostics when
1228 // _GLIBCXX_DEBUG was enabled because it broke the strict weak
1229 // ordering that priority_queue requires. It didn't help much anyway
1230 // because AddPseudoTwoAddrDeps already covers many of the cases
1231 // where it would have applied. In addition, it's counter-intuitive
1232 // that a tie breaker would be the first thing attempted. There's a
1233 // "real" tie breaker below that is the operation of last resort.
1234 // The fact that the "special tie breaker" would trigger when there
1235 // wasn't otherwise a tie is what broke the strict weak ordering
1238 unsigned LPriority = SPQ->getNodePriority(left);
1239 unsigned RPriority = SPQ->getNodePriority(right);
1240 if (LPriority > RPriority)
1242 else if (LPriority == RPriority) {
1243 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1248 // and the following instructions are both ready.
1252 // Then schedule t2 = op first.
1259 // This creates more short live intervals.
1260 unsigned LDist = closestSucc(left);
1261 unsigned RDist = closestSucc(right);
1264 else if (LDist == RDist) {
1265 // Intuitively, it's good to push down instructions whose results are
1266 // liveout so their long live ranges won't conflict with other values
1267 // which are needed inside the BB. Further prioritize liveout instructions
1268 // by the number of operands which are calculated within the BB.
1269 unsigned LScratch = calcMaxScratches(left);
1270 unsigned RScratch = calcMaxScratches(right);
1271 if (LScratch > RScratch)
1273 else if (LScratch == RScratch)
1274 if (left->Height > right->Height)
1276 else if (left->Height == right->Height)
1277 if (left->Depth < right->Depth)
1279 else if (left->Depth == right->Depth)
1280 if (left->CycleBound > right->CycleBound)
1288 bool BURegReductionPriorityQueue<SF>::canClobber(SUnit *SU, SUnit *Op) {
1289 if (SU->isTwoAddress) {
1290 unsigned Opc = SU->Node->getTargetOpcode();
1291 const TargetInstrDesc &TID = TII->get(Opc);
1292 unsigned NumRes = TID.getNumDefs();
1293 unsigned NumOps = ScheduleDAG::CountOperands(SU->Node);
1294 for (unsigned i = 0; i != NumOps; ++i) {
1295 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1296 SDNode *DU = SU->Node->getOperand(i).Val;
1297 if ((*SUnitMap).find(DU) != (*SUnitMap).end() &&
1298 Op == (*SUnitMap)[DU][SU->InstanceNo])
1307 /// hasCopyToRegUse - Return true if SU has a value successor that is a
1309 static bool hasCopyToRegUse(SUnit *SU) {
1310 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1312 if (I->isCtrl) continue;
1313 SUnit *SuccSU = I->Dep;
1314 if (SuccSU->Node && SuccSU->Node->getOpcode() == ISD::CopyToReg)
1320 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1321 /// physical register def.
1322 static bool canClobberPhysRegDefs(SUnit *SuccSU, SUnit *SU,
1323 const TargetInstrInfo *TII,
1324 const MRegisterInfo *MRI) {
1325 SDNode *N = SuccSU->Node;
1326 unsigned NumDefs = TII->get(N->getTargetOpcode()).getNumDefs();
1327 const unsigned *ImpDefs = TII->get(N->getTargetOpcode()).getImplicitDefs();
1330 const unsigned *SUImpDefs =
1331 TII->get(SU->Node->getTargetOpcode()).getImplicitDefs();
1334 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1335 MVT::ValueType VT = N->getValueType(i);
1336 if (VT == MVT::Flag || VT == MVT::Other)
1338 unsigned Reg = ImpDefs[i - NumDefs];
1339 for (;*SUImpDefs; ++SUImpDefs) {
1340 unsigned SUReg = *SUImpDefs;
1341 if (MRI->regsOverlap(Reg, SUReg))
1348 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1349 /// it as a def&use operand. Add a pseudo control edge from it to the other
1350 /// node (if it won't create a cycle) so the two-address one will be scheduled
1351 /// first (lower in the schedule). If both nodes are two-address, favor the
1352 /// one that has a CopyToReg use (more likely to be a loop induction update).
1353 /// If both are two-address, but one is commutable while the other is not
1354 /// commutable, favor the one that's not commutable.
1356 void BURegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
1357 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1358 SUnit *SU = (SUnit *)&((*SUnits)[i]);
1359 if (!SU->isTwoAddress)
1362 SDNode *Node = SU->Node;
1363 if (!Node || !Node->isTargetOpcode() || SU->FlaggedNodes.size() > 0)
1366 unsigned Opc = Node->getTargetOpcode();
1367 const TargetInstrDesc &TID = TII->get(Opc);
1368 unsigned NumRes = TID.getNumDefs();
1369 unsigned NumOps = ScheduleDAG::CountOperands(Node);
1370 for (unsigned j = 0; j != NumOps; ++j) {
1371 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) != -1) {
1372 SDNode *DU = SU->Node->getOperand(j).Val;
1373 if ((*SUnitMap).find(DU) == (*SUnitMap).end())
1375 SUnit *DUSU = (*SUnitMap)[DU][SU->InstanceNo];
1376 if (!DUSU) continue;
1377 for (SUnit::succ_iterator I = DUSU->Succs.begin(),E = DUSU->Succs.end();
1379 if (I->isCtrl) continue;
1380 SUnit *SuccSU = I->Dep;
1383 // Be conservative. Ignore if nodes aren't at roughly the same
1384 // depth and height.
1385 if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1387 if (!SuccSU->Node || !SuccSU->Node->isTargetOpcode())
1389 // Don't constrain nodes with physical register defs if the
1390 // predecessor can cloober them.
1391 if (SuccSU->hasPhysRegDefs) {
1392 if (canClobberPhysRegDefs(SuccSU, SU, TII, MRI))
1395 // Don't constraint extract_subreg / insert_subreg these may be
1396 // coalesced away. We don't them close to their uses.
1397 unsigned SuccOpc = SuccSU->Node->getTargetOpcode();
1398 if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1399 SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1401 if ((!canClobber(SuccSU, DUSU) ||
1402 (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1403 (!SU->isCommutable && SuccSU->isCommutable)) &&
1404 !isReachable(SuccSU, SU)) {
1405 DOUT << "Adding an edge from SU # " << SU->NodeNum
1406 << " to SU #" << SuccSU->NodeNum << "\n";
1407 SU->addPred(SuccSU, true, true);
1415 /// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
1416 /// Smaller number is the higher priority.
1418 unsigned BURegReductionPriorityQueue<SF>::
1419 CalcNodeSethiUllmanNumber(const SUnit *SU) {
1420 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
1421 if (SethiUllmanNumber != 0)
1422 return SethiUllmanNumber;
1425 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1427 if (I->isCtrl) continue; // ignore chain preds
1428 SUnit *PredSU = I->Dep;
1429 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
1430 if (PredSethiUllman > SethiUllmanNumber) {
1431 SethiUllmanNumber = PredSethiUllman;
1433 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1437 SethiUllmanNumber += Extra;
1439 if (SethiUllmanNumber == 0)
1440 SethiUllmanNumber = 1;
1442 return SethiUllmanNumber;
1445 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1446 /// scheduling units.
1448 void BURegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
1449 SethiUllmanNumbers.assign(SUnits->size(), 0);
1451 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1452 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
1455 static unsigned SumOfUnscheduledPredsOfSuccs(const SUnit *SU) {
1457 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1459 SUnit *SuccSU = I->Dep;
1460 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1461 EE = SuccSU->Preds.end(); II != EE; ++II) {
1462 SUnit *PredSU = II->Dep;
1463 if (!PredSU->isScheduled)
1473 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1474 unsigned LPriority = SPQ->getNodePriority(left);
1475 unsigned RPriority = SPQ->getNodePriority(right);
1476 bool LIsTarget = left->Node && left->Node->isTargetOpcode();
1477 bool RIsTarget = right->Node && right->Node->isTargetOpcode();
1478 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1479 bool RIsFloater = RIsTarget && right->NumPreds == 0;
1480 unsigned LBonus = (SumOfUnscheduledPredsOfSuccs(left) == 1) ? 2 : 0;
1481 unsigned RBonus = (SumOfUnscheduledPredsOfSuccs(right) == 1) ? 2 : 0;
1483 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1485 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1488 // Special tie breaker: if two nodes share a operand, the one that use it
1489 // as a def&use operand is preferred.
1490 if (LIsTarget && RIsTarget) {
1491 if (left->isTwoAddress && !right->isTwoAddress) {
1492 SDNode *DUNode = left->Node->getOperand(0).Val;
1493 if (DUNode->isOperand(right->Node))
1496 if (!left->isTwoAddress && right->isTwoAddress) {
1497 SDNode *DUNode = right->Node->getOperand(0).Val;
1498 if (DUNode->isOperand(left->Node))
1506 if (left->NumSuccs == 1)
1508 if (right->NumSuccs == 1)
1511 if (LPriority+LBonus < RPriority+RBonus)
1513 else if (LPriority == RPriority)
1514 if (left->Depth < right->Depth)
1516 else if (left->Depth == right->Depth)
1517 if (left->NumSuccsLeft > right->NumSuccsLeft)
1519 else if (left->NumSuccsLeft == right->NumSuccsLeft)
1520 if (left->CycleBound > right->CycleBound)
1525 /// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
1526 /// Smaller number is the higher priority.
1528 unsigned TDRegReductionPriorityQueue<SF>::
1529 CalcNodeSethiUllmanNumber(const SUnit *SU) {
1530 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
1531 if (SethiUllmanNumber != 0)
1532 return SethiUllmanNumber;
1534 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1535 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1536 SethiUllmanNumber = 0xffff;
1537 else if (SU->NumSuccsLeft == 0)
1538 // If SU does not have a use, i.e. it doesn't produce a value that would
1539 // be consumed (e.g. store), then it terminates a chain of computation.
1540 // Give it a small SethiUllman number so it will be scheduled right before
1541 // its predecessors that it doesn't lengthen their live ranges.
1542 SethiUllmanNumber = 0;
1543 else if (SU->NumPredsLeft == 0 &&
1544 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
1545 SethiUllmanNumber = 0xffff;
1548 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1550 if (I->isCtrl) continue; // ignore chain preds
1551 SUnit *PredSU = I->Dep;
1552 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
1553 if (PredSethiUllman > SethiUllmanNumber) {
1554 SethiUllmanNumber = PredSethiUllman;
1556 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1560 SethiUllmanNumber += Extra;
1563 return SethiUllmanNumber;
1566 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1567 /// scheduling units.
1569 void TDRegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
1570 SethiUllmanNumbers.assign(SUnits->size(), 0);
1572 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1573 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
1576 //===----------------------------------------------------------------------===//
1577 // Public Constructor Functions
1578 //===----------------------------------------------------------------------===//
1580 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1582 MachineBasicBlock *BB) {
1583 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
1584 const MRegisterInfo *MRI = DAG->getTarget().getRegisterInfo();
1585 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true,
1586 new BURegReductionPriorityQueue<bu_ls_rr_sort>(TII, MRI));
1589 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1591 MachineBasicBlock *BB) {
1592 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false,
1593 new TDRegReductionPriorityQueue<td_ls_rr_sort>());