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