ScheduleDAG.cpp revision d04a8d4b33ff316ca4cf961e06c9e312eff8e64f
1//===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
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 the ScheduleDAG class, which is a base class used by
11// scheduling implementation classes.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "pre-RA-sched"
16#include "llvm/CodeGen/ScheduleDAG.h"
17#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
18#include "llvm/CodeGen/SelectionDAGNodes.h"
19#include "llvm/Support/CommandLine.h"
20#include "llvm/Support/Debug.h"
21#include "llvm/Support/raw_ostream.h"
22#include "llvm/Target/TargetInstrInfo.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetRegisterInfo.h"
25#include <climits>
26using namespace llvm;
27
28#ifndef NDEBUG
29static cl::opt<bool> StressSchedOpt(
30  "stress-sched", cl::Hidden, cl::init(false),
31  cl::desc("Stress test instruction scheduling"));
32#endif
33
34void SchedulingPriorityQueue::anchor() { }
35
36ScheduleDAG::ScheduleDAG(MachineFunction &mf)
37  : TM(mf.getTarget()),
38    TII(TM.getInstrInfo()),
39    TRI(TM.getRegisterInfo()),
40    MF(mf), MRI(mf.getRegInfo()),
41    EntrySU(), ExitSU() {
42#ifndef NDEBUG
43  StressSched = StressSchedOpt;
44#endif
45}
46
47ScheduleDAG::~ScheduleDAG() {}
48
49/// Clear the DAG state (e.g. between scheduling regions).
50void ScheduleDAG::clearDAG() {
51  SUnits.clear();
52  EntrySU = SUnit();
53  ExitSU = SUnit();
54}
55
56/// getInstrDesc helper to handle SDNodes.
57const MCInstrDesc *ScheduleDAG::getNodeDesc(const SDNode *Node) const {
58  if (!Node || !Node->isMachineOpcode()) return NULL;
59  return &TII->get(Node->getMachineOpcode());
60}
61
62/// addPred - This adds the specified edge as a pred of the current node if
63/// not already.  It also adds the current node as a successor of the
64/// specified node.
65bool SUnit::addPred(const SDep &D, bool Required) {
66  // If this node already has this depenence, don't add a redundant one.
67  for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
68       I != E; ++I) {
69    // Zero-latency weak edges may be added purely for heuristic ordering. Don't
70    // add them if another kind of edge already exists.
71    if (!Required && I->getSUnit() == D.getSUnit())
72      return false;
73    if (I->overlaps(D)) {
74      // Extend the latency if needed. Equivalent to removePred(I) + addPred(D).
75      if (I->getLatency() < D.getLatency()) {
76        SUnit *PredSU = I->getSUnit();
77        // Find the corresponding successor in N.
78        SDep ForwardD = *I;
79        ForwardD.setSUnit(this);
80        for (SmallVector<SDep, 4>::iterator II = PredSU->Succs.begin(),
81               EE = PredSU->Succs.end(); II != EE; ++II) {
82          if (*II == ForwardD) {
83            II->setLatency(D.getLatency());
84            break;
85          }
86        }
87        I->setLatency(D.getLatency());
88      }
89      return false;
90    }
91  }
92  // Now add a corresponding succ to N.
93  SDep P = D;
94  P.setSUnit(this);
95  SUnit *N = D.getSUnit();
96  // Update the bookkeeping.
97  if (D.getKind() == SDep::Data) {
98    assert(NumPreds < UINT_MAX && "NumPreds will overflow!");
99    assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!");
100    ++NumPreds;
101    ++N->NumSuccs;
102  }
103  if (!N->isScheduled) {
104    if (D.isWeak()) {
105      ++WeakPredsLeft;
106    }
107    else {
108      assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
109      ++NumPredsLeft;
110    }
111  }
112  if (!isScheduled) {
113    if (D.isWeak()) {
114      ++N->WeakSuccsLeft;
115    }
116    else {
117      assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
118      ++N->NumSuccsLeft;
119    }
120  }
121  Preds.push_back(D);
122  N->Succs.push_back(P);
123  if (P.getLatency() != 0) {
124    this->setDepthDirty();
125    N->setHeightDirty();
126  }
127  return true;
128}
129
130/// removePred - This removes the specified edge as a pred of the current
131/// node if it exists.  It also removes the current node as a successor of
132/// the specified node.
133void SUnit::removePred(const SDep &D) {
134  // Find the matching predecessor.
135  for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
136       I != E; ++I)
137    if (*I == D) {
138      bool FoundSucc = false;
139      // Find the corresponding successor in N.
140      SDep P = D;
141      P.setSUnit(this);
142      SUnit *N = D.getSUnit();
143      for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
144             EE = N->Succs.end(); II != EE; ++II)
145        if (*II == P) {
146          FoundSucc = true;
147          N->Succs.erase(II);
148          break;
149        }
150      assert(FoundSucc && "Mismatching preds / succs lists!");
151      (void)FoundSucc;
152      Preds.erase(I);
153      // Update the bookkeeping.
154      if (P.getKind() == SDep::Data) {
155        assert(NumPreds > 0 && "NumPreds will underflow!");
156        assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
157        --NumPreds;
158        --N->NumSuccs;
159      }
160      if (!N->isScheduled) {
161        if (D.isWeak())
162          --WeakPredsLeft;
163        else {
164          assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
165          --NumPredsLeft;
166        }
167      }
168      if (!isScheduled) {
169        if (D.isWeak())
170          --N->WeakSuccsLeft;
171        else {
172          assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
173          --N->NumSuccsLeft;
174        }
175      }
176      if (P.getLatency() != 0) {
177        this->setDepthDirty();
178        N->setHeightDirty();
179      }
180      return;
181    }
182}
183
184void SUnit::setDepthDirty() {
185  if (!isDepthCurrent) return;
186  SmallVector<SUnit*, 8> WorkList;
187  WorkList.push_back(this);
188  do {
189    SUnit *SU = WorkList.pop_back_val();
190    SU->isDepthCurrent = false;
191    for (SUnit::const_succ_iterator I = SU->Succs.begin(),
192         E = SU->Succs.end(); I != E; ++I) {
193      SUnit *SuccSU = I->getSUnit();
194      if (SuccSU->isDepthCurrent)
195        WorkList.push_back(SuccSU);
196    }
197  } while (!WorkList.empty());
198}
199
200void SUnit::setHeightDirty() {
201  if (!isHeightCurrent) return;
202  SmallVector<SUnit*, 8> WorkList;
203  WorkList.push_back(this);
204  do {
205    SUnit *SU = WorkList.pop_back_val();
206    SU->isHeightCurrent = false;
207    for (SUnit::const_pred_iterator I = SU->Preds.begin(),
208         E = SU->Preds.end(); I != E; ++I) {
209      SUnit *PredSU = I->getSUnit();
210      if (PredSU->isHeightCurrent)
211        WorkList.push_back(PredSU);
212    }
213  } while (!WorkList.empty());
214}
215
216/// setDepthToAtLeast - Update this node's successors to reflect the
217/// fact that this node's depth just increased.
218///
219void SUnit::setDepthToAtLeast(unsigned NewDepth) {
220  if (NewDepth <= getDepth())
221    return;
222  setDepthDirty();
223  Depth = NewDepth;
224  isDepthCurrent = true;
225}
226
227/// setHeightToAtLeast - Update this node's predecessors to reflect the
228/// fact that this node's height just increased.
229///
230void SUnit::setHeightToAtLeast(unsigned NewHeight) {
231  if (NewHeight <= getHeight())
232    return;
233  setHeightDirty();
234  Height = NewHeight;
235  isHeightCurrent = true;
236}
237
238/// ComputeDepth - Calculate the maximal path from the node to the exit.
239///
240void SUnit::ComputeDepth() {
241  SmallVector<SUnit*, 8> WorkList;
242  WorkList.push_back(this);
243  do {
244    SUnit *Cur = WorkList.back();
245
246    bool Done = true;
247    unsigned MaxPredDepth = 0;
248    for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
249         E = Cur->Preds.end(); I != E; ++I) {
250      SUnit *PredSU = I->getSUnit();
251      if (PredSU->isDepthCurrent)
252        MaxPredDepth = std::max(MaxPredDepth,
253                                PredSU->Depth + I->getLatency());
254      else {
255        Done = false;
256        WorkList.push_back(PredSU);
257      }
258    }
259
260    if (Done) {
261      WorkList.pop_back();
262      if (MaxPredDepth != Cur->Depth) {
263        Cur->setDepthDirty();
264        Cur->Depth = MaxPredDepth;
265      }
266      Cur->isDepthCurrent = true;
267    }
268  } while (!WorkList.empty());
269}
270
271/// ComputeHeight - Calculate the maximal path from the node to the entry.
272///
273void SUnit::ComputeHeight() {
274  SmallVector<SUnit*, 8> WorkList;
275  WorkList.push_back(this);
276  do {
277    SUnit *Cur = WorkList.back();
278
279    bool Done = true;
280    unsigned MaxSuccHeight = 0;
281    for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
282         E = Cur->Succs.end(); I != E; ++I) {
283      SUnit *SuccSU = I->getSUnit();
284      if (SuccSU->isHeightCurrent)
285        MaxSuccHeight = std::max(MaxSuccHeight,
286                                 SuccSU->Height + I->getLatency());
287      else {
288        Done = false;
289        WorkList.push_back(SuccSU);
290      }
291    }
292
293    if (Done) {
294      WorkList.pop_back();
295      if (MaxSuccHeight != Cur->Height) {
296        Cur->setHeightDirty();
297        Cur->Height = MaxSuccHeight;
298      }
299      Cur->isHeightCurrent = true;
300    }
301  } while (!WorkList.empty());
302}
303
304#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
305/// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
306/// a group of nodes flagged together.
307void SUnit::dump(const ScheduleDAG *G) const {
308  dbgs() << "SU(" << NodeNum << "): ";
309  G->dumpNode(this);
310}
311
312void SUnit::dumpAll(const ScheduleDAG *G) const {
313  dump(G);
314
315  dbgs() << "  # preds left       : " << NumPredsLeft << "\n";
316  dbgs() << "  # succs left       : " << NumSuccsLeft << "\n";
317  if (WeakPredsLeft)
318    dbgs() << "  # weak preds left  : " << WeakPredsLeft << "\n";
319  if (WeakSuccsLeft)
320    dbgs() << "  # weak succs left  : " << WeakSuccsLeft << "\n";
321  dbgs() << "  # rdefs left       : " << NumRegDefsLeft << "\n";
322  dbgs() << "  Latency            : " << Latency << "\n";
323  dbgs() << "  Depth              : " << Depth << "\n";
324  dbgs() << "  Height             : " << Height << "\n";
325
326  if (Preds.size() != 0) {
327    dbgs() << "  Predecessors:\n";
328    for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
329         I != E; ++I) {
330      dbgs() << "   ";
331      switch (I->getKind()) {
332      case SDep::Data:        dbgs() << "val "; break;
333      case SDep::Anti:        dbgs() << "anti"; break;
334      case SDep::Output:      dbgs() << "out "; break;
335      case SDep::Order:       dbgs() << "ch  "; break;
336      }
337      dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
338      if (I->isArtificial())
339        dbgs() << " *";
340      dbgs() << ": Latency=" << I->getLatency();
341      if (I->isAssignedRegDep())
342        dbgs() << " Reg=" << PrintReg(I->getReg(), G->TRI);
343      dbgs() << "\n";
344    }
345  }
346  if (Succs.size() != 0) {
347    dbgs() << "  Successors:\n";
348    for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
349         I != E; ++I) {
350      dbgs() << "   ";
351      switch (I->getKind()) {
352      case SDep::Data:        dbgs() << "val "; break;
353      case SDep::Anti:        dbgs() << "anti"; break;
354      case SDep::Output:      dbgs() << "out "; break;
355      case SDep::Order:       dbgs() << "ch  "; break;
356      }
357      dbgs() << "SU(" << I->getSUnit()->NodeNum << ")";
358      if (I->isArtificial())
359        dbgs() << " *";
360      dbgs() << ": Latency=" << I->getLatency();
361      dbgs() << "\n";
362    }
363  }
364  dbgs() << "\n";
365}
366#endif
367
368#ifndef NDEBUG
369/// VerifyScheduledDAG - Verify that all SUnits were scheduled and that
370/// their state is consistent. Return the number of scheduled nodes.
371///
372unsigned ScheduleDAG::VerifyScheduledDAG(bool isBottomUp) {
373  bool AnyNotSched = false;
374  unsigned DeadNodes = 0;
375  for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
376    if (!SUnits[i].isScheduled) {
377      if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
378        ++DeadNodes;
379        continue;
380      }
381      if (!AnyNotSched)
382        dbgs() << "*** Scheduling failed! ***\n";
383      SUnits[i].dump(this);
384      dbgs() << "has not been scheduled!\n";
385      AnyNotSched = true;
386    }
387    if (SUnits[i].isScheduled &&
388        (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
389          unsigned(INT_MAX)) {
390      if (!AnyNotSched)
391        dbgs() << "*** Scheduling failed! ***\n";
392      SUnits[i].dump(this);
393      dbgs() << "has an unexpected "
394           << (isBottomUp ? "Height" : "Depth") << " value!\n";
395      AnyNotSched = true;
396    }
397    if (isBottomUp) {
398      if (SUnits[i].NumSuccsLeft != 0) {
399        if (!AnyNotSched)
400          dbgs() << "*** Scheduling failed! ***\n";
401        SUnits[i].dump(this);
402        dbgs() << "has successors left!\n";
403        AnyNotSched = true;
404      }
405    } else {
406      if (SUnits[i].NumPredsLeft != 0) {
407        if (!AnyNotSched)
408          dbgs() << "*** Scheduling failed! ***\n";
409        SUnits[i].dump(this);
410        dbgs() << "has predecessors left!\n";
411        AnyNotSched = true;
412      }
413    }
414  }
415  assert(!AnyNotSched);
416  return SUnits.size() - DeadNodes;
417}
418#endif
419
420/// InitDAGTopologicalSorting - create the initial topological
421/// ordering from the DAG to be scheduled.
422///
423/// The idea of the algorithm is taken from
424/// "Online algorithms for managing the topological order of
425/// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
426/// This is the MNR algorithm, which was first introduced by
427/// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
428/// "Maintaining a topological order under edge insertions".
429///
430/// Short description of the algorithm:
431///
432/// Topological ordering, ord, of a DAG maps each node to a topological
433/// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
434///
435/// This means that if there is a path from the node X to the node Z,
436/// then ord(X) < ord(Z).
437///
438/// This property can be used to check for reachability of nodes:
439/// if Z is reachable from X, then an insertion of the edge Z->X would
440/// create a cycle.
441///
442/// The algorithm first computes a topological ordering for the DAG by
443/// initializing the Index2Node and Node2Index arrays and then tries to keep
444/// the ordering up-to-date after edge insertions by reordering the DAG.
445///
446/// On insertion of the edge X->Y, the algorithm first marks by calling DFS
447/// the nodes reachable from Y, and then shifts them using Shift to lie
448/// immediately after X in Index2Node.
449void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
450  unsigned DAGSize = SUnits.size();
451  std::vector<SUnit*> WorkList;
452  WorkList.reserve(DAGSize);
453
454  Index2Node.resize(DAGSize);
455  Node2Index.resize(DAGSize);
456
457  // Initialize the data structures.
458  if (ExitSU)
459    WorkList.push_back(ExitSU);
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    // Temporarily use the Node2Index array as scratch space for degree counts.
465    Node2Index[NodeNum] = Degree;
466
467    // Is it a node without dependencies?
468    if (Degree == 0) {
469      assert(SU->Succs.empty() && "SUnit should have no successors");
470      // Collect leaf nodes.
471      WorkList.push_back(SU);
472    }
473  }
474
475  int Id = DAGSize;
476  while (!WorkList.empty()) {
477    SUnit *SU = WorkList.back();
478    WorkList.pop_back();
479    if (SU->NodeNum < DAGSize)
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->getSUnit();
484      if (SU->NodeNum < DAGSize && !--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->getSUnit()->NodeNum] &&
500      "Wrong topological sorting");
501    }
502  }
503#endif
504}
505
506/// AddPred - Updates the topological ordering to accommodate an edge
507/// to be added from SUnit X to SUnit Y.
508void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
509  int UpperBound, LowerBound;
510  LowerBound = Node2Index[Y->NodeNum];
511  UpperBound = Node2Index[X->NodeNum];
512  bool HasLoop = false;
513  // Is Ord(X) < Ord(Y) ?
514  if (LowerBound < UpperBound) {
515    // Update the topological order.
516    Visited.reset();
517    DFS(Y, UpperBound, HasLoop);
518    assert(!HasLoop && "Inserted edge creates a loop!");
519    // Recompute topological indexes.
520    Shift(Visited, LowerBound, UpperBound);
521  }
522}
523
524/// RemovePred - Updates the topological ordering to accommodate an
525/// an edge to be removed from the specified node N from the predecessors
526/// of the current node M.
527void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
528  // InitDAGTopologicalSorting();
529}
530
531/// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
532/// all nodes affected by the edge insertion. These nodes will later get new
533/// topological indexes by means of the Shift method.
534void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
535                                     bool &HasLoop) {
536  std::vector<const SUnit*> WorkList;
537  WorkList.reserve(SUnits.size());
538
539  WorkList.push_back(SU);
540  do {
541    SU = WorkList.back();
542    WorkList.pop_back();
543    Visited.set(SU->NodeNum);
544    for (int I = SU->Succs.size()-1; I >= 0; --I) {
545      unsigned s = SU->Succs[I].getSUnit()->NodeNum;
546      // Edges to non-SUnits are allowed but ignored (e.g. ExitSU).
547      if (s >= Node2Index.size())
548        continue;
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].getSUnit());
556      }
557    }
558  } while (!WorkList.empty());
559}
560
561/// Shift - Renumber the nodes so that the topological ordering is
562/// preserved.
563void ScheduleDAGTopologicalSort::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 to TargetSU from SU will
590/// create a cycle. If so, it is not safe to call AddPred(TargetSU, SU).
591bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *TargetSU, SUnit *SU) {
592  // Is SU reachable from TargetSU via successor edges?
593  if (IsReachable(SU, TargetSU))
594    return true;
595  for (SUnit::pred_iterator
596         I = TargetSU->Preds.begin(), E = TargetSU->Preds.end(); I != E; ++I)
597    if (I->isAssignedRegDep() &&
598        IsReachable(SU, I->getSUnit()))
599      return true;
600  return false;
601}
602
603/// IsReachable - Checks if SU is reachable from TargetSU.
604bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
605                                             const SUnit *TargetSU) {
606  // If insertion of the edge SU->TargetSU would create a cycle
607  // then there is a path from TargetSU to SU.
608  int UpperBound, LowerBound;
609  LowerBound = Node2Index[TargetSU->NodeNum];
610  UpperBound = Node2Index[SU->NodeNum];
611  bool HasLoop = false;
612  // Is Ord(TargetSU) < Ord(SU) ?
613  if (LowerBound < UpperBound) {
614    Visited.reset();
615    // There may be a path from TargetSU to SU. Check for it.
616    DFS(TargetSU, UpperBound, HasLoop);
617  }
618  return HasLoop;
619}
620
621/// Allocate - assign the topological index to the node n.
622void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
623  Node2Index[n] = index;
624  Index2Node[index] = n;
625}
626
627ScheduleDAGTopologicalSort::
628ScheduleDAGTopologicalSort(std::vector<SUnit> &sunits, SUnit *exitsu)
629  : SUnits(sunits), ExitSU(exitsu) {}
630
631ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}
632