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