some random notes.
[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 /// CalculateDepths - compute depths using algorithms for the longest
37 /// paths in the DAG
38 void ScheduleDAG::CalculateDepths() {
39   unsigned DAGSize = SUnits.size();
40   std::vector<SUnit*> WorkList;
41   WorkList.reserve(DAGSize);
42
43   // Initialize the data structures
44   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
45     SUnit *SU = &SUnits[i];
46     unsigned Degree = SU->Preds.size();
47     // Temporarily use the Depth field as scratch space for the degree count.
48     SU->Depth = Degree;
49
50     // Is it a node without dependencies?
51     if (Degree == 0) {
52         assert(SU->Preds.empty() && "SUnit should have no predecessors");
53         // Collect leaf nodes
54         WorkList.push_back(SU);
55     }
56   }
57
58   // Process nodes in the topological order
59   while (!WorkList.empty()) {
60     SUnit *SU = WorkList.back();
61     WorkList.pop_back();
62     unsigned SUDepth = 0;
63
64     // Use dynamic programming:
65     // When current node is being processed, all of its dependencies
66     // are already processed.
67     // So, just iterate over all predecessors and take the longest path
68     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
69          I != E; ++I) {
70       unsigned PredDepth = I->Dep->Depth;
71       if (PredDepth+1 > SUDepth) {
72           SUDepth = PredDepth + 1;
73       }
74     }
75
76     SU->Depth = SUDepth;
77
78     // Update degrees of all nodes depending on current SUnit
79     for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
80          I != E; ++I) {
81       SUnit *SU = I->Dep;
82       if (!--SU->Depth)
83         // If all dependencies of the node are processed already,
84         // then the longest path for the node can be computed now
85         WorkList.push_back(SU);
86     }
87   }
88 }
89
90 /// CalculateHeights - compute heights using algorithms for the longest
91 /// paths in the DAG
92 void ScheduleDAG::CalculateHeights() {
93   unsigned DAGSize = SUnits.size();
94   std::vector<SUnit*> WorkList;
95   WorkList.reserve(DAGSize);
96
97   // Initialize the data structures
98   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
99     SUnit *SU = &SUnits[i];
100     unsigned Degree = SU->Succs.size();
101     // Temporarily use the Height field as scratch space for the degree count.
102     SU->Height = Degree;
103
104     // Is it a node without dependencies?
105     if (Degree == 0) {
106         assert(SU->Succs.empty() && "Something wrong");
107         assert(WorkList.empty() && "Should be empty");
108         // Collect leaf nodes
109         WorkList.push_back(SU);
110     }
111   }
112
113   // Process nodes in the topological order
114   while (!WorkList.empty()) {
115     SUnit *SU = WorkList.back();
116     WorkList.pop_back();
117     unsigned SUHeight = 0;
118
119     // Use dynamic programming:
120     // When current node is being processed, all of its dependencies
121     // are already processed.
122     // So, just iterate over all successors and take the longest path
123     for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
124          I != E; ++I) {
125       unsigned SuccHeight = I->Dep->Height;
126       if (SuccHeight+1 > SUHeight) {
127           SUHeight = SuccHeight + 1;
128       }
129     }
130
131     SU->Height = SUHeight;
132
133     // Update degrees of all nodes depending on current SUnit
134     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
135          I != E; ++I) {
136       SUnit *SU = I->Dep;
137       if (!--SU->Height)
138         // If all dependencies of the node are processed already,
139         // then the longest path for the node can be computed now
140         WorkList.push_back(SU);
141     }
142   }
143 }
144
145 /// dump - dump the schedule.
146 void ScheduleDAG::dumpSchedule() const {
147   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
148     if (SUnit *SU = Sequence[i])
149       SU->dump(this);
150     else
151       cerr << "**** NOOP ****\n";
152   }
153 }
154
155
156 /// Run - perform scheduling.
157 ///
158 void ScheduleDAG::Run() {
159   Schedule();
160   
161   DOUT << "*** Final schedule ***\n";
162   DEBUG(dumpSchedule());
163   DOUT << "\n";
164 }
165
166 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
167 /// a group of nodes flagged together.
168 void SUnit::dump(const ScheduleDAG *G) const {
169   cerr << "SU(" << NodeNum << "): ";
170   G->dumpNode(this);
171 }
172
173 void SUnit::dumpAll(const ScheduleDAG *G) const {
174   dump(G);
175
176   cerr << "  # preds left       : " << NumPredsLeft << "\n";
177   cerr << "  # succs left       : " << NumSuccsLeft << "\n";
178   cerr << "  Latency            : " << Latency << "\n";
179   cerr << "  Depth              : " << Depth << "\n";
180   cerr << "  Height             : " << Height << "\n";
181
182   if (Preds.size() != 0) {
183     cerr << "  Predecessors:\n";
184     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
185          I != E; ++I) {
186       if (I->isCtrl)
187         cerr << "   ch  #";
188       else
189         cerr << "   val #";
190       cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
191       if (I->isArtificial)
192         cerr << " *";
193       cerr << "\n";
194     }
195   }
196   if (Succs.size() != 0) {
197     cerr << "  Successors:\n";
198     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
199          I != E; ++I) {
200       if (I->isCtrl)
201         cerr << "   ch  #";
202       else
203         cerr << "   val #";
204       cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
205       if (I->isArtificial)
206         cerr << " *";
207       cerr << "\n";
208     }
209   }
210   cerr << "\n";
211 }
212
213 #ifndef NDEBUG
214 /// VerifySchedule - Verify that all SUnits were scheduled and that
215 /// their state is consistent.
216 ///
217 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
218   bool AnyNotSched = false;
219   unsigned DeadNodes = 0;
220   unsigned Noops = 0;
221   for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
222     if (!SUnits[i].isScheduled) {
223       if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
224         ++DeadNodes;
225         continue;
226       }
227       if (!AnyNotSched)
228         cerr << "*** Scheduling failed! ***\n";
229       SUnits[i].dump(this);
230       cerr << "has not been scheduled!\n";
231       AnyNotSched = true;
232     }
233     if (SUnits[i].isScheduled && SUnits[i].Cycle > (unsigned)INT_MAX) {
234       if (!AnyNotSched)
235         cerr << "*** Scheduling failed! ***\n";
236       SUnits[i].dump(this);
237       cerr << "has an unexpected Cycle value!\n";
238       AnyNotSched = true;
239     }
240     if (isBottomUp) {
241       if (SUnits[i].NumSuccsLeft != 0) {
242         if (!AnyNotSched)
243           cerr << "*** Scheduling failed! ***\n";
244         SUnits[i].dump(this);
245         cerr << "has successors left!\n";
246         AnyNotSched = true;
247       }
248     } else {
249       if (SUnits[i].NumPredsLeft != 0) {
250         if (!AnyNotSched)
251           cerr << "*** Scheduling failed! ***\n";
252         SUnits[i].dump(this);
253         cerr << "has predecessors left!\n";
254         AnyNotSched = true;
255       }
256     }
257   }
258   for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
259     if (!Sequence[i])
260       ++Noops;
261   assert(!AnyNotSched);
262   assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
263          "The number of nodes scheduled doesn't match the expected number!");
264 }
265 #endif
266
267 /// InitDAGTopologicalSorting - create the initial topological 
268 /// ordering from the DAG to be scheduled.
269 ///
270 /// The idea of the algorithm is taken from 
271 /// "Online algorithms for managing the topological order of
272 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
273 /// This is the MNR algorithm, which was first introduced by 
274 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in  
275 /// "Maintaining a topological order under edge insertions".
276 ///
277 /// Short description of the algorithm: 
278 ///
279 /// Topological ordering, ord, of a DAG maps each node to a topological
280 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
281 ///
282 /// This means that if there is a path from the node X to the node Z, 
283 /// then ord(X) < ord(Z).
284 ///
285 /// This property can be used to check for reachability of nodes:
286 /// if Z is reachable from X, then an insertion of the edge Z->X would 
287 /// create a cycle.
288 ///
289 /// The algorithm first computes a topological ordering for the DAG by
290 /// initializing the Index2Node and Node2Index arrays and then tries to keep
291 /// the ordering up-to-date after edge insertions by reordering the DAG.
292 ///
293 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
294 /// the nodes reachable from Y, and then shifts them using Shift to lie
295 /// immediately after X in Index2Node.
296 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
297   unsigned DAGSize = SUnits.size();
298   std::vector<SUnit*> WorkList;
299   WorkList.reserve(DAGSize);
300
301   Index2Node.resize(DAGSize);
302   Node2Index.resize(DAGSize);
303
304   // Initialize the data structures.
305   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
306     SUnit *SU = &SUnits[i];
307     int NodeNum = SU->NodeNum;
308     unsigned Degree = SU->Succs.size();
309     // Temporarily use the Node2Index array as scratch space for degree counts.
310     Node2Index[NodeNum] = Degree;
311
312     // Is it a node without dependencies?
313     if (Degree == 0) {
314       assert(SU->Succs.empty() && "SUnit should have no successors");
315       // Collect leaf nodes.
316       WorkList.push_back(SU);
317     }
318   }  
319
320   int Id = DAGSize;
321   while (!WorkList.empty()) {
322     SUnit *SU = WorkList.back();
323     WorkList.pop_back();
324     Allocate(SU->NodeNum, --Id);
325     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
326          I != E; ++I) {
327       SUnit *SU = I->Dep;
328       if (!--Node2Index[SU->NodeNum])
329         // If all dependencies of the node are processed already,
330         // then the node can be computed now.
331         WorkList.push_back(SU);
332     }
333   }
334
335   Visited.resize(DAGSize);
336
337 #ifndef NDEBUG
338   // Check correctness of the ordering
339   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
340     SUnit *SU = &SUnits[i];
341     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
342          I != E; ++I) {
343       assert(Node2Index[SU->NodeNum] > Node2Index[I->Dep->NodeNum] && 
344       "Wrong topological sorting");
345     }
346   }
347 #endif
348 }
349
350 /// AddPred - Updates the topological ordering to accomodate an edge
351 /// to be added from SUnit X to SUnit Y.
352 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
353   int UpperBound, LowerBound;
354   LowerBound = Node2Index[Y->NodeNum];
355   UpperBound = Node2Index[X->NodeNum];
356   bool HasLoop = false;
357   // Is Ord(X) < Ord(Y) ?
358   if (LowerBound < UpperBound) {
359     // Update the topological order.
360     Visited.reset();
361     DFS(Y, UpperBound, HasLoop);
362     assert(!HasLoop && "Inserted edge creates a loop!");
363     // Recompute topological indexes.
364     Shift(Visited, LowerBound, UpperBound);
365   }
366 }
367
368 /// RemovePred - Updates the topological ordering to accomodate an
369 /// an edge to be removed from the specified node N from the predecessors
370 /// of the current node M.
371 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
372   // InitDAGTopologicalSorting();
373 }
374
375 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
376 /// all nodes affected by the edge insertion. These nodes will later get new
377 /// topological indexes by means of the Shift method.
378 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound, bool& HasLoop) {
379   std::vector<const SUnit*> WorkList;
380   WorkList.reserve(SUnits.size()); 
381
382   WorkList.push_back(SU);
383   while (!WorkList.empty()) {
384     SU = WorkList.back();
385     WorkList.pop_back();
386     Visited.set(SU->NodeNum);
387     for (int I = SU->Succs.size()-1; I >= 0; --I) {
388       int s = SU->Succs[I].Dep->NodeNum;
389       if (Node2Index[s] == UpperBound) {
390         HasLoop = true; 
391         return;
392       }
393       // Visit successors if not already and in affected region.
394       if (!Visited.test(s) && Node2Index[s] < UpperBound) {
395         WorkList.push_back(SU->Succs[I].Dep);
396       } 
397     } 
398   }
399 }
400
401 /// Shift - Renumber the nodes so that the topological ordering is 
402 /// preserved.
403 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound, 
404                               int UpperBound) {
405   std::vector<int> L;
406   int shift = 0;
407   int i;
408
409   for (i = LowerBound; i <= UpperBound; ++i) {
410     // w is node at topological index i.
411     int w = Index2Node[i];
412     if (Visited.test(w)) {
413       // Unmark.
414       Visited.reset(w);
415       L.push_back(w);
416       shift = shift + 1;
417     } else {
418       Allocate(w, i - shift);
419     }
420   }
421
422   for (unsigned j = 0; j < L.size(); ++j) {
423     Allocate(L[j], i - shift);
424     i = i + 1;
425   }
426 }
427
428
429 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
430 /// create a cycle.
431 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
432   if (IsReachable(TargetSU, SU))
433     return true;
434   for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
435        I != E; ++I)
436     if (I->Cost < 0 && IsReachable(TargetSU, I->Dep))
437       return true;
438   return false;
439 }
440
441 /// IsReachable - Checks if SU is reachable from TargetSU.
442 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU, const SUnit *TargetSU) {
443   // If insertion of the edge SU->TargetSU would create a cycle
444   // then there is a path from TargetSU to SU.
445   int UpperBound, LowerBound;
446   LowerBound = Node2Index[TargetSU->NodeNum];
447   UpperBound = Node2Index[SU->NodeNum];
448   bool HasLoop = false;
449   // Is Ord(TargetSU) < Ord(SU) ?
450   if (LowerBound < UpperBound) {
451     Visited.reset();
452     // There may be a path from TargetSU to SU. Check for it. 
453     DFS(TargetSU, UpperBound, HasLoop);
454   }
455   return HasLoop;
456 }
457
458 /// Allocate - assign the topological index to the node n.
459 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
460   Node2Index[n] = index;
461   Index2Node[index] = n;
462 }
463
464 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
465                                                      std::vector<SUnit> &sunits)
466  : SUnits(sunits) {}