ScheduleDAGRRList.cpp revision 55aef3bcfc7dd2c0c192554ab4f162bae750e689
1//===----- ScheduleDAGRRList.cpp - Reg pressure reduction list scheduler --===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "pre-RA-sched"
19#include "llvm/CodeGen/ScheduleDAGSDNodes.h"
20#include "llvm/CodeGen/SchedulerRegistry.h"
21#include "llvm/Target/TargetRegisterInfo.h"
22#include "llvm/Target/TargetData.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetInstrInfo.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/PriorityQueue.h"
29#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/ADT/SmallSet.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
33#include <climits>
34#include "llvm/Support/CommandLine.h"
35using namespace llvm;
36
37STATISTIC(NumBacktracks, "Number of times scheduler backtracked");
38STATISTIC(NumUnfolds,    "Number of nodes unfolded");
39STATISTIC(NumDups,       "Number of duplicated nodes");
40STATISTIC(NumCCCopies,   "Number of cross class copies");
41
42static RegisterScheduler
43  burrListDAGScheduler("list-burr",
44                       "Bottom-up register reduction list scheduling",
45                       createBURRListDAGScheduler);
46static RegisterScheduler
47  tdrListrDAGScheduler("list-tdrr",
48                       "Top-down register reduction list scheduling",
49                       createTDRRListDAGScheduler);
50
51namespace {
52//===----------------------------------------------------------------------===//
53/// ScheduleDAGRRList - The actual register reduction list scheduler
54/// implementation.  This supports both top-down and bottom-up scheduling.
55///
56class VISIBILITY_HIDDEN ScheduleDAGRRList : public ScheduleDAGSDNodes {
57private:
58  /// isBottomUp - This is true if the scheduling problem is bottom-up, false if
59  /// it is top-down.
60  bool isBottomUp;
61
62  /// AvailableQueue - The priority queue to use for the available SUnits.
63  SchedulingPriorityQueue *AvailableQueue;
64
65  /// LiveRegDefs - A set of physical registers and their definition
66  /// that are "live". These nodes must be scheduled before any other nodes that
67  /// modifies the registers can be scheduled.
68  unsigned NumLiveRegs;
69  std::vector<SUnit*> LiveRegDefs;
70  std::vector<unsigned> LiveRegCycles;
71
72public:
73  ScheduleDAGRRList(SelectionDAG *dag, MachineBasicBlock *bb,
74                    const TargetMachine &tm, bool isbottomup,
75                    SchedulingPriorityQueue *availqueue)
76    : ScheduleDAGSDNodes(dag, bb, tm), isBottomUp(isbottomup),
77      AvailableQueue(availqueue) {
78    }
79
80  ~ScheduleDAGRRList() {
81    delete AvailableQueue;
82  }
83
84  void Schedule();
85
86  /// IsReachable - Checks if SU is reachable from TargetSU.
87  bool IsReachable(const SUnit *SU, const SUnit *TargetSU);
88
89  /// willCreateCycle - Returns true if adding an edge from SU to TargetSU will
90  /// create a cycle.
91  bool WillCreateCycle(SUnit *SU, SUnit *TargetSU);
92
93  /// AddPred - This adds the specified node X as a predecessor of
94  /// the current node Y if not already.
95  /// This returns true if this is a new predecessor.
96  /// Updates the topological ordering if required.
97  bool AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
98               unsigned PhyReg = 0, int Cost = 1);
99
100  /// RemovePred - This removes the specified node N from the predecessors of
101  /// the current node M. Updates the topological ordering if required.
102  bool RemovePred(SUnit *M, SUnit *N, bool isCtrl, bool isSpecial);
103
104private:
105  void ReleasePred(SUnit *SU, SUnit *PredSU, bool isChain);
106  void ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain);
107  void CapturePred(SUnit*, SUnit*, bool);
108  void ScheduleNodeBottomUp(SUnit*, unsigned);
109  void ScheduleNodeTopDown(SUnit*, unsigned);
110  void UnscheduleNodeBottomUp(SUnit*);
111  void BacktrackBottomUp(SUnit*, unsigned, unsigned&);
112  SUnit *CopyAndMoveSuccessors(SUnit*);
113  void InsertCCCopiesAndMoveSuccs(SUnit*, unsigned,
114                                  const TargetRegisterClass*,
115                                  const TargetRegisterClass*,
116                                  SmallVector<SUnit*, 2>&);
117  bool DelayForLiveRegsBottomUp(SUnit*, SmallVector<unsigned, 4>&);
118  void ListScheduleTopDown();
119  void ListScheduleBottomUp();
120  void CommuteNodesToReducePressure();
121
122
123  /// CreateNewSUnit - Creates a new SUnit and returns a pointer to it.
124  /// Updates the topological ordering if required.
125  SUnit *CreateNewSUnit(SDNode *N) {
126    SUnit *NewNode = NewSUnit(N);
127    // Update the topological ordering.
128    if (NewNode->NodeNum >= Node2Index.size())
129      InitDAGTopologicalSorting();
130    return NewNode;
131  }
132
133  /// CreateClone - Creates a new SUnit from an existing one.
134  /// Updates the topological ordering if required.
135  SUnit *CreateClone(SUnit *N) {
136    SUnit *NewNode = Clone(N);
137    // Update the topological ordering.
138    if (NewNode->NodeNum >= Node2Index.size())
139      InitDAGTopologicalSorting();
140    return NewNode;
141  }
142
143  /// Functions for preserving the topological ordering
144  /// even after dynamic insertions of new edges.
145  /// This allows a very fast implementation of IsReachable.
146
147  /// InitDAGTopologicalSorting - create the initial topological
148  /// ordering from the DAG to be scheduled.
149  void InitDAGTopologicalSorting();
150
151  /// DFS - make a DFS traversal and mark all nodes affected by the
152  /// edge insertion. These nodes will later get new topological indexes
153  /// by means of the Shift method.
154  void DFS(const SUnit *SU, int UpperBound, bool& HasLoop);
155
156  /// Shift - reassign topological indexes for the nodes in the DAG
157  /// to preserve the topological ordering.
158  void Shift(BitVector& Visited, int LowerBound, int UpperBound);
159
160  /// Allocate - assign the topological index to the node n.
161  void Allocate(int n, int index);
162
163  /// Index2Node - Maps topological index to the node number.
164  std::vector<int> Index2Node;
165  /// Node2Index - Maps the node number to its topological index.
166  std::vector<int> Node2Index;
167  /// Visited - a set of nodes visited during a DFS traversal.
168  BitVector Visited;
169};
170}  // end anonymous namespace
171
172
173/// Schedule - Schedule the DAG using list scheduling.
174void ScheduleDAGRRList::Schedule() {
175  DOUT << "********** List Scheduling **********\n";
176
177  NumLiveRegs = 0;
178  LiveRegDefs.resize(TRI->getNumRegs(), NULL);
179  LiveRegCycles.resize(TRI->getNumRegs(), 0);
180
181  // Build scheduling units.
182  BuildSchedUnits();
183
184  DEBUG(for (unsigned su = 0, e = SUnits.size(); su != e; ++su)
185          SUnits[su].dumpAll(this));
186  CalculateDepths();
187  CalculateHeights();
188  InitDAGTopologicalSorting();
189
190  AvailableQueue->initNodes(SUnits);
191
192  // Execute the actual scheduling loop Top-Down or Bottom-Up as appropriate.
193  if (isBottomUp)
194    ListScheduleBottomUp();
195  else
196    ListScheduleTopDown();
197
198  AvailableQueue->releaseState();
199
200  CommuteNodesToReducePressure();
201}
202
203/// CommuteNodesToReducePressure - If a node is two-address and commutable, and
204/// it is not the last use of its first operand, add it to the CommuteSet if
205/// possible. It will be commuted when it is translated to a MI.
206void ScheduleDAGRRList::CommuteNodesToReducePressure() {
207  SmallPtrSet<SUnit*, 4> OperandSeen;
208  for (unsigned i = Sequence.size(); i != 0; ) {
209    --i;
210    SUnit *SU = Sequence[i];
211    if (!SU || !SU->getNode()) continue;
212    if (SU->isCommutable) {
213      unsigned Opc = SU->getNode()->getMachineOpcode();
214      const TargetInstrDesc &TID = TII->get(Opc);
215      unsigned NumRes = TID.getNumDefs();
216      unsigned NumOps = TID.getNumOperands() - NumRes;
217      for (unsigned j = 0; j != NumOps; ++j) {
218        if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
219          continue;
220
221        SDNode *OpN = SU->getNode()->getOperand(j).getNode();
222        SUnit *OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
223        if (OpSU && OperandSeen.count(OpSU) == 1) {
224          // Ok, so SU is not the last use of OpSU, but SU is two-address so
225          // it will clobber OpSU. Try to commute SU if no other source operands
226          // are live below.
227          bool DoCommute = true;
228          for (unsigned k = 0; k < NumOps; ++k) {
229            if (k != j) {
230              OpN = SU->getNode()->getOperand(k).getNode();
231              OpSU = isPassiveNode(OpN) ? NULL : &SUnits[OpN->getNodeId()];
232              if (OpSU && OperandSeen.count(OpSU) == 1) {
233                DoCommute = false;
234                break;
235              }
236            }
237          }
238          if (DoCommute)
239            CommuteSet.insert(SU->getNode());
240        }
241
242        // Only look at the first use&def node for now.
243        break;
244      }
245    }
246
247    for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
248         I != E; ++I) {
249      if (!I->isCtrl)
250        OperandSeen.insert(I->Dep->OrigNode);
251    }
252  }
253}
254
255//===----------------------------------------------------------------------===//
256//  Bottom-Up Scheduling
257//===----------------------------------------------------------------------===//
258
259/// ReleasePred - Decrement the NumSuccsLeft count of a predecessor. Add it to
260/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
261void ScheduleDAGRRList::ReleasePred(SUnit *SU, SUnit *PredSU, bool isChain) {
262  --PredSU->NumSuccsLeft;
263
264#ifndef NDEBUG
265  if (PredSU->NumSuccsLeft < 0) {
266    cerr << "*** Scheduling failed! ***\n";
267    PredSU->dump(this);
268    cerr << " has been released too many times!\n";
269    assert(0);
270  }
271#endif
272
273  // Compute how many cycles it will be before this actually becomes
274  // available.  This is the max of the start time of all predecessors plus
275  // their latencies.
276  // If this is a token edge, we don't need to wait for the latency of the
277  // preceeding instruction (e.g. a long-latency load) unless there is also
278  // some other data dependence.
279  unsigned PredDoneCycle = SU->Cycle;
280  if (!isChain)
281    PredDoneCycle += PredSU->Latency;
282  else if (SU->Latency)
283    PredDoneCycle += 1;
284  PredSU->CycleBound = std::max(PredSU->CycleBound, PredDoneCycle);
285
286  if (PredSU->NumSuccsLeft == 0) {
287    PredSU->isAvailable = true;
288    AvailableQueue->push(PredSU);
289  }
290}
291
292/// ScheduleNodeBottomUp - Add the node to the schedule. Decrement the pending
293/// count of its predecessors. If a predecessor pending count is zero, add it to
294/// the Available queue.
295void ScheduleDAGRRList::ScheduleNodeBottomUp(SUnit *SU, unsigned CurCycle) {
296  DOUT << "*** Scheduling [" << CurCycle << "]: ";
297  DEBUG(SU->dump(this));
298
299  SU->Cycle = CurCycle;
300  Sequence.push_back(SU);
301
302  // Bottom up: release predecessors
303  for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
304       I != E; ++I) {
305    ReleasePred(SU, I->Dep, I->isCtrl);
306    if (I->Cost < 0)  {
307      // This is a physical register dependency and it's impossible or
308      // expensive to copy the register. Make sure nothing that can
309      // clobber the register is scheduled between the predecessor and
310      // this node.
311      if (!LiveRegDefs[I->Reg]) {
312        ++NumLiveRegs;
313        LiveRegDefs[I->Reg] = I->Dep;
314        LiveRegCycles[I->Reg] = CurCycle;
315      }
316    }
317  }
318
319  // Release all the implicit physical register defs that are live.
320  for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
321       I != E; ++I) {
322    if (I->Cost < 0)  {
323      if (LiveRegCycles[I->Reg] == I->Dep->Cycle) {
324        assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
325        assert(LiveRegDefs[I->Reg] == SU &&
326               "Physical register dependency violated?");
327        --NumLiveRegs;
328        LiveRegDefs[I->Reg] = NULL;
329        LiveRegCycles[I->Reg] = 0;
330      }
331    }
332  }
333
334  SU->isScheduled = true;
335  AvailableQueue->ScheduledNode(SU);
336}
337
338/// CapturePred - This does the opposite of ReleasePred. Since SU is being
339/// unscheduled, incrcease the succ left count of its predecessors. Remove
340/// them from AvailableQueue if necessary.
341void ScheduleDAGRRList::CapturePred(SUnit *PredSU, SUnit *SU, bool isChain) {
342  unsigned CycleBound = 0;
343  for (SUnit::succ_iterator I = PredSU->Succs.begin(), E = PredSU->Succs.end();
344       I != E; ++I) {
345    if (I->Dep == SU)
346      continue;
347    CycleBound = std::max(CycleBound,
348                          I->Dep->Cycle + PredSU->Latency);
349  }
350
351  if (PredSU->isAvailable) {
352    PredSU->isAvailable = false;
353    if (!PredSU->isPending)
354      AvailableQueue->remove(PredSU);
355  }
356
357  PredSU->CycleBound = CycleBound;
358  ++PredSU->NumSuccsLeft;
359}
360
361/// UnscheduleNodeBottomUp - Remove the node from the schedule, update its and
362/// its predecessor states to reflect the change.
363void ScheduleDAGRRList::UnscheduleNodeBottomUp(SUnit *SU) {
364  DOUT << "*** Unscheduling [" << SU->Cycle << "]: ";
365  DEBUG(SU->dump(this));
366
367  AvailableQueue->UnscheduledNode(SU);
368
369  for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
370       I != E; ++I) {
371    CapturePred(I->Dep, SU, I->isCtrl);
372    if (I->Cost < 0 && SU->Cycle == LiveRegCycles[I->Reg])  {
373      assert(NumLiveRegs > 0 && "NumLiveRegs is already zero!");
374      assert(LiveRegDefs[I->Reg] == I->Dep &&
375             "Physical register dependency violated?");
376      --NumLiveRegs;
377      LiveRegDefs[I->Reg] = NULL;
378      LiveRegCycles[I->Reg] = 0;
379    }
380  }
381
382  for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
383       I != E; ++I) {
384    if (I->Cost < 0)  {
385      if (!LiveRegDefs[I->Reg]) {
386        LiveRegDefs[I->Reg] = SU;
387        ++NumLiveRegs;
388      }
389      if (I->Dep->Cycle < LiveRegCycles[I->Reg])
390        LiveRegCycles[I->Reg] = I->Dep->Cycle;
391    }
392  }
393
394  SU->Cycle = 0;
395  SU->isScheduled = false;
396  SU->isAvailable = true;
397  AvailableQueue->push(SU);
398}
399
400/// IsReachable - Checks if SU is reachable from TargetSU.
401bool ScheduleDAGRRList::IsReachable(const SUnit *SU, const SUnit *TargetSU) {
402  // If insertion of the edge SU->TargetSU would create a cycle
403  // then there is a path from TargetSU to SU.
404  int UpperBound, LowerBound;
405  LowerBound = Node2Index[TargetSU->NodeNum];
406  UpperBound = Node2Index[SU->NodeNum];
407  bool HasLoop = false;
408  // Is Ord(TargetSU) < Ord(SU) ?
409  if (LowerBound < UpperBound) {
410    Visited.reset();
411    // There may be a path from TargetSU to SU. Check for it.
412    DFS(TargetSU, UpperBound, HasLoop);
413  }
414  return HasLoop;
415}
416
417/// Allocate - assign the topological index to the node n.
418inline void ScheduleDAGRRList::Allocate(int n, int index) {
419  Node2Index[n] = index;
420  Index2Node[index] = n;
421}
422
423/// InitDAGTopologicalSorting - create the initial topological
424/// ordering from the DAG to be scheduled.
425
426/// The idea of the algorithm is taken from
427/// "Online algorithms for managing the topological order of
428/// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
429/// This is the MNR algorithm, which was first introduced by
430/// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
431/// "Maintaining a topological order under edge insertions".
432///
433/// Short description of the algorithm:
434///
435/// Topological ordering, ord, of a DAG maps each node to a topological
436/// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
437///
438/// This means that if there is a path from the node X to the node Z,
439/// then ord(X) < ord(Z).
440///
441/// This property can be used to check for reachability of nodes:
442/// if Z is reachable from X, then an insertion of the edge Z->X would
443/// create a cycle.
444///
445/// The algorithm first computes a topological ordering for the DAG by
446/// initializing the Index2Node and Node2Index arrays and then tries to keep
447/// the ordering up-to-date after edge insertions by reordering the DAG.
448///
449/// On insertion of the edge X->Y, the algorithm first marks by calling DFS
450/// the nodes reachable from Y, and then shifts them using Shift to lie
451/// immediately after X in Index2Node.
452void ScheduleDAGRRList::InitDAGTopologicalSorting() {
453  unsigned DAGSize = SUnits.size();
454  std::vector<SUnit*> WorkList;
455  WorkList.reserve(DAGSize);
456
457  Index2Node.resize(DAGSize);
458  Node2Index.resize(DAGSize);
459
460  // Initialize the data structures.
461  for (unsigned i = 0, e = DAGSize; i != e; ++i) {
462    SUnit *SU = &SUnits[i];
463    int NodeNum = SU->NodeNum;
464    unsigned Degree = SU->Succs.size();
465    // Temporarily use the Node2Index array as scratch space for degree counts.
466    Node2Index[NodeNum] = Degree;
467
468    // Is it a node without dependencies?
469    if (Degree == 0) {
470        assert(SU->Succs.empty() && "SUnit should have no successors");
471        // Collect leaf nodes.
472        WorkList.push_back(SU);
473    }
474  }
475
476  int Id = DAGSize;
477  while (!WorkList.empty()) {
478    SUnit *SU = WorkList.back();
479    WorkList.pop_back();
480    Allocate(SU->NodeNum, --Id);
481    for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
482         I != E; ++I) {
483      SUnit *SU = I->Dep;
484      if (!--Node2Index[SU->NodeNum])
485        // If all dependencies of the node are processed already,
486        // then the node can be computed now.
487        WorkList.push_back(SU);
488    }
489  }
490
491  Visited.resize(DAGSize);
492
493#ifndef NDEBUG
494  // Check correctness of the ordering
495  for (unsigned i = 0, e = DAGSize; i != e; ++i) {
496    SUnit *SU = &SUnits[i];
497    for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
498         I != E; ++I) {
499       assert(Node2Index[SU->NodeNum] > Node2Index[I->Dep->NodeNum] &&
500       "Wrong topological sorting");
501    }
502  }
503#endif
504}
505
506/// AddPred - adds an edge from SUnit X to SUnit Y.
507/// Updates the topological ordering if required.
508bool ScheduleDAGRRList::AddPred(SUnit *Y, SUnit *X, bool isCtrl, bool isSpecial,
509                 unsigned PhyReg, int Cost) {
510  int UpperBound, LowerBound;
511  LowerBound = Node2Index[Y->NodeNum];
512  UpperBound = Node2Index[X->NodeNum];
513  bool HasLoop = false;
514  // Is Ord(X) < Ord(Y) ?
515  if (LowerBound < UpperBound) {
516    // Update the topological order.
517    Visited.reset();
518    DFS(Y, UpperBound, HasLoop);
519    assert(!HasLoop && "Inserted edge creates a loop!");
520    // Recompute topological indexes.
521    Shift(Visited, LowerBound, UpperBound);
522  }
523  // Now really insert the edge.
524  return Y->addPred(X, isCtrl, isSpecial, PhyReg, Cost);
525}
526
527/// RemovePred - This removes the specified node N from the predecessors of
528/// the current node M. Updates the topological ordering if required.
529bool ScheduleDAGRRList::RemovePred(SUnit *M, SUnit *N,
530                                   bool isCtrl, bool isSpecial) {
531  // InitDAGTopologicalSorting();
532  return M->removePred(N, isCtrl, isSpecial);
533}
534
535/// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
536/// all nodes affected by the edge insertion. These nodes will later get new
537/// topological indexes by means of the Shift method.
538void ScheduleDAGRRList::DFS(const SUnit *SU, int UpperBound, bool& HasLoop) {
539  std::vector<const SUnit*> WorkList;
540  WorkList.reserve(SUnits.size());
541
542  WorkList.push_back(SU);
543  while (!WorkList.empty()) {
544    SU = WorkList.back();
545    WorkList.pop_back();
546    Visited.set(SU->NodeNum);
547    for (int I = SU->Succs.size()-1; I >= 0; --I) {
548      int s = SU->Succs[I].Dep->NodeNum;
549      if (Node2Index[s] == UpperBound) {
550        HasLoop = true;
551        return;
552      }
553      // Visit successors if not already and in affected region.
554      if (!Visited.test(s) && Node2Index[s] < UpperBound) {
555        WorkList.push_back(SU->Succs[I].Dep);
556      }
557    }
558  }
559}
560
561/// Shift - Renumber the nodes so that the topological ordering is
562/// preserved.
563void ScheduleDAGRRList::Shift(BitVector& Visited, int LowerBound,
564                              int UpperBound) {
565  std::vector<int> L;
566  int shift = 0;
567  int i;
568
569  for (i = LowerBound; i <= UpperBound; ++i) {
570    // w is node at topological index i.
571    int w = Index2Node[i];
572    if (Visited.test(w)) {
573      // Unmark.
574      Visited.reset(w);
575      L.push_back(w);
576      shift = shift + 1;
577    } else {
578      Allocate(w, i - shift);
579    }
580  }
581
582  for (unsigned j = 0; j < L.size(); ++j) {
583    Allocate(L[j], i - shift);
584    i = i + 1;
585  }
586}
587
588
589/// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
590/// create a cycle.
591bool ScheduleDAGRRList::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
592  if (IsReachable(TargetSU, SU))
593    return true;
594  for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
595       I != E; ++I)
596    if (I->Cost < 0 && IsReachable(TargetSU, I->Dep))
597      return true;
598  return false;
599}
600
601/// BacktrackBottomUp - Backtrack scheduling to a previous cycle specified in
602/// BTCycle in order to schedule a specific node. Returns the last unscheduled
603/// SUnit. Also returns if a successor is unscheduled in the process.
604void ScheduleDAGRRList::BacktrackBottomUp(SUnit *SU, unsigned BtCycle,
605                                          unsigned &CurCycle) {
606  SUnit *OldSU = NULL;
607  while (CurCycle > BtCycle) {
608    OldSU = Sequence.back();
609    Sequence.pop_back();
610    if (SU->isSucc(OldSU))
611      // Don't try to remove SU from AvailableQueue.
612      SU->isAvailable = false;
613    UnscheduleNodeBottomUp(OldSU);
614    --CurCycle;
615  }
616
617
618  if (SU->isSucc(OldSU)) {
619    assert(false && "Something is wrong!");
620    abort();
621  }
622
623  ++NumBacktracks;
624}
625
626/// CopyAndMoveSuccessors - Clone the specified node and move its scheduled
627/// successors to the newly created node.
628SUnit *ScheduleDAGRRList::CopyAndMoveSuccessors(SUnit *SU) {
629  if (SU->getNode()->getFlaggedNode())
630    return NULL;
631
632  SDNode *N = SU->getNode();
633  if (!N)
634    return NULL;
635
636  SUnit *NewSU;
637  bool TryUnfold = false;
638  for (unsigned i = 0, e = N->getNumValues(); i != e; ++i) {
639    MVT VT = N->getValueType(i);
640    if (VT == MVT::Flag)
641      return NULL;
642    else if (VT == MVT::Other)
643      TryUnfold = true;
644  }
645  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
646    const SDValue &Op = N->getOperand(i);
647    MVT VT = Op.getNode()->getValueType(Op.getResNo());
648    if (VT == MVT::Flag)
649      return NULL;
650  }
651
652  if (TryUnfold) {
653    SmallVector<SDNode*, 2> NewNodes;
654    if (!TII->unfoldMemoryOperand(*DAG, N, NewNodes))
655      return NULL;
656
657    DOUT << "Unfolding SU # " << SU->NodeNum << "\n";
658    assert(NewNodes.size() == 2 && "Expected a load folding node!");
659
660    N = NewNodes[1];
661    SDNode *LoadNode = NewNodes[0];
662    unsigned NumVals = N->getNumValues();
663    unsigned OldNumVals = SU->getNode()->getNumValues();
664    for (unsigned i = 0; i != NumVals; ++i)
665      DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), i), SDValue(N, i));
666    DAG->ReplaceAllUsesOfValueWith(SDValue(SU->getNode(), OldNumVals-1),
667                                   SDValue(LoadNode, 1));
668
669    // LoadNode may already exist. This can happen when there is another
670    // load from the same location and producing the same type of value
671    // but it has different alignment or volatileness.
672    bool isNewLoad = true;
673    SUnit *LoadSU;
674    if (LoadNode->getNodeId() != -1) {
675      LoadSU = &SUnits[LoadNode->getNodeId()];
676      isNewLoad = false;
677    } else {
678      LoadSU = CreateNewSUnit(LoadNode);
679      LoadNode->setNodeId(LoadSU->NodeNum);
680
681      LoadSU->Depth = SU->Depth;
682      LoadSU->Height = SU->Height;
683      ComputeLatency(LoadSU);
684    }
685
686    SUnit *NewSU = CreateNewSUnit(N);
687    assert(N->getNodeId() == -1 && "Node already inserted!");
688    N->setNodeId(NewSU->NodeNum);
689
690    const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
691    for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
692      if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
693        NewSU->isTwoAddress = true;
694        break;
695      }
696    }
697    if (TID.isCommutable())
698      NewSU->isCommutable = true;
699    // FIXME: Calculate height / depth and propagate the changes?
700    NewSU->Depth = SU->Depth;
701    NewSU->Height = SU->Height;
702    ComputeLatency(NewSU);
703
704    SUnit *ChainPred = NULL;
705    SmallVector<SDep, 4> ChainSuccs;
706    SmallVector<SDep, 4> LoadPreds;
707    SmallVector<SDep, 4> NodePreds;
708    SmallVector<SDep, 4> NodeSuccs;
709    for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
710         I != E; ++I) {
711      if (I->isCtrl)
712        ChainPred = I->Dep;
713      else if (I->Dep->getNode() && I->Dep->getNode()->isOperandOf(LoadNode))
714        LoadPreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
715      else
716        NodePreds.push_back(SDep(I->Dep, I->Reg, I->Cost, false, false));
717    }
718    for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
719         I != E; ++I) {
720      if (I->isCtrl)
721        ChainSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
722                                  I->isCtrl, I->isSpecial));
723      else
724        NodeSuccs.push_back(SDep(I->Dep, I->Reg, I->Cost,
725                                 I->isCtrl, I->isSpecial));
726    }
727
728    if (ChainPred) {
729      RemovePred(SU, ChainPred, true, false);
730      if (isNewLoad)
731        AddPred(LoadSU, ChainPred, true, false);
732    }
733    for (unsigned i = 0, e = LoadPreds.size(); i != e; ++i) {
734      SDep *Pred = &LoadPreds[i];
735      RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
736      if (isNewLoad) {
737        AddPred(LoadSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
738                Pred->Reg, Pred->Cost);
739      }
740    }
741    for (unsigned i = 0, e = NodePreds.size(); i != e; ++i) {
742      SDep *Pred = &NodePreds[i];
743      RemovePred(SU, Pred->Dep, Pred->isCtrl, Pred->isSpecial);
744      AddPred(NewSU, Pred->Dep, Pred->isCtrl, Pred->isSpecial,
745              Pred->Reg, Pred->Cost);
746    }
747    for (unsigned i = 0, e = NodeSuccs.size(); i != e; ++i) {
748      SDep *Succ = &NodeSuccs[i];
749      RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
750      AddPred(Succ->Dep, NewSU, Succ->isCtrl, Succ->isSpecial,
751              Succ->Reg, Succ->Cost);
752    }
753    for (unsigned i = 0, e = ChainSuccs.size(); i != e; ++i) {
754      SDep *Succ = &ChainSuccs[i];
755      RemovePred(Succ->Dep, SU, Succ->isCtrl, Succ->isSpecial);
756      if (isNewLoad) {
757        AddPred(Succ->Dep, LoadSU, Succ->isCtrl, Succ->isSpecial,
758                Succ->Reg, Succ->Cost);
759      }
760    }
761    if (isNewLoad) {
762      AddPred(NewSU, LoadSU, false, false);
763    }
764
765    if (isNewLoad)
766      AvailableQueue->addNode(LoadSU);
767    AvailableQueue->addNode(NewSU);
768
769    ++NumUnfolds;
770
771    if (NewSU->NumSuccsLeft == 0) {
772      NewSU->isAvailable = true;
773      return NewSU;
774    }
775    SU = NewSU;
776  }
777
778  DOUT << "Duplicating SU # " << SU->NodeNum << "\n";
779  NewSU = CreateClone(SU);
780
781  // New SUnit has the exact same predecessors.
782  for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
783       I != E; ++I)
784    if (!I->isSpecial) {
785      AddPred(NewSU, I->Dep, I->isCtrl, false, I->Reg, I->Cost);
786      NewSU->Depth = std::max(NewSU->Depth, I->Dep->Depth+1);
787    }
788
789  // Only copy scheduled successors. Cut them from old node's successor
790  // list and move them over.
791  SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
792  for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
793       I != E; ++I) {
794    if (I->isSpecial)
795      continue;
796    if (I->Dep->isScheduled) {
797      NewSU->Height = std::max(NewSU->Height, I->Dep->Height+1);
798      AddPred(I->Dep, NewSU, I->isCtrl, false, I->Reg, I->Cost);
799      DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
800    }
801  }
802  for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
803    SUnit *Succ = DelDeps[i].first;
804    bool isCtrl = DelDeps[i].second;
805    RemovePred(Succ, SU, isCtrl, false);
806  }
807
808  AvailableQueue->updateNode(SU);
809  AvailableQueue->addNode(NewSU);
810
811  ++NumDups;
812  return NewSU;
813}
814
815/// InsertCCCopiesAndMoveSuccs - Insert expensive cross register class copies
816/// and move all scheduled successors of the given SUnit to the last copy.
817void ScheduleDAGRRList::InsertCCCopiesAndMoveSuccs(SUnit *SU, unsigned Reg,
818                                              const TargetRegisterClass *DestRC,
819                                              const TargetRegisterClass *SrcRC,
820                                               SmallVector<SUnit*, 2> &Copies) {
821  SUnit *CopyFromSU = CreateNewSUnit(NULL);
822  CopyFromSU->CopySrcRC = SrcRC;
823  CopyFromSU->CopyDstRC = DestRC;
824  CopyFromSU->Depth = SU->Depth;
825  CopyFromSU->Height = SU->Height;
826
827  SUnit *CopyToSU = CreateNewSUnit(NULL);
828  CopyToSU->CopySrcRC = DestRC;
829  CopyToSU->CopyDstRC = SrcRC;
830
831  // Only copy scheduled successors. Cut them from old node's successor
832  // list and move them over.
833  SmallVector<std::pair<SUnit*, bool>, 4> DelDeps;
834  for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
835       I != E; ++I) {
836    if (I->isSpecial)
837      continue;
838    if (I->Dep->isScheduled) {
839      CopyToSU->Height = std::max(CopyToSU->Height, I->Dep->Height+1);
840      AddPred(I->Dep, CopyToSU, I->isCtrl, false, I->Reg, I->Cost);
841      DelDeps.push_back(std::make_pair(I->Dep, I->isCtrl));
842    }
843  }
844  for (unsigned i = 0, e = DelDeps.size(); i != e; ++i) {
845    SUnit *Succ = DelDeps[i].first;
846    bool isCtrl = DelDeps[i].second;
847    RemovePred(Succ, SU, isCtrl, false);
848  }
849
850  AddPred(CopyFromSU, SU, false, false, Reg, -1);
851  AddPred(CopyToSU, CopyFromSU, false, false, Reg, 1);
852
853  AvailableQueue->updateNode(SU);
854  AvailableQueue->addNode(CopyFromSU);
855  AvailableQueue->addNode(CopyToSU);
856  Copies.push_back(CopyFromSU);
857  Copies.push_back(CopyToSU);
858
859  ++NumCCCopies;
860}
861
862/// getPhysicalRegisterVT - Returns the ValueType of the physical register
863/// definition of the specified node.
864/// FIXME: Move to SelectionDAG?
865static MVT getPhysicalRegisterVT(SDNode *N, unsigned Reg,
866                                 const TargetInstrInfo *TII) {
867  const TargetInstrDesc &TID = TII->get(N->getMachineOpcode());
868  assert(TID.ImplicitDefs && "Physical reg def must be in implicit def list!");
869  unsigned NumRes = TID.getNumDefs();
870  for (const unsigned *ImpDef = TID.getImplicitDefs(); *ImpDef; ++ImpDef) {
871    if (Reg == *ImpDef)
872      break;
873    ++NumRes;
874  }
875  return N->getValueType(NumRes);
876}
877
878/// DelayForLiveRegsBottomUp - Returns true if it is necessary to delay
879/// scheduling of the given node to satisfy live physical register dependencies.
880/// If the specific node is the last one that's available to schedule, do
881/// whatever is necessary (i.e. backtracking or cloning) to make it possible.
882bool ScheduleDAGRRList::DelayForLiveRegsBottomUp(SUnit *SU,
883                                                 SmallVector<unsigned, 4> &LRegs){
884  if (NumLiveRegs == 0)
885    return false;
886
887  SmallSet<unsigned, 4> RegAdded;
888  // If this node would clobber any "live" register, then it's not ready.
889  for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
890       I != E; ++I) {
891    if (I->Cost < 0)  {
892      unsigned Reg = I->Reg;
893      if (LiveRegDefs[Reg] && LiveRegDefs[Reg] != I->Dep) {
894        if (RegAdded.insert(Reg))
895          LRegs.push_back(Reg);
896      }
897      for (const unsigned *Alias = TRI->getAliasSet(Reg);
898           *Alias; ++Alias)
899        if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != I->Dep) {
900          if (RegAdded.insert(*Alias))
901            LRegs.push_back(*Alias);
902        }
903    }
904  }
905
906  for (SDNode *Node = SU->getNode(); Node; Node = Node->getFlaggedNode()) {
907    if (!Node->isMachineOpcode())
908      continue;
909    const TargetInstrDesc &TID = TII->get(Node->getMachineOpcode());
910    if (!TID.ImplicitDefs)
911      continue;
912    for (const unsigned *Reg = TID.ImplicitDefs; *Reg; ++Reg) {
913      if (LiveRegDefs[*Reg] && LiveRegDefs[*Reg] != SU) {
914        if (RegAdded.insert(*Reg))
915          LRegs.push_back(*Reg);
916      }
917      for (const unsigned *Alias = TRI->getAliasSet(*Reg);
918           *Alias; ++Alias)
919        if (LiveRegDefs[*Alias] && LiveRegDefs[*Alias] != SU) {
920          if (RegAdded.insert(*Alias))
921            LRegs.push_back(*Alias);
922        }
923    }
924  }
925  return !LRegs.empty();
926}
927
928
929/// ListScheduleBottomUp - The main loop of list scheduling for bottom-up
930/// schedulers.
931void ScheduleDAGRRList::ListScheduleBottomUp() {
932  unsigned CurCycle = 0;
933  // Add root to Available queue.
934  if (!SUnits.empty()) {
935    SUnit *RootSU = &SUnits[DAG->getRoot().getNode()->getNodeId()];
936    assert(RootSU->Succs.empty() && "Graph root shouldn't have successors!");
937    RootSU->isAvailable = true;
938    AvailableQueue->push(RootSU);
939  }
940
941  // While Available queue is not empty, grab the node with the highest
942  // priority. If it is not ready put it back.  Schedule the node.
943  SmallVector<SUnit*, 4> NotReady;
944  DenseMap<SUnit*, SmallVector<unsigned, 4> > LRegsMap;
945  Sequence.reserve(SUnits.size());
946  while (!AvailableQueue->empty()) {
947    bool Delayed = false;
948    LRegsMap.clear();
949    SUnit *CurSU = AvailableQueue->pop();
950    while (CurSU) {
951      if (CurSU->CycleBound <= CurCycle) {
952        SmallVector<unsigned, 4> LRegs;
953        if (!DelayForLiveRegsBottomUp(CurSU, LRegs))
954          break;
955        Delayed = true;
956        LRegsMap.insert(std::make_pair(CurSU, LRegs));
957      }
958
959      CurSU->isPending = true;  // This SU is not in AvailableQueue right now.
960      NotReady.push_back(CurSU);
961      CurSU = AvailableQueue->pop();
962    }
963
964    // All candidates are delayed due to live physical reg dependencies.
965    // Try backtracking, code duplication, or inserting cross class copies
966    // to resolve it.
967    if (Delayed && !CurSU) {
968      for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
969        SUnit *TrySU = NotReady[i];
970        SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
971
972        // Try unscheduling up to the point where it's safe to schedule
973        // this node.
974        unsigned LiveCycle = CurCycle;
975        for (unsigned j = 0, ee = LRegs.size(); j != ee; ++j) {
976          unsigned Reg = LRegs[j];
977          unsigned LCycle = LiveRegCycles[Reg];
978          LiveCycle = std::min(LiveCycle, LCycle);
979        }
980        SUnit *OldSU = Sequence[LiveCycle];
981        if (!WillCreateCycle(TrySU, OldSU))  {
982          BacktrackBottomUp(TrySU, LiveCycle, CurCycle);
983          // Force the current node to be scheduled before the node that
984          // requires the physical reg dep.
985          if (OldSU->isAvailable) {
986            OldSU->isAvailable = false;
987            AvailableQueue->remove(OldSU);
988          }
989          AddPred(TrySU, OldSU, true, true);
990          // If one or more successors has been unscheduled, then the current
991          // node is no longer avaialable. Schedule a successor that's now
992          // available instead.
993          if (!TrySU->isAvailable)
994            CurSU = AvailableQueue->pop();
995          else {
996            CurSU = TrySU;
997            TrySU->isPending = false;
998            NotReady.erase(NotReady.begin()+i);
999          }
1000          break;
1001        }
1002      }
1003
1004      if (!CurSU) {
1005        // Can't backtrack. Try duplicating the nodes that produces these
1006        // "expensive to copy" values to break the dependency. In case even
1007        // that doesn't work, insert cross class copies.
1008        SUnit *TrySU = NotReady[0];
1009        SmallVector<unsigned, 4> &LRegs = LRegsMap[TrySU];
1010        assert(LRegs.size() == 1 && "Can't handle this yet!");
1011        unsigned Reg = LRegs[0];
1012        SUnit *LRDef = LiveRegDefs[Reg];
1013        SUnit *NewDef = CopyAndMoveSuccessors(LRDef);
1014        if (!NewDef) {
1015          // Issue expensive cross register class copies.
1016          MVT VT = getPhysicalRegisterVT(LRDef->getNode(), Reg, TII);
1017          const TargetRegisterClass *RC =
1018            TRI->getPhysicalRegisterRegClass(Reg, VT);
1019          const TargetRegisterClass *DestRC = TRI->getCrossCopyRegClass(RC);
1020          if (!DestRC) {
1021            assert(false && "Don't know how to copy this physical register!");
1022            abort();
1023          }
1024          SmallVector<SUnit*, 2> Copies;
1025          InsertCCCopiesAndMoveSuccs(LRDef, Reg, DestRC, RC, Copies);
1026          DOUT << "Adding an edge from SU # " << TrySU->NodeNum
1027               << " to SU #" << Copies.front()->NodeNum << "\n";
1028          AddPred(TrySU, Copies.front(), true, true);
1029          NewDef = Copies.back();
1030        }
1031
1032        DOUT << "Adding an edge from SU # " << NewDef->NodeNum
1033             << " to SU #" << TrySU->NodeNum << "\n";
1034        LiveRegDefs[Reg] = NewDef;
1035        AddPred(NewDef, TrySU, true, true);
1036        TrySU->isAvailable = false;
1037        CurSU = NewDef;
1038      }
1039
1040      if (!CurSU) {
1041        assert(false && "Unable to resolve live physical register dependencies!");
1042        abort();
1043      }
1044    }
1045
1046    // Add the nodes that aren't ready back onto the available list.
1047    for (unsigned i = 0, e = NotReady.size(); i != e; ++i) {
1048      NotReady[i]->isPending = false;
1049      // May no longer be available due to backtracking.
1050      if (NotReady[i]->isAvailable)
1051        AvailableQueue->push(NotReady[i]);
1052    }
1053    NotReady.clear();
1054
1055    if (CurSU)
1056      ScheduleNodeBottomUp(CurSU, CurCycle);
1057    ++CurCycle;
1058  }
1059
1060  // Reverse the order if it is bottom up.
1061  std::reverse(Sequence.begin(), Sequence.end());
1062
1063#ifndef NDEBUG
1064  VerifySchedule(isBottomUp);
1065#endif
1066}
1067
1068//===----------------------------------------------------------------------===//
1069//  Top-Down Scheduling
1070//===----------------------------------------------------------------------===//
1071
1072/// ReleaseSucc - Decrement the NumPredsLeft count of a successor. Add it to
1073/// the AvailableQueue if the count reaches zero. Also update its cycle bound.
1074void ScheduleDAGRRList::ReleaseSucc(SUnit *SU, SUnit *SuccSU, bool isChain) {
1075  --SuccSU->NumPredsLeft;
1076
1077#ifndef NDEBUG
1078  if (SuccSU->NumPredsLeft < 0) {
1079    cerr << "*** Scheduling failed! ***\n";
1080    SuccSU->dump(this);
1081    cerr << " has been released too many times!\n";
1082    assert(0);
1083  }
1084#endif
1085
1086  // Compute how many cycles it will be before this actually becomes
1087  // available.  This is the max of the start time of all predecessors plus
1088  // their latencies.
1089  // If this is a token edge, we don't need to wait for the latency of the
1090  // preceeding instruction (e.g. a long-latency load) unless there is also
1091  // some other data dependence.
1092  unsigned PredDoneCycle = SU->Cycle;
1093  if (!isChain)
1094    PredDoneCycle += SU->Latency;
1095  else if (SU->Latency)
1096    PredDoneCycle += 1;
1097  SuccSU->CycleBound = std::max(SuccSU->CycleBound, PredDoneCycle);
1098
1099  if (SuccSU->NumPredsLeft == 0) {
1100    SuccSU->isAvailable = true;
1101    AvailableQueue->push(SuccSU);
1102  }
1103}
1104
1105/// ScheduleNodeTopDown - Add the node to the schedule. Decrement the pending
1106/// count of its successors. If a successor pending count is zero, add it to
1107/// the Available queue.
1108void ScheduleDAGRRList::ScheduleNodeTopDown(SUnit *SU, unsigned CurCycle) {
1109  DOUT << "*** Scheduling [" << CurCycle << "]: ";
1110  DEBUG(SU->dump(this));
1111
1112  SU->Cycle = CurCycle;
1113  Sequence.push_back(SU);
1114
1115  // Top down: release successors
1116  for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1117       I != E; ++I)
1118    ReleaseSucc(SU, I->Dep, I->isCtrl);
1119
1120  SU->isScheduled = true;
1121  AvailableQueue->ScheduledNode(SU);
1122}
1123
1124/// ListScheduleTopDown - The main loop of list scheduling for top-down
1125/// schedulers.
1126void ScheduleDAGRRList::ListScheduleTopDown() {
1127  unsigned CurCycle = 0;
1128
1129  // All leaves to Available queue.
1130  for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
1131    // It is available if it has no predecessors.
1132    if (SUnits[i].Preds.empty()) {
1133      AvailableQueue->push(&SUnits[i]);
1134      SUnits[i].isAvailable = true;
1135    }
1136  }
1137
1138  // While Available queue is not empty, grab the node with the highest
1139  // priority. If it is not ready put it back.  Schedule the node.
1140  std::vector<SUnit*> NotReady;
1141  Sequence.reserve(SUnits.size());
1142  while (!AvailableQueue->empty()) {
1143    SUnit *CurSU = AvailableQueue->pop();
1144    while (CurSU && CurSU->CycleBound > CurCycle) {
1145      NotReady.push_back(CurSU);
1146      CurSU = AvailableQueue->pop();
1147    }
1148
1149    // Add the nodes that aren't ready back onto the available list.
1150    AvailableQueue->push_all(NotReady);
1151    NotReady.clear();
1152
1153    if (CurSU)
1154      ScheduleNodeTopDown(CurSU, CurCycle);
1155    ++CurCycle;
1156  }
1157
1158#ifndef NDEBUG
1159  VerifySchedule(isBottomUp);
1160#endif
1161}
1162
1163
1164//===----------------------------------------------------------------------===//
1165//                RegReductionPriorityQueue Implementation
1166//===----------------------------------------------------------------------===//
1167//
1168// This is a SchedulingPriorityQueue that schedules using Sethi Ullman numbers
1169// to reduce register pressure.
1170//
1171namespace {
1172  template<class SF>
1173  class RegReductionPriorityQueue;
1174
1175  /// Sorting functions for the Available queue.
1176  struct bu_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1177    RegReductionPriorityQueue<bu_ls_rr_sort> *SPQ;
1178    bu_ls_rr_sort(RegReductionPriorityQueue<bu_ls_rr_sort> *spq) : SPQ(spq) {}
1179    bu_ls_rr_sort(const bu_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1180
1181    bool operator()(const SUnit* left, const SUnit* right) const;
1182  };
1183
1184  struct td_ls_rr_sort : public std::binary_function<SUnit*, SUnit*, bool> {
1185    RegReductionPriorityQueue<td_ls_rr_sort> *SPQ;
1186    td_ls_rr_sort(RegReductionPriorityQueue<td_ls_rr_sort> *spq) : SPQ(spq) {}
1187    td_ls_rr_sort(const td_ls_rr_sort &RHS) : SPQ(RHS.SPQ) {}
1188
1189    bool operator()(const SUnit* left, const SUnit* right) const;
1190  };
1191}  // end anonymous namespace
1192
1193static inline bool isCopyFromLiveIn(const SUnit *SU) {
1194  SDNode *N = SU->getNode();
1195  return N && N->getOpcode() == ISD::CopyFromReg &&
1196    N->getOperand(N->getNumOperands()-1).getValueType() != MVT::Flag;
1197}
1198
1199/// CalcNodeSethiUllmanNumber - Compute Sethi Ullman number.
1200/// Smaller number is the higher priority.
1201static unsigned
1202CalcNodeSethiUllmanNumber(const SUnit *SU, std::vector<unsigned> &SUNumbers) {
1203  unsigned &SethiUllmanNumber = SUNumbers[SU->NodeNum];
1204  if (SethiUllmanNumber != 0)
1205    return SethiUllmanNumber;
1206
1207  unsigned Extra = 0;
1208  for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1209       I != E; ++I) {
1210    if (I->isCtrl) continue;  // ignore chain preds
1211    SUnit *PredSU = I->Dep;
1212    unsigned PredSethiUllman = CalcNodeSethiUllmanNumber(PredSU, SUNumbers);
1213    if (PredSethiUllman > SethiUllmanNumber) {
1214      SethiUllmanNumber = PredSethiUllman;
1215      Extra = 0;
1216    } else if (PredSethiUllman == SethiUllmanNumber && !I->isCtrl)
1217      ++Extra;
1218  }
1219
1220  SethiUllmanNumber += Extra;
1221
1222  if (SethiUllmanNumber == 0)
1223    SethiUllmanNumber = 1;
1224
1225  return SethiUllmanNumber;
1226}
1227
1228namespace {
1229  template<class SF>
1230  class VISIBILITY_HIDDEN RegReductionPriorityQueue
1231   : public SchedulingPriorityQueue {
1232    PriorityQueue<SUnit*, std::vector<SUnit*>, SF> Queue;
1233    unsigned currentQueueId;
1234
1235  protected:
1236    // SUnits - The SUnits for the current graph.
1237    std::vector<SUnit> *SUnits;
1238
1239    const TargetInstrInfo *TII;
1240    const TargetRegisterInfo *TRI;
1241    ScheduleDAGRRList *scheduleDAG;
1242
1243    // SethiUllmanNumbers - The SethiUllman number for each node.
1244    std::vector<unsigned> SethiUllmanNumbers;
1245
1246  public:
1247    RegReductionPriorityQueue(const TargetInstrInfo *tii,
1248                              const TargetRegisterInfo *tri) :
1249    Queue(SF(this)), currentQueueId(0),
1250    TII(tii), TRI(tri), scheduleDAG(NULL) {}
1251
1252    void initNodes(std::vector<SUnit> &sunits) {
1253      SUnits = &sunits;
1254      // Add pseudo dependency edges for two-address nodes.
1255      AddPseudoTwoAddrDeps();
1256      // Calculate node priorities.
1257      CalculateSethiUllmanNumbers();
1258    }
1259
1260    void addNode(const SUnit *SU) {
1261      unsigned SUSize = SethiUllmanNumbers.size();
1262      if (SUnits->size() > SUSize)
1263        SethiUllmanNumbers.resize(SUSize*2, 0);
1264      CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1265    }
1266
1267    void updateNode(const SUnit *SU) {
1268      SethiUllmanNumbers[SU->NodeNum] = 0;
1269      CalcNodeSethiUllmanNumber(SU, SethiUllmanNumbers);
1270    }
1271
1272    void releaseState() {
1273      SUnits = 0;
1274      SethiUllmanNumbers.clear();
1275    }
1276
1277    unsigned getNodePriority(const SUnit *SU) const {
1278      assert(SU->NodeNum < SethiUllmanNumbers.size());
1279      unsigned Opc = SU->getNode() ? SU->getNode()->getOpcode() : 0;
1280      if (Opc == ISD::CopyFromReg && !isCopyFromLiveIn(SU))
1281        // CopyFromReg should be close to its def because it restricts
1282        // allocation choices. But if it is a livein then perhaps we want it
1283        // closer to its uses so it can be coalesced.
1284        return 0xffff;
1285      else if (Opc == ISD::TokenFactor || Opc == ISD::CopyToReg)
1286        // CopyToReg should be close to its uses to facilitate coalescing and
1287        // avoid spilling.
1288        return 0;
1289      else if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
1290               Opc == TargetInstrInfo::INSERT_SUBREG)
1291        // EXTRACT_SUBREG / INSERT_SUBREG should be close to its use to
1292        // facilitate coalescing.
1293        return 0;
1294      else if (SU->NumSuccs == 0)
1295        // If SU does not have a use, i.e. it doesn't produce a value that would
1296        // be consumed (e.g. store), then it terminates a chain of computation.
1297        // Give it a large SethiUllman number so it will be scheduled right
1298        // before its predecessors that it doesn't lengthen their live ranges.
1299        return 0xffff;
1300      else if (SU->NumPreds == 0)
1301        // If SU does not have a def, schedule it close to its uses because it
1302        // does not lengthen any live ranges.
1303        return 0;
1304      else
1305        return SethiUllmanNumbers[SU->NodeNum];
1306    }
1307
1308    unsigned size() const { return Queue.size(); }
1309
1310    bool empty() const { return Queue.empty(); }
1311
1312    void push(SUnit *U) {
1313      assert(!U->NodeQueueId && "Node in the queue already");
1314      U->NodeQueueId = ++currentQueueId;
1315      Queue.push(U);
1316    }
1317
1318    void push_all(const std::vector<SUnit *> &Nodes) {
1319      for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
1320        push(Nodes[i]);
1321    }
1322
1323    SUnit *pop() {
1324      if (empty()) return NULL;
1325      SUnit *V = Queue.top();
1326      Queue.pop();
1327      V->NodeQueueId = 0;
1328      return V;
1329    }
1330
1331    void remove(SUnit *SU) {
1332      assert(!Queue.empty() && "Queue is empty!");
1333      assert(SU->NodeQueueId != 0 && "Not in queue!");
1334      Queue.erase_one(SU);
1335      SU->NodeQueueId = 0;
1336    }
1337
1338    void setScheduleDAG(ScheduleDAGRRList *scheduleDag) {
1339      scheduleDAG = scheduleDag;
1340    }
1341
1342  protected:
1343    bool canClobber(const SUnit *SU, const SUnit *Op);
1344    void AddPseudoTwoAddrDeps();
1345    void CalculateSethiUllmanNumbers();
1346  };
1347
1348  typedef RegReductionPriorityQueue<bu_ls_rr_sort>
1349    BURegReductionPriorityQueue;
1350
1351  typedef RegReductionPriorityQueue<td_ls_rr_sort>
1352    TDRegReductionPriorityQueue;
1353}
1354
1355/// closestSucc - Returns the scheduled cycle of the successor which is
1356/// closet to the current cycle.
1357static unsigned closestSucc(const SUnit *SU) {
1358  unsigned MaxCycle = 0;
1359  for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1360       I != E; ++I) {
1361    unsigned Cycle = I->Dep->Cycle;
1362    // If there are bunch of CopyToRegs stacked up, they should be considered
1363    // to be at the same position.
1364    if (I->Dep->getNode() && I->Dep->getNode()->getOpcode() == ISD::CopyToReg)
1365      Cycle = closestSucc(I->Dep)+1;
1366    if (Cycle > MaxCycle)
1367      MaxCycle = Cycle;
1368  }
1369  return MaxCycle;
1370}
1371
1372/// calcMaxScratches - Returns an cost estimate of the worse case requirement
1373/// for scratch registers. Live-in operands and live-out results don't count
1374/// since they are "fixed".
1375static unsigned calcMaxScratches(const SUnit *SU) {
1376  unsigned Scratches = 0;
1377  for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
1378       I != E; ++I) {
1379    if (I->isCtrl) continue;  // ignore chain preds
1380    if (!I->Dep->getNode() || I->Dep->getNode()->getOpcode() != ISD::CopyFromReg)
1381      Scratches++;
1382  }
1383  for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1384       I != E; ++I) {
1385    if (I->isCtrl) continue;  // ignore chain succs
1386    if (!I->Dep->getNode() || I->Dep->getNode()->getOpcode() != ISD::CopyToReg)
1387      Scratches += 10;
1388  }
1389  return Scratches;
1390}
1391
1392// Bottom up
1393bool bu_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1394  unsigned LPriority = SPQ->getNodePriority(left);
1395  unsigned RPriority = SPQ->getNodePriority(right);
1396  if (LPriority != RPriority)
1397    return LPriority > RPriority;
1398
1399  // Try schedule def + use closer when Sethi-Ullman numbers are the same.
1400  // e.g.
1401  // t1 = op t2, c1
1402  // t3 = op t4, c2
1403  //
1404  // and the following instructions are both ready.
1405  // t2 = op c3
1406  // t4 = op c4
1407  //
1408  // Then schedule t2 = op first.
1409  // i.e.
1410  // t4 = op c4
1411  // t2 = op c3
1412  // t1 = op t2, c1
1413  // t3 = op t4, c2
1414  //
1415  // This creates more short live intervals.
1416  unsigned LDist = closestSucc(left);
1417  unsigned RDist = closestSucc(right);
1418  if (LDist != RDist)
1419    return LDist < RDist;
1420
1421  // Intuitively, it's good to push down instructions whose results are
1422  // liveout so their long live ranges won't conflict with other values
1423  // which are needed inside the BB. Further prioritize liveout instructions
1424  // by the number of operands which are calculated within the BB.
1425  unsigned LScratch = calcMaxScratches(left);
1426  unsigned RScratch = calcMaxScratches(right);
1427  if (LScratch != RScratch)
1428    return LScratch > RScratch;
1429
1430  if (left->Height != right->Height)
1431    return left->Height > right->Height;
1432
1433  if (left->Depth != right->Depth)
1434    return left->Depth < right->Depth;
1435
1436  if (left->CycleBound != right->CycleBound)
1437    return left->CycleBound > right->CycleBound;
1438
1439  assert(left->NodeQueueId && right->NodeQueueId &&
1440         "NodeQueueId cannot be zero");
1441  return (left->NodeQueueId > right->NodeQueueId);
1442}
1443
1444template<class SF>
1445bool
1446RegReductionPriorityQueue<SF>::canClobber(const SUnit *SU, const SUnit *Op) {
1447  if (SU->isTwoAddress) {
1448    unsigned Opc = SU->getNode()->getMachineOpcode();
1449    const TargetInstrDesc &TID = TII->get(Opc);
1450    unsigned NumRes = TID.getNumDefs();
1451    unsigned NumOps = TID.getNumOperands() - NumRes;
1452    for (unsigned i = 0; i != NumOps; ++i) {
1453      if (TID.getOperandConstraint(i+NumRes, TOI::TIED_TO) != -1) {
1454        SDNode *DU = SU->getNode()->getOperand(i).getNode();
1455        if (DU->getNodeId() != -1 &&
1456            Op->OrigNode == &(*SUnits)[DU->getNodeId()])
1457          return true;
1458      }
1459    }
1460  }
1461  return false;
1462}
1463
1464
1465/// hasCopyToRegUse - Return true if SU has a value successor that is a
1466/// CopyToReg node.
1467static bool hasCopyToRegUse(const SUnit *SU) {
1468  for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1469       I != E; ++I) {
1470    if (I->isCtrl) continue;
1471    const SUnit *SuccSU = I->Dep;
1472    if (SuccSU->getNode() && SuccSU->getNode()->getOpcode() == ISD::CopyToReg)
1473      return true;
1474  }
1475  return false;
1476}
1477
1478/// canClobberPhysRegDefs - True if SU would clobber one of SuccSU's
1479/// physical register defs.
1480static bool canClobberPhysRegDefs(const SUnit *SuccSU, const SUnit *SU,
1481                                  const TargetInstrInfo *TII,
1482                                  const TargetRegisterInfo *TRI) {
1483  SDNode *N = SuccSU->getNode();
1484  unsigned NumDefs = TII->get(N->getMachineOpcode()).getNumDefs();
1485  const unsigned *ImpDefs = TII->get(N->getMachineOpcode()).getImplicitDefs();
1486  assert(ImpDefs && "Caller should check hasPhysRegDefs");
1487  const unsigned *SUImpDefs =
1488    TII->get(SU->getNode()->getMachineOpcode()).getImplicitDefs();
1489  if (!SUImpDefs)
1490    return false;
1491  for (unsigned i = NumDefs, e = N->getNumValues(); i != e; ++i) {
1492    MVT VT = N->getValueType(i);
1493    if (VT == MVT::Flag || VT == MVT::Other)
1494      continue;
1495    if (!N->hasAnyUseOfValue(i))
1496      continue;
1497    unsigned Reg = ImpDefs[i - NumDefs];
1498    for (;*SUImpDefs; ++SUImpDefs) {
1499      unsigned SUReg = *SUImpDefs;
1500      if (TRI->regsOverlap(Reg, SUReg))
1501        return true;
1502    }
1503  }
1504  return false;
1505}
1506
1507/// AddPseudoTwoAddrDeps - If two nodes share an operand and one of them uses
1508/// it as a def&use operand. Add a pseudo control edge from it to the other
1509/// node (if it won't create a cycle) so the two-address one will be scheduled
1510/// first (lower in the schedule). If both nodes are two-address, favor the
1511/// one that has a CopyToReg use (more likely to be a loop induction update).
1512/// If both are two-address, but one is commutable while the other is not
1513/// commutable, favor the one that's not commutable.
1514template<class SF>
1515void RegReductionPriorityQueue<SF>::AddPseudoTwoAddrDeps() {
1516  for (unsigned i = 0, e = SUnits->size(); i != e; ++i) {
1517    SUnit *SU = &(*SUnits)[i];
1518    if (!SU->isTwoAddress)
1519      continue;
1520
1521    SDNode *Node = SU->getNode();
1522    if (!Node || !Node->isMachineOpcode() || SU->getNode()->getFlaggedNode())
1523      continue;
1524
1525    unsigned Opc = Node->getMachineOpcode();
1526    const TargetInstrDesc &TID = TII->get(Opc);
1527    unsigned NumRes = TID.getNumDefs();
1528    unsigned NumOps = TID.getNumOperands() - NumRes;
1529    for (unsigned j = 0; j != NumOps; ++j) {
1530      if (TID.getOperandConstraint(j+NumRes, TOI::TIED_TO) == -1)
1531        continue;
1532      SDNode *DU = SU->getNode()->getOperand(j).getNode();
1533      if (DU->getNodeId() == -1)
1534        continue;
1535      const SUnit *DUSU = &(*SUnits)[DU->getNodeId()];
1536      if (!DUSU) continue;
1537      for (SUnit::const_succ_iterator I = DUSU->Succs.begin(),
1538           E = DUSU->Succs.end(); I != E; ++I) {
1539        if (I->isCtrl) continue;
1540        SUnit *SuccSU = I->Dep;
1541        if (SuccSU == SU)
1542          continue;
1543        // Be conservative. Ignore if nodes aren't at roughly the same
1544        // depth and height.
1545        if (SuccSU->Height < SU->Height && (SU->Height - SuccSU->Height) > 1)
1546          continue;
1547        if (!SuccSU->getNode() || !SuccSU->getNode()->isMachineOpcode())
1548          continue;
1549        // Don't constrain nodes with physical register defs if the
1550        // predecessor can clobber them.
1551        if (SuccSU->hasPhysRegDefs) {
1552          if (canClobberPhysRegDefs(SuccSU, SU, TII, TRI))
1553            continue;
1554        }
1555        // Don't constraint extract_subreg / insert_subreg these may be
1556        // coalesced away. We don't them close to their uses.
1557        unsigned SuccOpc = SuccSU->getNode()->getMachineOpcode();
1558        if (SuccOpc == TargetInstrInfo::EXTRACT_SUBREG ||
1559            SuccOpc == TargetInstrInfo::INSERT_SUBREG)
1560          continue;
1561        if ((!canClobber(SuccSU, DUSU) ||
1562             (hasCopyToRegUse(SU) && !hasCopyToRegUse(SuccSU)) ||
1563             (!SU->isCommutable && SuccSU->isCommutable)) &&
1564            !scheduleDAG->IsReachable(SuccSU, SU)) {
1565          DOUT << "Adding an edge from SU # " << SU->NodeNum
1566               << " to SU #" << SuccSU->NodeNum << "\n";
1567          scheduleDAG->AddPred(SU, SuccSU, true, true);
1568        }
1569      }
1570    }
1571  }
1572}
1573
1574/// CalculateSethiUllmanNumbers - Calculate Sethi-Ullman numbers of all
1575/// scheduling units.
1576template<class SF>
1577void RegReductionPriorityQueue<SF>::CalculateSethiUllmanNumbers() {
1578  SethiUllmanNumbers.assign(SUnits->size(), 0);
1579
1580  for (unsigned i = 0, e = SUnits->size(); i != e; ++i)
1581    CalcNodeSethiUllmanNumber(&(*SUnits)[i], SethiUllmanNumbers);
1582}
1583
1584/// LimitedSumOfUnscheduledPredsOfSuccs - Compute the sum of the unscheduled
1585/// predecessors of the successors of the SUnit SU. Stop when the provided
1586/// limit is exceeded.
1587static unsigned LimitedSumOfUnscheduledPredsOfSuccs(const SUnit *SU,
1588                                                    unsigned Limit) {
1589  unsigned Sum = 0;
1590  for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
1591       I != E; ++I) {
1592    const SUnit *SuccSU = I->Dep;
1593    for (SUnit::const_pred_iterator II = SuccSU->Preds.begin(),
1594         EE = SuccSU->Preds.end(); II != EE; ++II) {
1595      SUnit *PredSU = II->Dep;
1596      if (!PredSU->isScheduled)
1597        if (++Sum > Limit)
1598          return Sum;
1599    }
1600  }
1601  return Sum;
1602}
1603
1604
1605// Top down
1606bool td_ls_rr_sort::operator()(const SUnit *left, const SUnit *right) const {
1607  unsigned LPriority = SPQ->getNodePriority(left);
1608  unsigned RPriority = SPQ->getNodePriority(right);
1609  bool LIsTarget = left->getNode() && left->getNode()->isMachineOpcode();
1610  bool RIsTarget = right->getNode() && right->getNode()->isMachineOpcode();
1611  bool LIsFloater = LIsTarget && left->NumPreds == 0;
1612  bool RIsFloater = RIsTarget && right->NumPreds == 0;
1613  unsigned LBonus = (LimitedSumOfUnscheduledPredsOfSuccs(left,1) == 1) ? 2 : 0;
1614  unsigned RBonus = (LimitedSumOfUnscheduledPredsOfSuccs(right,1) == 1) ? 2 : 0;
1615
1616  if (left->NumSuccs == 0 && right->NumSuccs != 0)
1617    return false;
1618  else if (left->NumSuccs != 0 && right->NumSuccs == 0)
1619    return true;
1620
1621  if (LIsFloater)
1622    LBonus -= 2;
1623  if (RIsFloater)
1624    RBonus -= 2;
1625  if (left->NumSuccs == 1)
1626    LBonus += 2;
1627  if (right->NumSuccs == 1)
1628    RBonus += 2;
1629
1630  if (LPriority+LBonus != RPriority+RBonus)
1631    return LPriority+LBonus < RPriority+RBonus;
1632
1633  if (left->Depth != right->Depth)
1634    return left->Depth < right->Depth;
1635
1636  if (left->NumSuccsLeft != right->NumSuccsLeft)
1637    return left->NumSuccsLeft > right->NumSuccsLeft;
1638
1639  if (left->CycleBound != right->CycleBound)
1640    return left->CycleBound > right->CycleBound;
1641
1642  assert(left->NodeQueueId && right->NodeQueueId &&
1643         "NodeQueueId cannot be zero");
1644  return (left->NodeQueueId > right->NodeQueueId);
1645}
1646
1647//===----------------------------------------------------------------------===//
1648//                         Public Constructor Functions
1649//===----------------------------------------------------------------------===//
1650
1651llvm::ScheduleDAG* llvm::createBURRListDAGScheduler(SelectionDAGISel *IS,
1652                                                    SelectionDAG *DAG,
1653                                                    const TargetMachine *TM,
1654                                                    MachineBasicBlock *BB,
1655                                                    bool) {
1656  const TargetInstrInfo *TII = TM->getInstrInfo();
1657  const TargetRegisterInfo *TRI = TM->getRegisterInfo();
1658
1659  BURegReductionPriorityQueue *PQ = new BURegReductionPriorityQueue(TII, TRI);
1660
1661  ScheduleDAGRRList *SD =
1662    new ScheduleDAGRRList(DAG, BB, *TM, true, PQ);
1663  PQ->setScheduleDAG(SD);
1664  return SD;
1665}
1666
1667llvm::ScheduleDAG* llvm::createTDRRListDAGScheduler(SelectionDAGISel *IS,
1668                                                    SelectionDAG *DAG,
1669                                                    const TargetMachine *TM,
1670                                                    MachineBasicBlock *BB,
1671                                                    bool) {
1672  const TargetInstrInfo *TII = TM->getInstrInfo();
1673  const TargetRegisterInfo *TRI = TM->getRegisterInfo();
1674
1675  TDRegReductionPriorityQueue *PQ = new TDRegReductionPriorityQueue(TII, TRI);
1676
1677  ScheduleDAGRRList *SD = new ScheduleDAGRRList(DAG, BB, *TM, false, PQ);
1678  PQ->setScheduleDAG(SD);
1679  return SD;
1680}
1681