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/TargetRegisterInfo.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/ADT/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 backtracked");
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.
61 SchedulingPriorityQueue *AvailableQueue;
63 /// LiveRegs / LiveRegDefs - A set of physical registers and their definition
64 /// that are "live". These nodes must be scheduled before any other nodes that
65 /// modifies the registers can be scheduled.
66 SmallSet<unsigned, 4> LiveRegs;
67 std::vector<SUnit*> LiveRegDefs;
68 std::vector<unsigned> LiveRegCycles;
71 ScheduleDAGRRList(SelectionDAG &dag, MachineBasicBlock *bb,
72 const TargetMachine &tm, bool isbottomup,
73 SchedulingPriorityQueue *availqueue)
74 : ScheduleDAG(dag, bb, tm), isBottomUp(isbottomup),
75 AvailableQueue(availqueue) {
78 ~ScheduleDAGRRList() {
79 delete AvailableQueue;
84 /// IsReachable - Checks if SU is reachable from TargetSU.
85 bool IsReachable(SUnit *SU, SUnit *TargetSU);
87 /// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
89 bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
91 /// AddPred - This adds the specified node X as a predecessor of
92 /// the current node Y if not already.
93 /// This returns true if this is a new predecessor.
94 /// Updates the topological ordering if required.
95 bool AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
96 unsigned PhyReg = 0, int Cost = 1);
98 /// RemovePred - This removes the specified node N from the predecessors of
99 /// the current node M. Updates the topological ordering if required.
100 bool RemovePred(SUnit *M, SUnit *N, bool isCtrl, bool isSpecial);
103 void ReleasePred(SUnit*, bool, unsigned);
104 void ReleaseSucc(SUnit*, bool isChain, unsigned);
105 void CapturePred(SUnit*, SUnit*, bool);
106 void ScheduleNodeBottomUp(SUnit*, unsigned);
107 void ScheduleNodeTopDown(SUnit*, unsigned);
108 void UnscheduleNodeBottomUp(SUnit*);
109 void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
110 SUnit *CopyAndMoveSuccessors(SUnit*);
111 void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
112 const TargetRegisterClass*,
113 const TargetRegisterClass*,
114 SmallVector<SUnit*, 2>&);
115 bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
116 void ListScheduleTopDown();
117 void ListScheduleBottomUp();
118 void CommuteNodesToReducePressure();
121 /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
122 /// Updates the topological ordering if required.
123 SUnit *CreateNewSUnit(SDNode *N) {
124 SUnit *NewNode = NewSUnit(N);
125 // Update the topological ordering.
126 if (NewNode->NodeNum >= Node2Index.size())
127 InitDAGTopologicalSorting();
131 /// CreateClone - Creates a new SUnit from an existing one.
132 /// Updates the topological ordering if required.
133 SUnit *CreateClone(SUnit *N) {
134 SUnit *NewNode = Clone(N);
135 // Update the topological ordering.
136 if (NewNode->NodeNum >= Node2Index.size())
137 InitDAGTopologicalSorting();
141 /// Functions for preserving the topological ordering
142 /// even after dynamic insertions of new edges.
143 /// This allows a very fast implementation of IsReachable.
147 The idea of the algorithm is taken from
148 "Online algorithms for managing the topological order of
149 a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
150 This is the MNR algorithm, which was first introduced by
151 A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
152 "Maintaining a topological order under edge insertions".
154 Short description of the algorithm:
156 Topological ordering, ord, of a DAG maps each node to a topological
157 index so that for all edges X->Y it is the case that ord(X) < ord(Y).
159 This means that if there is a path from the node X to the node Z,
160 then ord(X) < ord(Z).
162 This property can be used to check for reachability of nodes:
163 if Z is reachable from X, then an insertion of the edge Z->X would
166 The algorithm first computes a topological ordering for the DAG by initializing
167 the Index2Node and Node2Index arrays and then tries to keep the ordering
168 up-to-date after edge insertions by reordering the DAG.
170 On insertion of the edge X->Y, the algorithm first marks by calling DFS the
171 nodes reachable from Y, and then shifts them using Shift to lie immediately
172 after X in Index2Node.
175 /// InitDAGTopologicalSorting - create the initial topological
176 /// ordering from the DAG to be scheduled.
177 void InitDAGTopologicalSorting();
179 /// DFS - make a DFS traversal and mark all nodes affected by the
180 /// edge insertion. These nodes will later get new topological indexes
181 /// by means of the Shift method.
182 void DFS(SUnit *SU, int UpperBound, bool& HasLoop);
184 /// Shift - reassign topological indexes for the nodes in the DAG
185 /// to preserve the topological ordering.
186 void Shift(BitVector& Visited, int LowerBound, int UpperBound);
188 /// Allocate - assign the topological index to the node n.
189 void Allocate(int n, int index);
191 /// Index2Node - Maps topological index to the node number.
192 std::vector<int> Index2Node;
193 /// Node2Index - Maps the node number to its topological index.
194 std::vector<int> Node2Index;
195 /// Visited - a set of nodes visited during a DFS traversal.
198 } // end anonymous namespace
201 /// Schedule - Schedule the DAG using list scheduling.
202 void ScheduleDAGRRList::Schedule() {
203 DOUT << "********** List Scheduling **********\n";
205 LiveRegDefs.resize(TRI->getNumRegs(), NULL);
206 LiveRegCycles.resize(TRI->getNumRegs(), 0);
208 // Build scheduling units.
211 DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
212 SUnits[su].dumpAll(&DAG));
215 InitDAGTopologicalSorting();
217 AvailableQueue->initNodes(SUnitMap, SUnits);
219 // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
221 ListScheduleBottomUp();
223 ListScheduleTopDown();
225 AvailableQueue->releaseState();
227 CommuteNodesToReducePressure();
229 DOUT << "*** Final schedule ***\n";
230 DEBUG(dumpSchedule());
233 // Emit in scheduled order
237 /// CommuteNodesToReducePressure - If a node is two-address and commutable, and
238 /// it is not the last use of its first operand, add it to the CommuteSet if
239 /// possible. It will be commuted when it is translated to a MI.
240 void ScheduleDAGRRList::CommuteNodesToReducePressure() {
241 SmallPtrSet<SUnit*, 4> OperandSeen;
242 for (unsigned i = Sequence.size()-1; i != 0; --i) { // Ignore first node.
243 SUnit *SU = Sequence[i];
244 if (!SU || !SU->Node) continue;
245 if (SU->isCommutable) {
246 unsigned Opc = SU->Node->getTargetOpcode();
247 const TargetInstrDesc &TID = TII->get(Opc);
248 unsigned NumRes = TID.getNumDefs();
249 unsigned NumOps = TID.getNumOperands() - NumRes;
250 for (unsigned j = 0; j != NumOps; ++j) {
251 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
254 SDNode *OpN = SU->Node->getOperand(j).Val;
255 SUnit *OpSU = isPassiveNode(OpN) ? NULL : SUnitMap[OpN][SU->InstanceNo];
256 if (OpSU && OperandSeen.count(OpSU) == 1) {
257 // Ok, so SU is not the last use of OpSU, but SU is two-address so
258 // it will clobber OpSU. Try to commute SU if no other source operands
260 bool DoCommute = true;
261 for (unsigned k = 0; k < NumOps; ++k) {
263 OpN = SU->Node->getOperand(k).Val;
264 OpSU = isPassiveNode(OpN) ? NULL : SUnitMap[OpN][SU->InstanceNo];
265 if (OpSU && OperandSeen.count(OpSU) == 1) {
272 CommuteSet.insert(SU->Node);
275 // Only look at the first use&def node for now.
280 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
283 OperandSeen.insert(I->Dep);
288 //===----------------------------------------------------------------------===//
289 // Bottom-Up Scheduling
290 //===----------------------------------------------------------------------===//
292 /// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
293 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
294 void ScheduleDAGRRList::ReleasePred(SUnit *PredSU, bool isChain,
296 // FIXME: the distance between two nodes is not always == the predecessor's
297 // latency. For example, the reader can very well read the register written
298 // by the predecessor later than the issue cycle. It also depends on the
299 // interrupt model (drain vs. freeze).
300 PredSU->CycleBound = std::max(PredSU->CycleBound, CurCycle + PredSU->Latency);
302 --PredSU->NumSuccsLeft;
305 if (PredSU->NumSuccsLeft < 0) {
306 cerr << "*** List scheduling failed! ***\n";
308 cerr << " has been released too many times!\n";
313 if (PredSU->NumSuccsLeft == 0) {
314 // EntryToken has to go last! Special case it here.
315 if (!PredSU->Node || PredSU->Node->getOpcode() != ISD::EntryToken) {
316 PredSU->isAvailable = true;
317 AvailableQueue->push(PredSU);
322 /// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
323 /// count of its predecessors. If a predecessor pending count is zero, add it to
324 /// the Available queue.
325 void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
326 DOUT << "*** Scheduling [" << CurCycle << "]: ";
327 DEBUG(SU->dump(&DAG));
328 SU->Cycle = CurCycle;
330 AvailableQueue->ScheduledNode(SU);
332 // Bottom up: release predecessors
333 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
335 ReleasePred(I->Dep, I->isCtrl, CurCycle);
337 // This is a physical register dependency and it's impossible or
338 // expensive to copy the register. Make sure nothing that can
339 // clobber the register is scheduled between the predecessor and
341 if (LiveRegs.insert(I->Reg)) {
342 LiveRegDefs[I->Reg] = I->Dep;
343 LiveRegCycles[I->Reg] = CurCycle;
348 // Release all the implicit physical register defs that are live.
349 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
352 if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
353 LiveRegs.erase(I->Reg);
354 assert(LiveRegDefs[I->Reg] == SU &&
355 "Physical register dependency violated?");
356 LiveRegDefs[I->Reg] = NULL;
357 LiveRegCycles[I->Reg] = 0;
362 SU->isScheduled = true;
365 /// CapturePred - This does the opposite of ReleasePred. Since SU is being
366 /// unscheduled, incrcease the succ left count of its predecessors. Remove
367 /// them from AvailableQueue if necessary.
368 void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
369 PredSU->CycleBound = 0;
370 for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
374 PredSU->CycleBound = std::max(PredSU->CycleBound,
375 I->Dep->Cycle + PredSU->Latency);
378 if (PredSU->isAvailable) {
379 PredSU->isAvailable = false;
380 if (!PredSU->isPending)
381 AvailableQueue->remove(PredSU);
384 ++PredSU->NumSuccsLeft;
387 /// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
388 /// its predecessor states to reflect the change.
389 void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
390 DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
391 DEBUG(SU->dump(&DAG));
393 AvailableQueue->UnscheduledNode(SU);
395 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
397 CapturePred(I->Dep, SU, I->isCtrl);
398 if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg]) {
399 LiveRegs.erase(I->Reg);
400 assert(LiveRegDefs[I->Reg] == I->Dep &&
401 "Physical register dependency violated?");
402 LiveRegDefs[I->Reg] = NULL;
403 LiveRegCycles[I->Reg] = 0;
407 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
410 if (LiveRegs.insert(I->Reg)) {
411 assert(!LiveRegDefs[I->Reg] &&
412 "Physical register dependency violated?");
413 LiveRegDefs[I->Reg] = SU;
415 if (I->Dep->Cycle < LiveRegCycles[I->Reg])
416 LiveRegCycles[I->Reg] = I->Dep->Cycle;
421 SU->isScheduled = false;
422 SU->isAvailable = true;
423 AvailableQueue->push(SU);
426 /// IsReachable - Checks if SU is reachable from TargetSU.
427 bool ScheduleDAGRRList::IsReachable(SUnit *SU, SUnit *TargetSU) {
428 // If insertion of the edge SU->TargetSU would create a cycle
429 // then there is a path from TargetSU to SU.
430 int UpperBound, LowerBound;
431 LowerBound = Node2Index[TargetSU->NodeNum];
432 UpperBound = Node2Index[SU->NodeNum];
433 bool HasLoop = false;
434 // Is Ord(TargetSU) < Ord(SU) ?
435 if (LowerBound < UpperBound) {
437 // There may be a path from TargetSU to SU. Check for it.
438 DFS(TargetSU, UpperBound, HasLoop);
443 /// Allocate - assign the topological index to the node n.
444 inline void ScheduleDAGRRList::Allocate(int n, int index) {
445 Node2Index[n] = index;
446 Index2Node[index] = n;
449 /// InitDAGTopologicalSorting - create the initial topological
450 /// ordering from the DAG to be scheduled.
451 void ScheduleDAGRRList::InitDAGTopologicalSorting() {
452 unsigned DAGSize = SUnits.size();
453 std::vector<unsigned> InDegree(DAGSize);
454 std::vector<SUnit*> WorkList;
455 WorkList.reserve(DAGSize);
456 std::vector<SUnit*> TopOrder;
457 TopOrder.reserve(DAGSize);
459 // Initialize the data structures.
460 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
461 SUnit *SU = &SUnits[i];
462 int NodeNum = SU->NodeNum;
463 unsigned Degree = SU->Succs.size();
464 InDegree[NodeNum] = Degree;
466 // Is it a node without dependencies?
468 assert(SU->Succs.empty() && "SUnit should have no successors");
469 // Collect leaf nodes.
470 WorkList.push_back(SU);
474 while (!WorkList.empty()) {
475 SUnit *SU = WorkList.back();
477 TopOrder.push_back(SU);
478 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
481 if (!--InDegree[SU->NodeNum])
482 // If all dependencies of the node are processed already,
483 // then the node can be computed now.
484 WorkList.push_back(SU);
488 // Second pass, assign the actual topological order as node ids.
493 Index2Node.resize(DAGSize);
494 Node2Index.resize(DAGSize);
495 Visited.resize(DAGSize);
497 for (std::vector<SUnit*>::reverse_iterator TI = TopOrder.rbegin(),
498 TE = TopOrder.rend();TI != TE; ++TI) {
499 Allocate((*TI)->NodeNum, Id);
504 // Check correctness of the ordering
505 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
506 SUnit *SU = &SUnits[i];
507 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
509 assert(Node2Index[SU->NodeNum] > Node2Index[I->Dep->NodeNum] &&
510 "Wrong topological sorting");
516 /// AddPred - adds an edge from SUnit X to SUnit Y.
517 /// Updates the topological ordering if required.
518 bool ScheduleDAGRRList::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
519 unsigned PhyReg, int Cost) {
520 int UpperBound, LowerBound;
521 LowerBound = Node2Index[Y->NodeNum];
522 UpperBound = Node2Index[X->NodeNum];
523 bool HasLoop = false;
524 // Is Ord(X) < Ord(Y) ?
525 if (LowerBound < UpperBound) {
526 // Update the topological order.
528 DFS(Y, UpperBound, HasLoop);
529 assert(!HasLoop && "Inserted edge creates a loop!");
530 // Recompute topological indexes.
531 Shift(Visited, LowerBound, UpperBound);
533 // Now really insert the edge.
534 return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
537 /// RemovePred - This removes the specified node N from the predecessors of
538 /// the current node M. Updates the topological ordering if required.
539 bool ScheduleDAGRRList::RemovePred(SUnit *M, SUnit *N,
540 bool isCtrl, bool isSpecial) {
541 // InitDAGTopologicalSorting();
542 return M->removePred(N, isCtrl, isSpecial);
545 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
546 /// all nodes affected by the edge insertion. These nodes will later get new
547 /// topological indexes by means of the Shift method.
548 void ScheduleDAGRRList::DFS(SUnit *SU, int UpperBound, bool& HasLoop) {
549 std::vector<SUnit*> WorkList;
550 WorkList.reserve(SUnits.size());
552 WorkList.push_back(SU);
553 while (!WorkList.empty()) {
554 SU = WorkList.back();
556 Visited.set(SU->NodeNum);
557 for (int I = SU->Succs.size()-1; I >= 0; --I) {
558 int s = SU->Succs[I].Dep->NodeNum;
559 if (Node2Index[s] == UpperBound) {
563 // Visit successors if not already and in affected region.
564 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
565 WorkList.push_back(SU->Succs[I].Dep);
571 /// Shift - Renumber the nodes so that the topological ordering is
573 void ScheduleDAGRRList::Shift(BitVector& Visited, int LowerBound,
579 for (i = LowerBound; i <= UpperBound; ++i) {
580 // w is node at topological index i.
581 int w = Index2Node[i];
582 if (Visited.test(w)) {
588 Allocate(w, i - shift);
592 for (unsigned j = 0; j < L.size(); ++j) {
593 Allocate(L[j], i - shift);
599 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
601 bool ScheduleDAGRRList::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
602 if (IsReachable(TargetSU, SU))
604 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
606 if (I->Cost < 0 && IsReachable(TargetSU, I->Dep))
611 /// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
612 /// BTCycle in order to schedule a specific node. Returns the last unscheduled
613 /// SUnit. Also returns if a successor is unscheduled in the process.
614 void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
615 unsigned &CurCycle) {
617 while (CurCycle > BtCycle) {
618 OldSU = Sequence.back();
620 if (SU->isSucc(OldSU))
621 // Don't try to remove SU from AvailableQueue.
622 SU->isAvailable = false;
623 UnscheduleNodeBottomUp(OldSU);
628 if (SU->isSucc(OldSU)) {
629 assert(false && "Something is wrong!");
636 /// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
637 /// successors to the newly created node.
638 SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
639 if (SU->FlaggedNodes.size())
642 SDNode *N = SU->Node;
647 bool TryUnfold = false;
648 for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
649 MVT::ValueType VT = N->getValueType(i);
652 else if (VT == MVT::Other)
655 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
656 const SDOperand &Op = N->getOperand(i);
657 MVT::ValueType VT = Op.Val->getValueType(Op.ResNo);
663 SmallVector<SDNode*, 4> NewNodes;
664 if (!TII->unfoldMemoryOperand(DAG, N, NewNodes))
667 DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
668 assert(NewNodes.size() == 2 && "Expected a load folding node!");
671 SDNode *LoadNode = NewNodes[0];
672 unsigned NumVals = N->getNumValues();
673 unsigned OldNumVals = SU->Node->getNumValues();
674 for (unsigned i = 0; i != NumVals; ++i)
675 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, i), SDOperand(N, i));
676 DAG.ReplaceAllUsesOfValueWith(SDOperand(SU->Node, OldNumVals-1),
677 SDOperand(LoadNode, 1));
679 SUnit *NewSU = CreateNewSUnit(N);
680 SUnitMap[N].push_back(NewSU);
681 const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
682 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
683 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
684 NewSU->isTwoAddress = true;
688 if (TID.isCommutable())
689 NewSU->isCommutable = true;
690 // FIXME: Calculate height / depth and propagate the changes?
691 NewSU->Depth = SU->Depth;
692 NewSU->Height = SU->Height;
693 ComputeLatency(NewSU);
695 // LoadNode may already exist. This can happen when there is another
696 // load from the same location and producing the same type of value
697 // but it has different alignment or volatileness.
698 bool isNewLoad = true;
700 DenseMap<SDNode*, std::vector<SUnit*> >::iterator SMI =
701 SUnitMap.find(LoadNode);
702 if (SMI != SUnitMap.end()) {
703 LoadSU = SMI->second.front();
706 LoadSU = CreateNewSUnit(LoadNode);
707 SUnitMap[LoadNode].push_back(LoadSU);
709 LoadSU->Depth = SU->Depth;
710 LoadSU->Height = SU->Height;
711 ComputeLatency(LoadSU);
714 SUnit *ChainPred = NULL;
715 SmallVector<SDep, 4> ChainSuccs;
716 SmallVector<SDep, 4> LoadPreds;
717 SmallVector<SDep, 4> NodePreds;
718 SmallVector<SDep, 4> NodeSuccs;
719 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
723 else if (I->Dep->Node && I->Dep->Node->isOperandOf(LoadNode))
724 LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
726 NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
728 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
731 ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
732 I->isCtrl, I->isSpecial));
734 NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
735 I->isCtrl, I->isSpecial));
738 RemovePred(SU, ChainPred, true, false);
740 AddPred(LoadSU,ChainPred, true, false);
742 for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
743 SDep *Pred = &LoadPreds[i];
744 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
746 AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
747 Pred->Reg, Pred->Cost);
750 for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
751 SDep *Pred = &NodePreds[i];
752 RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
753 AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
754 Pred->Reg, Pred->Cost);
756 for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
757 SDep *Succ = &NodeSuccs[i];
758 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
759 AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
760 Succ->Reg, Succ->Cost);
762 for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
763 SDep *Succ = &ChainSuccs[i];
764 RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
766 AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
767 Succ->Reg, Succ->Cost);
771 AddPred(NewSU, LoadSU, false, false);
775 AvailableQueue->addNode(LoadSU);
776 AvailableQueue->addNode(NewSU);
780 if (NewSU->NumSuccsLeft == 0) {
781 NewSU->isAvailable = true;
787 DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
788 NewSU = CreateClone(SU);
790 // New SUnit has the exact same predecessors.
791 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
794 AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
795 NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
798 // Only copy scheduled successors. Cut them from old node's successor
799 // list and move them over.
800 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
801 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
805 if (I->Dep->isScheduled) {
806 NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
807 AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
808 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
811 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
812 SUnit *Succ = DelDeps[i].first;
813 bool isCtrl = DelDeps[i].second;
814 RemovePred(Succ, SU, isCtrl, false);
817 AvailableQueue->updateNode(SU);
818 AvailableQueue->addNode(NewSU);
824 /// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
825 /// and move all scheduled successors of the given SUnit to the last copy.
826 void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
827 const TargetRegisterClass *DestRC,
828 const TargetRegisterClass *SrcRC,
829 SmallVector<SUnit*, 2> &Copies) {
830 SUnit *CopyFromSU = CreateNewSUnit(NULL);
831 CopyFromSU->CopySrcRC = SrcRC;
832 CopyFromSU->CopyDstRC = DestRC;
833 CopyFromSU->Depth = SU->Depth;
834 CopyFromSU->Height = SU->Height;
836 SUnit *CopyToSU = CreateNewSUnit(NULL);
837 CopyToSU->CopySrcRC = DestRC;
838 CopyToSU->CopyDstRC = SrcRC;
840 // Only copy scheduled successors. Cut them from old node's successor
841 // list and move them over.
842 SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
843 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
847 if (I->Dep->isScheduled) {
848 CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
849 AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
850 DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
853 for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
854 SUnit *Succ = DelDeps[i].first;
855 bool isCtrl = DelDeps[i].second;
856 RemovePred(Succ, SU, isCtrl, false);
859 AddPred(CopyFromSU, SU, false, false, Reg, -1);
860 AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
862 AvailableQueue->updateNode(SU);
863 AvailableQueue->addNode(CopyFromSU);
864 AvailableQueue->addNode(CopyToSU);
865 Copies.push_back(CopyFromSU);
866 Copies.push_back(CopyToSU);
871 /// getPhysicalRegisterVT - Returns the ValueType of the physical register
872 /// definition of the specified node.
873 /// FIXME: Move to SelectionDAG?
874 static MVT::ValueType getPhysicalRegisterVT(SDNode *N, unsigned Reg,
875 const TargetInstrInfo *TII) {
876 const TargetInstrDesc &TID = TII->get(N->getTargetOpcode());
877 assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
878 unsigned NumRes = TID.getNumDefs();
879 for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
884 return N->getValueType(NumRes);
887 /// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
888 /// scheduling of the given node to satisfy live physical register dependencies.
889 /// If the specific node is the last one that's available to schedule, do
890 /// whatever is necessary (i.e. backtracking or cloning) to make it possible.
891 bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
892 SmallVector<unsigned, 4> &LRegs){
893 if (LiveRegs.empty())
896 SmallSet<unsigned, 4> RegAdded;
897 // If this node would clobber any "live" register, then it's not ready.
898 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
901 unsigned Reg = I->Reg;
902 if (LiveRegs.count(Reg) && LiveRegDefs[Reg] != I->Dep) {
903 if (RegAdded.insert(Reg))
904 LRegs.push_back(Reg);
906 for (const unsigned *Alias = TRI->getAliasSet(Reg);
908 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != I->Dep) {
909 if (RegAdded.insert(*Alias))
910 LRegs.push_back(*Alias);
915 for (unsigned i = 0, e = SU->FlaggedNodes.size()+1; i != e; ++i) {
916 SDNode *Node = (i == 0) ? SU->Node : SU->FlaggedNodes[i-1];
917 if (!Node || !Node->isTargetOpcode())
919 const TargetInstrDesc &TID = TII->get(Node->getTargetOpcode());
920 if (!TID.ImplicitDefs)
922 for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
923 if (LiveRegs.count(*Reg) && LiveRegDefs[*Reg] != SU) {
924 if (RegAdded.insert(*Reg))
925 LRegs.push_back(*Reg);
927 for (const unsigned *Alias = TRI->getAliasSet(*Reg);
929 if (LiveRegs.count(*Alias) && LiveRegDefs[*Alias] != SU) {
930 if (RegAdded.insert(*Alias))
931 LRegs.push_back(*Alias);
935 return !LRegs.empty();
939 /// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
941 void ScheduleDAGRRList::ListScheduleBottomUp() {
942 unsigned CurCycle = 0;
943 // Add root to Available queue.
944 SUnit *RootSU = SUnitMap[DAG.getRoot().Val].front();
945 RootSU->isAvailable = true;
946 AvailableQueue->push(RootSU);
948 // While Available queue is not empty, grab the node with the highest
949 // priority. If it is not ready put it back. Schedule the node.
950 SmallVector<SUnit*, 4> NotReady;
951 while (!AvailableQueue->empty()) {
952 bool Delayed = false;
953 DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
954 SUnit *CurSU = AvailableQueue->pop();
956 if (CurSU->CycleBound <= CurCycle) {
957 SmallVector<unsigned, 4> LRegs;
958 if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
961 LRegsMap.insert(std::make_pair(CurSU, LRegs));
964 CurSU->isPending = true; // This SU is not in AvailableQueue right now.
965 NotReady.push_back(CurSU);
966 CurSU = AvailableQueue->pop();
969 // All candidates are delayed due to live physical reg dependencies.
970 // Try backtracking, code duplication, or inserting cross class copies
972 if (Delayed && !CurSU) {
973 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
974 SUnit *TrySU = NotReady[i];
975 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
977 // Try unscheduling up to the point where it's safe to schedule
979 unsigned LiveCycle = CurCycle;
980 for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
981 unsigned Reg = LRegs[j];
982 unsigned LCycle = LiveRegCycles[Reg];
983 LiveCycle = std::min(LiveCycle, LCycle);
985 SUnit *OldSU = Sequence[LiveCycle];
986 if (!WillCreateCycle(TrySU, OldSU)) {
987 BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
988 // Force the current node to be scheduled before the node that
989 // requires the physical reg dep.
990 if (OldSU->isAvailable) {
991 OldSU->isAvailable = false;
992 AvailableQueue->remove(OldSU);
994 AddPred(TrySU, OldSU, true, true);
995 // If one or more successors has been unscheduled, then the current
996 // node is no longer avaialable. Schedule a successor that's now
997 // available instead.
998 if (!TrySU->isAvailable)
999 CurSU = AvailableQueue->pop();
1002 TrySU->isPending = false;
1003 NotReady.erase(NotReady.begin()+i);
1010 // Can't backtrack. Try duplicating the nodes that produces these
1011 // "expensive to copy" values to break the dependency. In case even
1012 // that doesn't work, insert cross class copies.
1013 SUnit *TrySU = NotReady[0];
1014 SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1015 assert(LRegs.size() == 1 && "Can't handle this yet!");
1016 unsigned Reg = LRegs[0];
1017 SUnit *LRDef = LiveRegDefs[Reg];
1018 SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
1020 // Issue expensive cross register class copies.
1021 MVT::ValueType VT = getPhysicalRegisterVT(LRDef->Node, Reg, TII);
1022 const TargetRegisterClass *RC =
1023 TRI->getPhysicalRegisterRegClass(Reg, VT);
1024 const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1026 assert(false && "Don't know how to copy this physical register!");
1029 SmallVector<SUnit*, 2> Copies;
1030 InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1031 DOUT << "Adding an edge from SU # " << TrySU->NodeNum
1032 << " to SU #" << Copies.front()->NodeNum << "\n";
1033 AddPred(TrySU, Copies.front(), true, true);
1034 NewDef = Copies.back();
1037 DOUT << "Adding an edge from SU # " << NewDef->NodeNum
1038 << " to SU #" << TrySU->NodeNum << "\n";
1039 LiveRegDefs[Reg] = NewDef;
1040 AddPred(NewDef, TrySU, true, true);
1041 TrySU->isAvailable = false;
1046 assert(false && "Unable to resolve live physical register dependencies!");
1051 // Add the nodes that aren't ready back onto the available list.
1052 for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
1053 NotReady[i]->isPending = false;
1054 // May no longer be available due to backtracking.
1055 if (NotReady[i]->isAvailable)
1056 AvailableQueue->push(NotReady[i]);
1061 Sequence.push_back(0);
1063 ScheduleNodeBottomUp(CurSU, CurCycle);
1064 Sequence.push_back(CurSU);
1069 // Add entry node last
1070 if (DAG.getEntryNode().Val != DAG.getRoot().Val) {
1071 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
1072 Sequence.push_back(Entry);
1075 // Reverse the order if it is bottom up.
1076 std::reverse(Sequence.begin(), Sequence.end());
1080 // Verify that all SUnits were scheduled.
1081 bool AnyNotSched = false;
1082 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1083 if (SUnits[i].NumSuccsLeft != 0) {
1085 cerr << "*** List scheduling failed! ***\n";
1086 SUnits[i].dump(&DAG);
1087 cerr << "has not been scheduled!\n";
1091 assert(!AnyNotSched);
1095 //===----------------------------------------------------------------------===//
1096 // Top-Down Scheduling
1097 //===----------------------------------------------------------------------===//
1099 /// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1100 /// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1101 void ScheduleDAGRRList::ReleaseSucc(SUnit *SuccSU, bool isChain,
1102 unsigned CurCycle) {
1103 // FIXME: the distance between two nodes is not always == the predecessor's
1104 // latency. For example, the reader can very well read the register written
1105 // by the predecessor later than the issue cycle. It also depends on the
1106 // interrupt model (drain vs. freeze).
1107 SuccSU->CycleBound = std::max(SuccSU->CycleBound, CurCycle + SuccSU->Latency);
1109 --SuccSU->NumPredsLeft;
1112 if (SuccSU->NumPredsLeft < 0) {
1113 cerr << "*** List scheduling failed! ***\n";
1115 cerr << " has been released too many times!\n";
1120 if (SuccSU->NumPredsLeft == 0) {
1121 SuccSU->isAvailable = true;
1122 AvailableQueue->push(SuccSU);
1127 /// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1128 /// count of its successors. If a successor pending count is zero, add it to
1129 /// the Available queue.
1130 void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
1131 DOUT << "*** Scheduling [" << CurCycle << "]: ";
1132 DEBUG(SU->dump(&DAG));
1133 SU->Cycle = CurCycle;
1135 AvailableQueue->ScheduledNode(SU);
1137 // Top down: release successors
1138 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1140 ReleaseSucc(I->Dep, I->isCtrl, CurCycle);
1141 SU->isScheduled = true;
1144 /// ListScheduleTopDown - The main loop of list scheduling for top-down
1146 void ScheduleDAGRRList::ListScheduleTopDown() {
1147 unsigned CurCycle = 0;
1148 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val].front();
1150 // All leaves to Available queue.
1151 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1152 // It is available if it has no predecessors.
1153 if (SUnits[i].Preds.empty() && &SUnits[i] != Entry) {
1154 AvailableQueue->push(&SUnits[i]);
1155 SUnits[i].isAvailable = true;
1159 // Emit the entry node first.
1160 ScheduleNodeTopDown(Entry, CurCycle);
1161 Sequence.push_back(Entry);
1164 // While Available queue is not empty, grab the node with the highest
1165 // priority. If it is not ready put it back. Schedule the node.
1166 std::vector<SUnit*> NotReady;
1167 while (!AvailableQueue->empty()) {
1168 SUnit *CurSU = AvailableQueue->pop();
1169 while (CurSU && CurSU->CycleBound > CurCycle) {
1170 NotReady.push_back(CurSU);
1171 CurSU = AvailableQueue->pop();
1174 // Add the nodes that aren't ready back onto the available list.
1175 AvailableQueue->push_all(NotReady);
1179 Sequence.push_back(0);
1181 ScheduleNodeTopDown(CurSU, CurCycle);
1182 Sequence.push_back(CurSU);
1189 // Verify that all SUnits were scheduled.
1190 bool AnyNotSched = false;
1191 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1192 if (!SUnits[i].isScheduled) {
1194 cerr << "*** List scheduling failed! ***\n";
1195 SUnits[i].dump(&DAG);
1196 cerr << "has not been scheduled!\n";
1200 assert(!AnyNotSched);
1206 //===----------------------------------------------------------------------===//
1207 // RegReductionPriorityQueue Implementation
1208 //===----------------------------------------------------------------------===//
1210 // This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1211 // to reduce register pressure.
1215 class RegReductionPriorityQueue;
1217 /// Sorting functions for the Available queue.
1218 struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1219 RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1220 bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1221 bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1223 bool operator()(const SUnit* left, const SUnit* right) const;
1226 struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1227 RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
1228 td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1229 td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1231 bool operator()(const SUnit* left, const SUnit* right) const;
1233 } // end anonymous namespace
1235 static inline bool isCopyFromLiveIn(const SUnit *SU) {
1236 SDNode *N = SU->Node;
1237 return N && N->getOpcode() == ISD::CopyFromReg &&
1238 N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
1243 class VISIBILITY_HIDDEN RegReductionPriorityQueue
1244 : public SchedulingPriorityQueue {
1245 std::priority_queue<SUnit*, std::vector<SUnit*>, SF> Queue;
1248 RegReductionPriorityQueue() :
1251 virtual void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
1252 std::vector<SUnit> &sunits) {}
1254 virtual void addNode(const SUnit *SU) {}
1256 virtual void updateNode(const SUnit *SU) {}
1258 virtual void releaseState() {}
1260 virtual unsigned getNodePriority(const SUnit *SU) const {
1264 unsigned size() const { return Queue.size(); }
1266 bool empty() const { return Queue.empty(); }
1268 void push(SUnit *U) {
1271 void push_all(const std::vector<SUnit *> &Nodes) {
1272 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1273 Queue.push(Nodes[i]);
1277 if (empty()) return NULL;
1278 SUnit *V = Queue.top();
1283 /// remove - This is a really inefficient way to remove a node from a
1284 /// priority queue. We should roll our own heap to make this better or
1286 void remove(SUnit *SU) {
1287 std::vector<SUnit*> Temp;
1289 assert(!Queue.empty() && "Not in queue!");
1290 while (Queue.top() != SU) {
1291 Temp.push_back(Queue.top());
1293 assert(!Queue.empty() && "Not in queue!");
1296 // Remove the node from the PQ.
1299 // Add all the other nodes back.
1300 for (unsigned i = 0, e = Temp.size(); i != e; ++i)
1301 Queue.push(Temp[i]);
1306 class VISIBILITY_HIDDEN BURegReductionPriorityQueue
1307 : public RegReductionPriorityQueue<SF> {
1308 // SUnitMap SDNode to SUnit mapping (n -> n).
1309 DenseMap<SDNode*, std::vector<SUnit*> > *SUnitMap;
1311 // SUnits - The SUnits for the current graph.
1312 const std::vector<SUnit> *SUnits;
1314 // SethiUllmanNumbers - The SethiUllman number for each node.
1315 std::vector<unsigned> SethiUllmanNumbers;
1317 const TargetInstrInfo *TII;
1318 const TargetRegisterInfo *TRI;
1319 ScheduleDAGRRList *scheduleDAG;
1321 explicit BURegReductionPriorityQueue(const TargetInstrInfo *tii,
1322 const TargetRegisterInfo *tri)
1323 : TII(tii), TRI(tri), scheduleDAG(NULL) {}
1325 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
1326 std::vector<SUnit> &sunits) {
1329 // Add pseudo dependency edges for two-address nodes.
1330 AddPseudoTwoAddrDeps();
1331 // Calculate node priorities.
1332 CalculateSethiUllmanNumbers();
1335 void addNode(const SUnit *SU) {
1336 SethiUllmanNumbers.resize(SUnits->size(), 0);
1337 CalcNodeSethiUllmanNumber(SU);
1340 void updateNode(const SUnit *SU) {
1341 SethiUllmanNumbers[SU->NodeNum] = 0;
1342 CalcNodeSethiUllmanNumber(SU);
1345 void releaseState() {
1347 SethiUllmanNumbers.clear();
1350 unsigned getNodePriority(const SUnit *SU) const {
1351 assert(SU->NodeNum < SethiUllmanNumbers.size());
1352 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1353 if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1354 // CopyFromReg should be close to its def because it restricts
1355 // allocation choices. But if it is a livein then perhaps we want it
1356 // closer to its uses so it can be coalesced.
1358 else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1359 // CopyToReg should be close to its uses to facilitate coalescing and
1362 else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1363 Opc == TargetInstrInfo::INSERT_SUBREG)
1364 // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1365 // facilitate coalescing.
1367 else if (SU->NumSuccs == 0)
1368 // If SU does not have a use, i.e. it doesn't produce a value that would
1369 // be consumed (e.g. store), then it terminates a chain of computation.
1370 // Give it a large SethiUllman number so it will be scheduled right
1371 // before its predecessors that it doesn't lengthen their live ranges.
1373 else if (SU->NumPreds == 0)
1374 // If SU does not have a def, schedule it close to its uses because it
1375 // does not lengthen any live ranges.
1378 return SethiUllmanNumbers[SU->NodeNum];
1381 void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1382 scheduleDAG = scheduleDag;
1386 bool canClobber(const SUnit *SU, const SUnit *Op);
1387 void AddPseudoTwoAddrDeps();
1388 void CalculateSethiUllmanNumbers();
1389 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
1394 class VISIBILITY_HIDDEN TDRegReductionPriorityQueue
1395 : public RegReductionPriorityQueue<SF> {
1396 // SUnitMap SDNode to SUnit mapping (n -> n).
1397 DenseMap<SDNode*, std::vector<SUnit*> > *SUnitMap;
1399 // SUnits - The SUnits for the current graph.
1400 const std::vector<SUnit> *SUnits;
1402 // SethiUllmanNumbers - The SethiUllman number for each node.
1403 std::vector<unsigned> SethiUllmanNumbers;
1406 TDRegReductionPriorityQueue() {}
1408 void initNodes(DenseMap<SDNode*, std::vector<SUnit*> > &sumap,
1409 std::vector<SUnit> &sunits) {
1412 // Calculate node priorities.
1413 CalculateSethiUllmanNumbers();
1416 void addNode(const SUnit *SU) {
1417 SethiUllmanNumbers.resize(SUnits->size(), 0);
1418 CalcNodeSethiUllmanNumber(SU);
1421 void updateNode(const SUnit *SU) {
1422 SethiUllmanNumbers[SU->NodeNum] = 0;
1423 CalcNodeSethiUllmanNumber(SU);
1426 void releaseState() {
1428 SethiUllmanNumbers.clear();
1431 unsigned getNodePriority(const SUnit *SU) const {
1432 assert(SU->NodeNum < SethiUllmanNumbers.size());
1433 return SethiUllmanNumbers[SU->NodeNum];
1437 void CalculateSethiUllmanNumbers();
1438 unsigned CalcNodeSethiUllmanNumber(const SUnit *SU);
1442 /// closestSucc - Returns the scheduled cycle of the successor which is
1443 /// closet to the current cycle.
1444 static unsigned closestSucc(const SUnit *SU) {
1445 unsigned MaxCycle = 0;
1446 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1448 unsigned Cycle = I->Dep->Cycle;
1449 // If there are bunch of CopyToRegs stacked up, they should be considered
1450 // to be at the same position.
1451 if (I->Dep->Node && I->Dep->Node->getOpcode() == ISD::CopyToReg)
1452 Cycle = closestSucc(I->Dep)+1;
1453 if (Cycle > MaxCycle)
1459 /// calcMaxScratches - Returns an cost estimate of the worse case requirement
1460 /// for scratch registers. Live-in operands and live-out results don't count
1461 /// since they are "fixed".
1462 static unsigned calcMaxScratches(const SUnit *SU) {
1463 unsigned Scratches = 0;
1464 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1466 if (I->isCtrl) continue; // ignore chain preds
1467 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyFromReg)
1470 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1472 if (I->isCtrl) continue; // ignore chain succs
1473 if (!I->Dep->Node || I->Dep->Node->getOpcode() != ISD::CopyToReg)
1480 bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1481 // There used to be a special tie breaker here that looked for
1482 // two-address instructions and preferred the instruction with a
1483 // def&use operand. The special case triggered diagnostics when
1484 // _GLIBCXX_DEBUG was enabled because it broke the strict weak
1485 // ordering that priority_queue requires. It didn't help much anyway
1486 // because AddPseudoTwoAddrDeps already covers many of the cases
1487 // where it would have applied. In addition, it's counter-intuitive
1488 // that a tie breaker would be the first thing attempted. There's a
1489 // "real" tie breaker below that is the operation of last resort.
1490 // The fact that the "special tie breaker" would trigger when there
1491 // wasn't otherwise a tie is what broke the strict weak ordering
1494 unsigned LPriority = SPQ->getNodePriority(left);
1495 unsigned RPriority = SPQ->getNodePriority(right);
1496 if (LPriority != RPriority)
1497 return LPriority > RPriority;
1499 // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1504 // and the following instructions are both ready.
1508 // Then schedule t2 = op first.
1515 // This creates more short live intervals.
1516 unsigned LDist = closestSucc(left);
1517 unsigned RDist = closestSucc(right);
1519 return LDist < RDist;
1521 // Intuitively, it's good to push down instructions whose results are
1522 // liveout so their long live ranges won't conflict with other values
1523 // which are needed inside the BB. Further prioritize liveout instructions
1524 // by the number of operands which are calculated within the BB.
1525 unsigned LScratch = calcMaxScratches(left);
1526 unsigned RScratch = calcMaxScratches(right);
1527 if (LScratch != RScratch)
1528 return LScratch > RScratch;
1530 if (left->Height != right->Height)
1531 return left->Height > right->Height;
1533 if (left->Depth != right->Depth)
1534 return left->Depth < right->Depth;
1536 if (left->CycleBound != right->CycleBound)
1537 return left->CycleBound > right->CycleBound;
1539 // FIXME: No strict ordering.
1543 template<class SF> bool
1544 BURegReductionPriorityQueue<SF>::canClobber(const SUnit *SU, const SUnit *Op) {
1545 if (SU->isTwoAddress) {
1546 unsigned Opc = SU->Node->getTargetOpcode();
1547 const TargetInstrDesc &TID = TII->get(Opc);
1548 unsigned NumRes = TID.getNumDefs();
1549 unsigned NumOps = TID.getNumOperands() - NumRes;
1550 for (unsigned i = 0; i != NumOps; ++i) {
1551 if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1552 SDNode *DU = SU->Node->getOperand(i).Val;
1553 if ((*SUnitMap).find(DU) != (*SUnitMap).end() &&
1554 Op == (*SUnitMap)[DU][SU->InstanceNo])
1563 /// hasCopyToRegUse - Return true if SU has a value successor that is a
1565 static bool hasCopyToRegUse(SUnit *SU) {
1566 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1568 if (I->isCtrl) continue;
1569 SUnit *SuccSU = I->Dep;
1570 if (SuccSU->Node && SuccSU->Node->getOpcode() == ISD::CopyToReg)
1576 /// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1577 /// physical register def.
1578 static bool canClobberPhysRegDefs(SUnit *SuccSU, SUnit *SU,
1579 const TargetInstrInfo *TII,
1580 const TargetRegisterInfo *TRI) {
1581 SDNode *N = SuccSU->Node;
1582 unsigned NumDefs = TII->get(N->getTargetOpcode()).getNumDefs();
1583 const unsigned *ImpDefs = TII->get(N->getTargetOpcode()).getImplicitDefs();
1586 const unsigned *SUImpDefs =
1587 TII->get(SU->Node->getTargetOpcode()).getImplicitDefs();
1590 for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1591 MVT::ValueType VT = N->getValueType(i);
1592 if (VT == MVT::Flag || VT == MVT::Other)
1594 unsigned Reg = ImpDefs[i - NumDefs];
1595 for (;*SUImpDefs; ++SUImpDefs) {
1596 unsigned SUReg = *SUImpDefs;
1597 if (TRI->regsOverlap(Reg, SUReg))
1604 /// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1605 /// it as a def&use operand. Add a pseudo control edge from it to the other
1606 /// node (if it won't create a cycle) so the two-address one will be scheduled
1607 /// first (lower in the schedule). If both nodes are two-address, favor the
1608 /// one that has a CopyToReg use (more likely to be a loop induction update).
1609 /// If both are two-address, but one is commutable while the other is not
1610 /// commutable, favor the one that's not commutable.
1612 void BURegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
1613 for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1614 SUnit *SU = (SUnit *)&((*SUnits)[i]);
1615 if (!SU->isTwoAddress)
1618 SDNode *Node = SU->Node;
1619 if (!Node || !Node->isTargetOpcode() || SU->FlaggedNodes.size() > 0)
1622 unsigned Opc = Node->getTargetOpcode();
1623 const TargetInstrDesc &TID = TII->get(Opc);
1624 unsigned NumRes = TID.getNumDefs();
1625 unsigned NumOps = TID.getNumOperands() - NumRes;
1626 for (unsigned j = 0; j != NumOps; ++j) {
1627 if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) != -1) {
1628 SDNode *DU = SU->Node->getOperand(j).Val;
1629 if ((*SUnitMap).find(DU) == (*SUnitMap).end())
1631 SUnit *DUSU = (*SUnitMap)[DU][SU->InstanceNo];
1632 if (!DUSU) continue;
1633 for (SUnit::succ_iterator I = DUSU->Succs.begin(),E = DUSU->Succs.end();
1635 if (I->isCtrl) continue;
1636 SUnit *SuccSU = I->Dep;
1639 // Be conservative. Ignore if nodes aren't at roughly the same
1640 // depth and height.
1641 if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1643 if (!SuccSU->Node || !SuccSU->Node->isTargetOpcode())
1645 // Don't constrain nodes with physical register defs if the
1646 // predecessor can clobber them.
1647 if (SuccSU->hasPhysRegDefs) {
1648 if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1651 // Don't constraint extract_subreg / insert_subreg these may be
1652 // coalesced away. We don't them close to their uses.
1653 unsigned SuccOpc = SuccSU->Node->getTargetOpcode();
1654 if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1655 SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1657 if ((!canClobber(SuccSU, DUSU) ||
1658 (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1659 (!SU->isCommutable && SuccSU->isCommutable)) &&
1660 !scheduleDAG->IsReachable(SuccSU, SU)) {
1661 DOUT << "Adding an edge from SU # " << SU->NodeNum
1662 << " to SU #" << SuccSU->NodeNum << "\n";
1663 scheduleDAG->AddPred(SU, SuccSU, true, true);
1671 /// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
1672 /// Smaller number is the higher priority.
1674 unsigned BURegReductionPriorityQueue<SF>::
1675 CalcNodeSethiUllmanNumber(const SUnit *SU) {
1676 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
1677 if (SethiUllmanNumber != 0)
1678 return SethiUllmanNumber;
1681 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1683 if (I->isCtrl) continue; // ignore chain preds
1684 SUnit *PredSU = I->Dep;
1685 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
1686 if (PredSethiUllman > SethiUllmanNumber) {
1687 SethiUllmanNumber = PredSethiUllman;
1689 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1693 SethiUllmanNumber += Extra;
1695 if (SethiUllmanNumber == 0)
1696 SethiUllmanNumber = 1;
1698 return SethiUllmanNumber;
1701 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1702 /// scheduling units.
1704 void BURegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
1705 SethiUllmanNumbers.assign(SUnits->size(), 0);
1707 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1708 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
1711 static unsigned SumOfUnscheduledPredsOfSuccs(const SUnit *SU) {
1713 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1715 SUnit *SuccSU = I->Dep;
1716 for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1717 EE = SuccSU->Preds.end(); II != EE; ++II) {
1718 SUnit *PredSU = II->Dep;
1719 if (!PredSU->isScheduled)
1729 bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1730 unsigned LPriority = SPQ->getNodePriority(left);
1731 unsigned RPriority = SPQ->getNodePriority(right);
1732 bool LIsTarget = left->Node && left->Node->isTargetOpcode();
1733 bool RIsTarget = right->Node && right->Node->isTargetOpcode();
1734 bool LIsFloater = LIsTarget && left->NumPreds == 0;
1735 bool RIsFloater = RIsTarget && right->NumPreds == 0;
1736 unsigned LBonus = (SumOfUnscheduledPredsOfSuccs(left) == 1) ? 2 : 0;
1737 unsigned RBonus = (SumOfUnscheduledPredsOfSuccs(right) == 1) ? 2 : 0;
1739 if (left->NumSuccs == 0 && right->NumSuccs != 0)
1741 else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1748 if (left->NumSuccs == 1)
1750 if (right->NumSuccs == 1)
1753 if (LPriority+LBonus != RPriority+RBonus)
1754 return LPriority+LBonus < RPriority+RBonus;
1756 if (left->Depth != right->Depth)
1757 return left->Depth < right->Depth;
1759 if (left->NumSuccsLeft != right->NumSuccsLeft)
1760 return left->NumSuccsLeft > right->NumSuccsLeft;
1762 if (left->CycleBound != right->CycleBound)
1763 return left->CycleBound > right->CycleBound;
1765 // FIXME: No strict ordering.
1769 /// CalcNodeSethiUllmanNumber - Priority is the Sethi Ullman number.
1770 /// Smaller number is the higher priority.
1772 unsigned TDRegReductionPriorityQueue<SF>::
1773 CalcNodeSethiUllmanNumber(const SUnit *SU) {
1774 unsigned &SethiUllmanNumber = SethiUllmanNumbers[SU->NodeNum];
1775 if (SethiUllmanNumber != 0)
1776 return SethiUllmanNumber;
1778 unsigned Opc = SU->Node ? SU->Node->getOpcode() : 0;
1779 if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1780 SethiUllmanNumber = 0xffff;
1781 else if (SU->NumSuccsLeft == 0)
1782 // If SU does not have a use, i.e. it doesn't produce a value that would
1783 // be consumed (e.g. store), then it terminates a chain of computation.
1784 // Give it a small SethiUllman number so it will be scheduled right before
1785 // its predecessors that it doesn't lengthen their live ranges.
1786 SethiUllmanNumber = 0;
1787 else if (SU->NumPredsLeft == 0 &&
1788 (Opc != ISD::CopyFromReg || isCopyFromLiveIn(SU)))
1789 SethiUllmanNumber = 0xffff;
1792 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1794 if (I->isCtrl) continue; // ignore chain preds
1795 SUnit *PredSU = I->Dep;
1796 unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU);
1797 if (PredSethiUllman > SethiUllmanNumber) {
1798 SethiUllmanNumber = PredSethiUllman;
1800 } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1804 SethiUllmanNumber += Extra;
1807 return SethiUllmanNumber;
1810 /// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1811 /// scheduling units.
1813 void TDRegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
1814 SethiUllmanNumbers.assign(SUnits->size(), 0);
1816 for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1817 CalcNodeSethiUllmanNumber(&(*SUnits)[i]);
1820 //===----------------------------------------------------------------------===//
1821 // Public Constructor Functions
1822 //===----------------------------------------------------------------------===//
1824 llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1826 MachineBasicBlock *BB) {
1827 const TargetInstrInfo *TII = DAG->getTarget().getInstrInfo();
1828 const TargetRegisterInfo *TRI = DAG->getTarget().getRegisterInfo();
1830 BURegReductionPriorityQueue<bu_ls_rr_sort> *priorityQueue =
1831 new BURegReductionPriorityQueue<bu_ls_rr_sort>(TII, TRI);
1833 ScheduleDAGRRList * scheduleDAG =
1834 new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), true, priorityQueue);
1835 priorityQueue->setScheduleDAG(scheduleDAG);
1839 llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1841 MachineBasicBlock *BB) {
1842 return new ScheduleDAGRRList(*DAG, BB, DAG->getTarget(), false,
1843 new TDRegReductionPriorityQueue<td_ls_rr_sort>());