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"
22 #include "llvm/Support/raw_ostream.h"
26 ScheduleDAG::ScheduleDAG(MachineFunction &mf)
28 TII(TM.getInstrInfo()),
29 TRI(TM.getRegisterInfo()),
30 TLI(TM.getTargetLowering()),
31 MF(mf), MRI(mf.getRegInfo()),
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 dbgs() << "**** NOOP ****\n";
48 /// Run - perform scheduling.
50 void ScheduleDAG::Run(MachineBasicBlock *bb,
51 MachineBasicBlock::iterator insertPos) {
53 InsertPos = insertPos;
63 dbgs() << "*** Final schedule ***\n";
69 /// addPred - This adds the specified edge as a pred of the current node if
70 /// not already. It also adds the current node as a successor of the
72 void SUnit::addPred(const SDep &D) {
73 // If this node already has this depenence, don't add a redundant one.
74 for (SmallVector<SDep, 4>::const_iterator I = Preds.begin(), E = Preds.end();
78 // Now add a corresponding succ to N.
81 SUnit *N = D.getSUnit();
82 // Update the bookkeeping.
83 if (D.getKind() == SDep::Data) {
84 assert(NumPreds < UINT_MAX && "NumPreds will overflow!");
85 assert(N->NumSuccs < UINT_MAX && "NumSuccs will overflow!");
89 if (!N->isScheduled) {
90 assert(NumPredsLeft < UINT_MAX && "NumPredsLeft will overflow!");
94 assert(N->NumSuccsLeft < UINT_MAX && "NumSuccsLeft will overflow!");
98 N->Succs.push_back(P);
99 if (P.getLatency() != 0) {
100 this->setDepthDirty();
105 /// removePred - This removes the specified edge as a pred of the current
106 /// node if it exists. It also removes the current node as a successor of
107 /// the specified node.
108 void SUnit::removePred(const SDep &D) {
109 // Find the matching predecessor.
110 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
113 bool FoundSucc = false;
114 // Find the corresponding successor in N.
117 SUnit *N = D.getSUnit();
118 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
119 EE = N->Succs.end(); II != EE; ++II)
125 assert(FoundSucc && "Mismatching preds / succs lists!");
127 // Update the bookkeeping.
128 if (P.getKind() == SDep::Data) {
129 assert(NumPreds > 0 && "NumPreds will underflow!");
130 assert(N->NumSuccs > 0 && "NumSuccs will underflow!");
134 if (!N->isScheduled) {
135 assert(NumPredsLeft > 0 && "NumPredsLeft will underflow!");
139 assert(N->NumSuccsLeft > 0 && "NumSuccsLeft will underflow!");
142 if (P.getLatency() != 0) {
143 this->setDepthDirty();
150 void SUnit::setDepthDirty() {
151 if (!isDepthCurrent) return;
152 SmallVector<SUnit*, 8> WorkList;
153 WorkList.push_back(this);
155 SUnit *SU = WorkList.pop_back_val();
156 SU->isDepthCurrent = false;
157 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
158 E = SU->Succs.end(); I != E; ++I) {
159 SUnit *SuccSU = I->getSUnit();
160 if (SuccSU->isDepthCurrent)
161 WorkList.push_back(SuccSU);
163 } while (!WorkList.empty());
166 void SUnit::setHeightDirty() {
167 if (!isHeightCurrent) return;
168 SmallVector<SUnit*, 8> WorkList;
169 WorkList.push_back(this);
171 SUnit *SU = WorkList.pop_back_val();
172 SU->isHeightCurrent = false;
173 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
174 E = SU->Preds.end(); I != E; ++I) {
175 SUnit *PredSU = I->getSUnit();
176 if (PredSU->isHeightCurrent)
177 WorkList.push_back(PredSU);
179 } while (!WorkList.empty());
182 /// setDepthToAtLeast - Update this node's successors to reflect the
183 /// fact that this node's depth just increased.
185 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
186 if (NewDepth <= getDepth())
190 isDepthCurrent = true;
193 /// setHeightToAtLeast - Update this node's predecessors to reflect the
194 /// fact that this node's height just increased.
196 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
197 if (NewHeight <= getHeight())
201 isHeightCurrent = true;
204 /// ComputeDepth - Calculate the maximal path from the node to the exit.
206 void SUnit::ComputeDepth() {
207 SmallVector<SUnit*, 8> WorkList;
208 WorkList.push_back(this);
210 SUnit *Cur = WorkList.back();
213 unsigned MaxPredDepth = 0;
214 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
215 E = Cur->Preds.end(); I != E; ++I) {
216 SUnit *PredSU = I->getSUnit();
217 if (PredSU->isDepthCurrent)
218 MaxPredDepth = std::max(MaxPredDepth,
219 PredSU->Depth + I->getLatency());
222 WorkList.push_back(PredSU);
228 if (MaxPredDepth != Cur->Depth) {
229 Cur->setDepthDirty();
230 Cur->Depth = MaxPredDepth;
232 Cur->isDepthCurrent = true;
234 } while (!WorkList.empty());
237 /// ComputeHeight - Calculate the maximal path from the node to the entry.
239 void SUnit::ComputeHeight() {
240 SmallVector<SUnit*, 8> WorkList;
241 WorkList.push_back(this);
243 SUnit *Cur = WorkList.back();
246 unsigned MaxSuccHeight = 0;
247 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
248 E = Cur->Succs.end(); I != E; ++I) {
249 SUnit *SuccSU = I->getSUnit();
250 if (SuccSU->isHeightCurrent)
251 MaxSuccHeight = std::max(MaxSuccHeight,
252 SuccSU->Height + I->getLatency());
255 WorkList.push_back(SuccSU);
261 if (MaxSuccHeight != Cur->Height) {
262 Cur->setHeightDirty();
263 Cur->Height = MaxSuccHeight;
265 Cur->isHeightCurrent = true;
267 } while (!WorkList.empty());
270 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
271 /// a group of nodes flagged together.
272 void SUnit::dump(const ScheduleDAG *G) const {
273 dbgs() << "SU(" << NodeNum << "): ";
277 void SUnit::dumpAll(const ScheduleDAG *G) const {
280 dbgs() << " # preds left : " << NumPredsLeft << "\n";
281 dbgs() << " # succs left : " << NumSuccsLeft << "\n";
282 dbgs() << " Latency : " << Latency << "\n";
283 dbgs() << " Depth : " << Depth << "\n";
284 dbgs() << " Height : " << Height << "\n";
286 if (Preds.size() != 0) {
287 dbgs() << " Predecessors:\n";
288 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
291 switch (I->getKind()) {
292 case SDep::Data: dbgs() << "val "; break;
293 case SDep::Anti: dbgs() << "anti"; break;
294 case SDep::Output: dbgs() << "out "; break;
295 case SDep::Order: dbgs() << "ch "; break;
298 dbgs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
299 if (I->isArtificial())
301 dbgs() << ": Latency=" << I->getLatency();
305 if (Succs.size() != 0) {
306 dbgs() << " Successors:\n";
307 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
310 switch (I->getKind()) {
311 case SDep::Data: dbgs() << "val "; break;
312 case SDep::Anti: dbgs() << "anti"; break;
313 case SDep::Output: dbgs() << "out "; break;
314 case SDep::Order: dbgs() << "ch "; break;
317 dbgs() << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
318 if (I->isArtificial())
320 dbgs() << ": Latency=" << I->getLatency();
328 /// VerifySchedule - Verify that all SUnits were scheduled and that
329 /// their state is consistent.
331 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
332 bool AnyNotSched = false;
333 unsigned DeadNodes = 0;
335 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
336 if (!SUnits[i].isScheduled) {
337 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
342 dbgs() << "*** Scheduling failed! ***\n";
343 SUnits[i].dump(this);
344 dbgs() << "has not been scheduled!\n";
347 if (SUnits[i].isScheduled &&
348 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getDepth()) >
351 dbgs() << "*** Scheduling failed! ***\n";
352 SUnits[i].dump(this);
353 dbgs() << "has an unexpected "
354 << (isBottomUp ? "Height" : "Depth") << " value!\n";
358 if (SUnits[i].NumSuccsLeft != 0) {
360 dbgs() << "*** Scheduling failed! ***\n";
361 SUnits[i].dump(this);
362 dbgs() << "has successors left!\n";
366 if (SUnits[i].NumPredsLeft != 0) {
368 dbgs() << "*** Scheduling failed! ***\n";
369 SUnits[i].dump(this);
370 dbgs() << "has predecessors left!\n";
375 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
378 assert(!AnyNotSched);
379 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
380 "The number of nodes scheduled doesn't match the expected number!");
384 /// InitDAGTopologicalSorting - create the initial topological
385 /// ordering from the DAG to be scheduled.
387 /// The idea of the algorithm is taken from
388 /// "Online algorithms for managing the topological order of
389 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
390 /// This is the MNR algorithm, which was first introduced by
391 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
392 /// "Maintaining a topological order under edge insertions".
394 /// Short description of the algorithm:
396 /// Topological ordering, ord, of a DAG maps each node to a topological
397 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
399 /// This means that if there is a path from the node X to the node Z,
400 /// then ord(X) < ord(Z).
402 /// This property can be used to check for reachability of nodes:
403 /// if Z is reachable from X, then an insertion of the edge Z->X would
406 /// The algorithm first computes a topological ordering for the DAG by
407 /// initializing the Index2Node and Node2Index arrays and then tries to keep
408 /// the ordering up-to-date after edge insertions by reordering the DAG.
410 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
411 /// the nodes reachable from Y, and then shifts them using Shift to lie
412 /// immediately after X in Index2Node.
413 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
414 unsigned DAGSize = SUnits.size();
415 std::vector<SUnit*> WorkList;
416 WorkList.reserve(DAGSize);
418 Index2Node.resize(DAGSize);
419 Node2Index.resize(DAGSize);
421 // Initialize the data structures.
422 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
423 SUnit *SU = &SUnits[i];
424 int NodeNum = SU->NodeNum;
425 unsigned Degree = SU->Succs.size();
426 // Temporarily use the Node2Index array as scratch space for degree counts.
427 Node2Index[NodeNum] = Degree;
429 // Is it a node without dependencies?
431 assert(SU->Succs.empty() && "SUnit should have no successors");
432 // Collect leaf nodes.
433 WorkList.push_back(SU);
438 while (!WorkList.empty()) {
439 SUnit *SU = WorkList.back();
441 Allocate(SU->NodeNum, --Id);
442 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
444 SUnit *SU = I->getSUnit();
445 if (!--Node2Index[SU->NodeNum])
446 // If all dependencies of the node are processed already,
447 // then the node can be computed now.
448 WorkList.push_back(SU);
452 Visited.resize(DAGSize);
455 // Check correctness of the ordering
456 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
457 SUnit *SU = &SUnits[i];
458 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
460 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
461 "Wrong topological sorting");
467 /// AddPred - Updates the topological ordering to accomodate an edge
468 /// to be added from SUnit X to SUnit Y.
469 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
470 int UpperBound, LowerBound;
471 LowerBound = Node2Index[Y->NodeNum];
472 UpperBound = Node2Index[X->NodeNum];
473 bool HasLoop = false;
474 // Is Ord(X) < Ord(Y) ?
475 if (LowerBound < UpperBound) {
476 // Update the topological order.
478 DFS(Y, UpperBound, HasLoop);
479 assert(!HasLoop && "Inserted edge creates a loop!");
480 // Recompute topological indexes.
481 Shift(Visited, LowerBound, UpperBound);
485 /// RemovePred - Updates the topological ordering to accomodate an
486 /// an edge to be removed from the specified node N from the predecessors
487 /// of the current node M.
488 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
489 // InitDAGTopologicalSorting();
492 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
493 /// all nodes affected by the edge insertion. These nodes will later get new
494 /// topological indexes by means of the Shift method.
495 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
497 std::vector<const SUnit*> WorkList;
498 WorkList.reserve(SUnits.size());
500 WorkList.push_back(SU);
502 SU = WorkList.back();
504 Visited.set(SU->NodeNum);
505 for (int I = SU->Succs.size()-1; I >= 0; --I) {
506 int s = SU->Succs[I].getSUnit()->NodeNum;
507 if (Node2Index[s] == UpperBound) {
511 // Visit successors if not already and in affected region.
512 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
513 WorkList.push_back(SU->Succs[I].getSUnit());
516 } while (!WorkList.empty());
519 /// Shift - Renumber the nodes so that the topological ordering is
521 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
527 for (i = LowerBound; i <= UpperBound; ++i) {
528 // w is node at topological index i.
529 int w = Index2Node[i];
530 if (Visited.test(w)) {
536 Allocate(w, i - shift);
540 for (unsigned j = 0; j < L.size(); ++j) {
541 Allocate(L[j], i - shift);
547 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
549 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
550 if (IsReachable(TargetSU, SU))
552 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
554 if (I->isAssignedRegDep() &&
555 IsReachable(TargetSU, I->getSUnit()))
560 /// IsReachable - Checks if SU is reachable from TargetSU.
561 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
562 const SUnit *TargetSU) {
563 // If insertion of the edge SU->TargetSU would create a cycle
564 // then there is a path from TargetSU to SU.
565 int UpperBound, LowerBound;
566 LowerBound = Node2Index[TargetSU->NodeNum];
567 UpperBound = Node2Index[SU->NodeNum];
568 bool HasLoop = false;
569 // Is Ord(TargetSU) < Ord(SU) ?
570 if (LowerBound < UpperBound) {
572 // There may be a path from TargetSU to SU. Check for it.
573 DFS(TargetSU, UpperBound, HasLoop);
578 /// Allocate - assign the topological index to the node n.
579 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
580 Node2Index[n] = index;
581 Index2Node[index] = n;
584 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
585 std::vector<SUnit> &sunits)
588 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}