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