1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the ScheduleDAG class, which is a base class used by
11 // scheduling implementation classes.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "pre-RA-sched"
16 #include "llvm/CodeGen/ScheduleDAG.h"
17 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Target/TargetRegisterInfo.h"
21 #include "llvm/Support/Debug.h"
25 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
26 : DAG(0), BB(0), TM(mf.getTarget()),
27 TII(TM.getInstrInfo()),
28 TRI(TM.getRegisterInfo()),
29 TLI(TM.getTargetLowering()),
30 MF(mf), MRI(mf.getRegInfo()),
31 ConstPool(MF.getConstantPool()),
35 ScheduleDAG::~ScheduleDAG() {}
37 /// dump - dump the schedule.
38 void ScheduleDAG::dumpSchedule() const {
39 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
40 if (SUnit *SU = Sequence[i])
43 cerr << "**** NOOP ****\n";
48 /// Run - perform scheduling.
50 void ScheduleDAG::Run(SelectionDAG *dag, MachineBasicBlock *bb,
51 MachineBasicBlock::iterator begin,
52 MachineBasicBlock::iterator end) {
53 assert((!dag || begin == end) &&
54 "An instruction range was given for SelectionDAG scheduling!");
67 DOUT << "*** Final schedule ***\n";
68 DEBUG(dumpSchedule());
72 /// addPred - This adds the specified edge as a pred of the current node if
73 /// not already. It also adds the current node as a successor of the
75 void SUnit::addPred(const SDep &D) {
76 // If this node already has this depenence, don't add a redundant one.
77 for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
80 // Now add a corresponding succ to N.
83 SUnit *N = D.getSUnit();
84 // Update the bookkeeping.
85 if (D.getKind() == SDep::Data) {
94 N->Succs.push_back(P);
95 if (P.getLatency() != 0) {
96 this->setDepthDirty();
101 /// removePred - This removes the specified edge as a pred of the current
102 /// node if it exists. It also removes the current node as a successor of
103 /// the specified node.
104 void SUnit::removePred(const SDep &D) {
105 // Find the matching predecessor.
106 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
109 bool FoundSucc = false;
110 // Find the corresponding successor in N.
113 SUnit *N = D.getSUnit();
114 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
115 EE = N->Succs.end(); II != EE; ++II)
121 assert(FoundSucc && "Mismatching preds / succs lists!");
123 // Update the bookkeeping.
124 if (P.getKind() == SDep::Data) {
132 if (P.getLatency() != 0) {
133 this->setDepthDirty();
140 void SUnit::setDepthDirty() {
141 if (!isDepthCurrent) return;
142 SmallVector<SUnit*, 8> WorkList;
143 WorkList.push_back(this);
145 SUnit *SU = WorkList.pop_back_val();
146 SU->isDepthCurrent = false;
147 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
148 E = SU->Succs.end(); I != E; ++I) {
149 SUnit *SuccSU = I->getSUnit();
150 if (SuccSU->isDepthCurrent)
151 WorkList.push_back(SuccSU);
153 } while (!WorkList.empty());
156 void SUnit::setHeightDirty() {
157 if (!isHeightCurrent) return;
158 SmallVector<SUnit*, 8> WorkList;
159 WorkList.push_back(this);
161 SUnit *SU = WorkList.pop_back_val();
162 SU->isHeightCurrent = false;
163 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
164 E = SU->Preds.end(); I != E; ++I) {
165 SUnit *PredSU = I->getSUnit();
166 if (PredSU->isHeightCurrent)
167 WorkList.push_back(PredSU);
169 } while (!WorkList.empty());
172 /// setDepthToAtLeast - Update this node's successors to reflect the
173 /// fact that this node's depth just increased.
175 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
176 if (NewDepth <= getDepth())
180 isDepthCurrent = true;
183 /// setHeightToAtLeast - Update this node's predecessors to reflect the
184 /// fact that this node's height just increased.
186 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
187 if (NewHeight <= getHeight())
191 isHeightCurrent = true;
194 /// ComputeDepth - Calculate the maximal path from the node to the exit.
196 void SUnit::ComputeDepth() {
197 SmallVector<SUnit*, 8> WorkList;
198 WorkList.push_back(this);
200 SUnit *Cur = WorkList.back();
203 unsigned MaxPredDepth = 0;
204 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
205 E = Cur->Preds.end(); I != E; ++I) {
206 SUnit *PredSU = I->getSUnit();
207 if (PredSU->isDepthCurrent)
208 MaxPredDepth = std::max(MaxPredDepth,
209 PredSU->Depth + I->getLatency());
212 WorkList.push_back(PredSU);
218 if (MaxPredDepth != Cur->Depth) {
219 Cur->setDepthDirty();
220 Cur->Depth = MaxPredDepth;
222 Cur->isDepthCurrent = true;
224 } while (!WorkList.empty());
227 /// ComputeHeight - Calculate the maximal path from the node to the entry.
229 void SUnit::ComputeHeight() {
230 SmallVector<SUnit*, 8> WorkList;
231 WorkList.push_back(this);
233 SUnit *Cur = WorkList.back();
236 unsigned MaxSuccHeight = 0;
237 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
238 E = Cur->Succs.end(); I != E; ++I) {
239 SUnit *SuccSU = I->getSUnit();
240 if (SuccSU->isHeightCurrent)
241 MaxSuccHeight = std::max(MaxSuccHeight,
242 SuccSU->Height + I->getLatency());
245 WorkList.push_back(SuccSU);
251 if (MaxSuccHeight != Cur->Height) {
252 Cur->setHeightDirty();
253 Cur->Height = MaxSuccHeight;
255 Cur->isHeightCurrent = true;
257 } while (!WorkList.empty());
260 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
261 /// a group of nodes flagged together.
262 void SUnit::dump(const ScheduleDAG *G) const {
263 cerr << "SU(" << NodeNum << "): ";
267 void SUnit::dumpAll(const ScheduleDAG *G) const {
270 cerr << " # preds left : " << NumPredsLeft << "\n";
271 cerr << " # succs left : " << NumSuccsLeft << "\n";
272 cerr << " Latency : " << Latency << "\n";
273 cerr << " Depth : " << Depth << "\n";
274 cerr << " Height : " << Height << "\n";
276 if (Preds.size() != 0) {
277 cerr << " Predecessors:\n";
278 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
281 switch (I->getKind()) {
282 case SDep::Data: cerr << "val "; break;
283 case SDep::Anti: cerr << "anti"; break;
284 case SDep::Output: cerr << "out "; break;
285 case SDep::Order: cerr << "ch "; break;
288 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
289 if (I->isArtificial())
294 if (Succs.size() != 0) {
295 cerr << " Successors:\n";
296 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
299 switch (I->getKind()) {
300 case SDep::Data: cerr << "val "; break;
301 case SDep::Anti: cerr << "anti"; break;
302 case SDep::Output: cerr << "out "; break;
303 case SDep::Order: cerr << "ch "; break;
306 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
307 if (I->isArtificial())
316 /// VerifySchedule - Verify that all SUnits were scheduled and that
317 /// their state is consistent.
319 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
320 bool AnyNotSched = false;
321 unsigned DeadNodes = 0;
323 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
324 if (!SUnits[i].isScheduled) {
325 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
330 cerr << "*** Scheduling failed! ***\n";
331 SUnits[i].dump(this);
332 cerr << "has not been scheduled!\n";
335 if (SUnits[i].isScheduled &&
336 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getHeight()) >
339 cerr << "*** Scheduling failed! ***\n";
340 SUnits[i].dump(this);
341 cerr << "has an unexpected "
342 << (isBottomUp ? "Height" : "Depth") << " value!\n";
346 if (SUnits[i].NumSuccsLeft != 0) {
348 cerr << "*** Scheduling failed! ***\n";
349 SUnits[i].dump(this);
350 cerr << "has successors left!\n";
354 if (SUnits[i].NumPredsLeft != 0) {
356 cerr << "*** Scheduling failed! ***\n";
357 SUnits[i].dump(this);
358 cerr << "has predecessors left!\n";
363 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
366 assert(!AnyNotSched);
367 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
368 "The number of nodes scheduled doesn't match the expected number!");
372 /// InitDAGTopologicalSorting - create the initial topological
373 /// ordering from the DAG to be scheduled.
375 /// The idea of the algorithm is taken from
376 /// "Online algorithms for managing the topological order of
377 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
378 /// This is the MNR algorithm, which was first introduced by
379 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
380 /// "Maintaining a topological order under edge insertions".
382 /// Short description of the algorithm:
384 /// Topological ordering, ord, of a DAG maps each node to a topological
385 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
387 /// This means that if there is a path from the node X to the node Z,
388 /// then ord(X) < ord(Z).
390 /// This property can be used to check for reachability of nodes:
391 /// if Z is reachable from X, then an insertion of the edge Z->X would
394 /// The algorithm first computes a topological ordering for the DAG by
395 /// initializing the Index2Node and Node2Index arrays and then tries to keep
396 /// the ordering up-to-date after edge insertions by reordering the DAG.
398 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
399 /// the nodes reachable from Y, and then shifts them using Shift to lie
400 /// immediately after X in Index2Node.
401 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
402 unsigned DAGSize = SUnits.size();
403 std::vector<SUnit*> WorkList;
404 WorkList.reserve(DAGSize);
406 Index2Node.resize(DAGSize);
407 Node2Index.resize(DAGSize);
409 // Initialize the data structures.
410 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
411 SUnit *SU = &SUnits[i];
412 int NodeNum = SU->NodeNum;
413 unsigned Degree = SU->Succs.size();
414 // Temporarily use the Node2Index array as scratch space for degree counts.
415 Node2Index[NodeNum] = Degree;
417 // Is it a node without dependencies?
419 assert(SU->Succs.empty() && "SUnit should have no successors");
420 // Collect leaf nodes.
421 WorkList.push_back(SU);
426 while (!WorkList.empty()) {
427 SUnit *SU = WorkList.back();
429 Allocate(SU->NodeNum, --Id);
430 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
432 SUnit *SU = I->getSUnit();
433 if (!--Node2Index[SU->NodeNum])
434 // If all dependencies of the node are processed already,
435 // then the node can be computed now.
436 WorkList.push_back(SU);
440 Visited.resize(DAGSize);
443 // Check correctness of the ordering
444 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
445 SUnit *SU = &SUnits[i];
446 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
448 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
449 "Wrong topological sorting");
455 /// AddPred - Updates the topological ordering to accomodate an edge
456 /// to be added from SUnit X to SUnit Y.
457 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
458 int UpperBound, LowerBound;
459 LowerBound = Node2Index[Y->NodeNum];
460 UpperBound = Node2Index[X->NodeNum];
461 bool HasLoop = false;
462 // Is Ord(X) < Ord(Y) ?
463 if (LowerBound < UpperBound) {
464 // Update the topological order.
466 DFS(Y, UpperBound, HasLoop);
467 assert(!HasLoop && "Inserted edge creates a loop!");
468 // Recompute topological indexes.
469 Shift(Visited, LowerBound, UpperBound);
473 /// RemovePred - Updates the topological ordering to accomodate an
474 /// an edge to be removed from the specified node N from the predecessors
475 /// of the current node M.
476 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
477 // InitDAGTopologicalSorting();
480 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
481 /// all nodes affected by the edge insertion. These nodes will later get new
482 /// topological indexes by means of the Shift method.
483 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
485 std::vector<const SUnit*> WorkList;
486 WorkList.reserve(SUnits.size());
488 WorkList.push_back(SU);
490 SU = WorkList.back();
492 Visited.set(SU->NodeNum);
493 for (int I = SU->Succs.size()-1; I >= 0; --I) {
494 int s = SU->Succs[I].getSUnit()->NodeNum;
495 if (Node2Index[s] == UpperBound) {
499 // Visit successors if not already and in affected region.
500 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
501 WorkList.push_back(SU->Succs[I].getSUnit());
504 } while (!WorkList.empty());
507 /// Shift - Renumber the nodes so that the topological ordering is
509 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
515 for (i = LowerBound; i <= UpperBound; ++i) {
516 // w is node at topological index i.
517 int w = Index2Node[i];
518 if (Visited.test(w)) {
524 Allocate(w, i - shift);
528 for (unsigned j = 0; j < L.size(); ++j) {
529 Allocate(L[j], i - shift);
535 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
537 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
538 if (IsReachable(TargetSU, SU))
540 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
542 if (I->isAssignedRegDep() &&
543 IsReachable(TargetSU, I->getSUnit()))
548 /// IsReachable - Checks if SU is reachable from TargetSU.
549 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
550 const SUnit *TargetSU) {
551 // If insertion of the edge SU->TargetSU would create a cycle
552 // then there is a path from TargetSU to SU.
553 int UpperBound, LowerBound;
554 LowerBound = Node2Index[TargetSU->NodeNum];
555 UpperBound = Node2Index[SU->NodeNum];
556 bool HasLoop = false;
557 // Is Ord(TargetSU) < Ord(SU) ?
558 if (LowerBound < UpperBound) {
560 // There may be a path from TargetSU to SU. Check for it.
561 DFS(TargetSU, UpperBound, HasLoop);
566 /// Allocate - assign the topological index to the node n.
567 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
568 Node2Index[n] = index;
569 Index2Node[index] = n;
572 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
573 std::vector<SUnit> &sunits)
576 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}