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