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