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()) {
34 ScheduleDAG::~ScheduleDAG() {}
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])
42 cerr << "**** NOOP ****\n";
47 /// Run - perform scheduling.
49 void ScheduleDAG::Run(SelectionDAG *dag, MachineBasicBlock *bb) {
57 DOUT << "*** Final schedule ***\n";
58 DEBUG(dumpSchedule());
62 /// addPred - This adds the specified edge as a pred of the current node if
63 /// not already. It also adds the current node as a successor of the
65 void SUnit::addPred(const SDep &D) {
66 // If this node already has this depenence, don't add a redundant one.
67 for (unsigned i = 0, e = (unsigned)Preds.size(); i != e; ++i)
70 // Now add a corresponding succ to N.
73 SUnit *N = D.getSUnit();
74 // Update the bookkeeping.
75 if (D.getKind() == SDep::Data) {
84 N->Succs.push_back(P);
85 if (P.getLatency() != 0) {
86 this->setDepthDirty();
91 /// removePred - This removes the specified edge as a pred of the current
92 /// node if it exists. It also removes the current node as a successor of
93 /// the specified node.
94 void SUnit::removePred(const SDep &D) {
95 // Find the matching predecessor.
96 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
99 bool FoundSucc = false;
100 // Find the corresponding successor in N.
103 SUnit *N = D.getSUnit();
104 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
105 EE = N->Succs.end(); II != EE; ++II)
111 assert(FoundSucc && "Mismatching preds / succs lists!");
113 // Update the bookkeeping.
114 if (P.getKind() == SDep::Data) {
122 if (P.getLatency() != 0) {
123 this->setDepthDirty();
130 void SUnit::setDepthDirty() {
131 if (!isDepthCurrent) return;
132 SmallVector<SUnit*, 8> WorkList;
133 WorkList.push_back(this);
135 SUnit *SU = WorkList.pop_back_val();
136 SU->isDepthCurrent = false;
137 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
138 E = SU->Succs.end(); I != E; ++I) {
139 SUnit *SuccSU = I->getSUnit();
140 if (SuccSU->isDepthCurrent)
141 WorkList.push_back(SuccSU);
143 } while (!WorkList.empty());
146 void SUnit::setHeightDirty() {
147 if (!isHeightCurrent) return;
148 SmallVector<SUnit*, 8> WorkList;
149 WorkList.push_back(this);
151 SUnit *SU = WorkList.pop_back_val();
152 SU->isHeightCurrent = false;
153 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
154 E = SU->Preds.end(); I != E; ++I) {
155 SUnit *PredSU = I->getSUnit();
156 if (PredSU->isHeightCurrent)
157 WorkList.push_back(PredSU);
159 } while (!WorkList.empty());
162 /// setDepthToAtLeast - Update this node's successors to reflect the
163 /// fact that this node's depth just increased.
165 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
166 if (NewDepth <= getDepth())
170 isDepthCurrent = true;
173 /// setHeightToAtLeast - Update this node's predecessors to reflect the
174 /// fact that this node's height just increased.
176 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
177 if (NewHeight <= getHeight())
181 isHeightCurrent = true;
184 /// ComputeDepth - Calculate the maximal path from the node to the exit.
186 void SUnit::ComputeDepth() {
187 SmallVector<SUnit*, 8> WorkList;
188 WorkList.push_back(this);
190 SUnit *Cur = WorkList.back();
193 unsigned MaxPredDepth = 0;
194 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
195 E = Cur->Preds.end(); I != E; ++I) {
196 SUnit *PredSU = I->getSUnit();
197 if (PredSU->isDepthCurrent)
198 MaxPredDepth = std::max(MaxPredDepth,
199 PredSU->Depth + I->getLatency());
202 WorkList.push_back(PredSU);
208 if (MaxPredDepth != Cur->Depth) {
209 Cur->setDepthDirty();
210 Cur->Depth = MaxPredDepth;
212 Cur->isDepthCurrent = true;
214 } while (!WorkList.empty());
217 /// ComputeHeight - Calculate the maximal path from the node to the entry.
219 void SUnit::ComputeHeight() {
220 SmallVector<SUnit*, 8> WorkList;
221 WorkList.push_back(this);
223 SUnit *Cur = WorkList.back();
226 unsigned MaxSuccHeight = 0;
227 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
228 E = Cur->Succs.end(); I != E; ++I) {
229 SUnit *SuccSU = I->getSUnit();
230 if (SuccSU->isHeightCurrent)
231 MaxSuccHeight = std::max(MaxSuccHeight,
232 SuccSU->Height + I->getLatency());
235 WorkList.push_back(SuccSU);
241 if (MaxSuccHeight != Cur->Height) {
242 Cur->setHeightDirty();
243 Cur->Height = MaxSuccHeight;
245 Cur->isHeightCurrent = true;
247 } while (!WorkList.empty());
250 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
251 /// a group of nodes flagged together.
252 void SUnit::dump(const ScheduleDAG *G) const {
253 cerr << "SU(" << NodeNum << "): ";
257 void SUnit::dumpAll(const ScheduleDAG *G) const {
260 cerr << " # preds left : " << NumPredsLeft << "\n";
261 cerr << " # succs left : " << NumSuccsLeft << "\n";
262 cerr << " Latency : " << Latency << "\n";
263 cerr << " Depth : " << Depth << "\n";
264 cerr << " Height : " << Height << "\n";
266 if (Preds.size() != 0) {
267 cerr << " Predecessors:\n";
268 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
271 switch (I->getKind()) {
272 case SDep::Data: cerr << "val "; break;
273 case SDep::Anti: cerr << "anti"; break;
274 case SDep::Output: cerr << "out "; break;
275 case SDep::Order: cerr << "ch "; break;
278 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
279 if (I->isArtificial())
284 if (Succs.size() != 0) {
285 cerr << " Successors:\n";
286 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
289 switch (I->getKind()) {
290 case SDep::Data: cerr << "val "; break;
291 case SDep::Anti: cerr << "anti"; break;
292 case SDep::Output: cerr << "out "; break;
293 case SDep::Order: cerr << "ch "; break;
296 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
297 if (I->isArtificial())
306 /// VerifySchedule - Verify that all SUnits were scheduled and that
307 /// their state is consistent.
309 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
310 bool AnyNotSched = false;
311 unsigned DeadNodes = 0;
313 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
314 if (!SUnits[i].isScheduled) {
315 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
320 cerr << "*** Scheduling failed! ***\n";
321 SUnits[i].dump(this);
322 cerr << "has not been scheduled!\n";
325 if (SUnits[i].isScheduled &&
326 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getHeight()) >
329 cerr << "*** Scheduling failed! ***\n";
330 SUnits[i].dump(this);
331 cerr << "has an unexpected "
332 << (isBottomUp ? "Height" : "Depth") << " value!\n";
336 if (SUnits[i].NumSuccsLeft != 0) {
338 cerr << "*** Scheduling failed! ***\n";
339 SUnits[i].dump(this);
340 cerr << "has successors left!\n";
344 if (SUnits[i].NumPredsLeft != 0) {
346 cerr << "*** Scheduling failed! ***\n";
347 SUnits[i].dump(this);
348 cerr << "has predecessors left!\n";
353 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
356 assert(!AnyNotSched);
357 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
358 "The number of nodes scheduled doesn't match the expected number!");
362 /// InitDAGTopologicalSorting - create the initial topological
363 /// ordering from the DAG to be scheduled.
365 /// The idea of the algorithm is taken from
366 /// "Online algorithms for managing the topological order of
367 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
368 /// This is the MNR algorithm, which was first introduced by
369 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
370 /// "Maintaining a topological order under edge insertions".
372 /// Short description of the algorithm:
374 /// Topological ordering, ord, of a DAG maps each node to a topological
375 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
377 /// This means that if there is a path from the node X to the node Z,
378 /// then ord(X) < ord(Z).
380 /// This property can be used to check for reachability of nodes:
381 /// if Z is reachable from X, then an insertion of the edge Z->X would
384 /// The algorithm first computes a topological ordering for the DAG by
385 /// initializing the Index2Node and Node2Index arrays and then tries to keep
386 /// the ordering up-to-date after edge insertions by reordering the DAG.
388 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
389 /// the nodes reachable from Y, and then shifts them using Shift to lie
390 /// immediately after X in Index2Node.
391 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
392 unsigned DAGSize = SUnits.size();
393 std::vector<SUnit*> WorkList;
394 WorkList.reserve(DAGSize);
396 Index2Node.resize(DAGSize);
397 Node2Index.resize(DAGSize);
399 // Initialize the data structures.
400 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
401 SUnit *SU = &SUnits[i];
402 int NodeNum = SU->NodeNum;
403 unsigned Degree = SU->Succs.size();
404 // Temporarily use the Node2Index array as scratch space for degree counts.
405 Node2Index[NodeNum] = Degree;
407 // Is it a node without dependencies?
409 assert(SU->Succs.empty() && "SUnit should have no successors");
410 // Collect leaf nodes.
411 WorkList.push_back(SU);
416 while (!WorkList.empty()) {
417 SUnit *SU = WorkList.back();
419 Allocate(SU->NodeNum, --Id);
420 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
422 SUnit *SU = I->getSUnit();
423 if (!--Node2Index[SU->NodeNum])
424 // If all dependencies of the node are processed already,
425 // then the node can be computed now.
426 WorkList.push_back(SU);
430 Visited.resize(DAGSize);
433 // Check correctness of the ordering
434 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
435 SUnit *SU = &SUnits[i];
436 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
438 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
439 "Wrong topological sorting");
445 /// AddPred - Updates the topological ordering to accomodate an edge
446 /// to be added from SUnit X to SUnit Y.
447 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
448 int UpperBound, LowerBound;
449 LowerBound = Node2Index[Y->NodeNum];
450 UpperBound = Node2Index[X->NodeNum];
451 bool HasLoop = false;
452 // Is Ord(X) < Ord(Y) ?
453 if (LowerBound < UpperBound) {
454 // Update the topological order.
456 DFS(Y, UpperBound, HasLoop);
457 assert(!HasLoop && "Inserted edge creates a loop!");
458 // Recompute topological indexes.
459 Shift(Visited, LowerBound, UpperBound);
463 /// RemovePred - Updates the topological ordering to accomodate an
464 /// an edge to be removed from the specified node N from the predecessors
465 /// of the current node M.
466 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
467 // InitDAGTopologicalSorting();
470 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
471 /// all nodes affected by the edge insertion. These nodes will later get new
472 /// topological indexes by means of the Shift method.
473 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
475 std::vector<const SUnit*> WorkList;
476 WorkList.reserve(SUnits.size());
478 WorkList.push_back(SU);
480 SU = WorkList.back();
482 Visited.set(SU->NodeNum);
483 for (int I = SU->Succs.size()-1; I >= 0; --I) {
484 int s = SU->Succs[I].getSUnit()->NodeNum;
485 if (Node2Index[s] == UpperBound) {
489 // Visit successors if not already and in affected region.
490 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
491 WorkList.push_back(SU->Succs[I].getSUnit());
494 } while (!WorkList.empty());
497 /// Shift - Renumber the nodes so that the topological ordering is
499 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
505 for (i = LowerBound; i <= UpperBound; ++i) {
506 // w is node at topological index i.
507 int w = Index2Node[i];
508 if (Visited.test(w)) {
514 Allocate(w, i - shift);
518 for (unsigned j = 0; j < L.size(); ++j) {
519 Allocate(L[j], i - shift);
525 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
527 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
528 if (IsReachable(TargetSU, SU))
530 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
532 if (I->isAssignedRegDep() &&
533 IsReachable(TargetSU, I->getSUnit()))
538 /// IsReachable - Checks if SU is reachable from TargetSU.
539 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
540 const SUnit *TargetSU) {
541 // If insertion of the edge SU->TargetSU would create a cycle
542 // then there is a path from TargetSU to SU.
543 int UpperBound, LowerBound;
544 LowerBound = Node2Index[TargetSU->NodeNum];
545 UpperBound = Node2Index[SU->NodeNum];
546 bool HasLoop = false;
547 // Is Ord(TargetSU) < Ord(SU) ?
548 if (LowerBound < UpperBound) {
550 // There may be a path from TargetSU to SU. Check for it.
551 DFS(TargetSU, UpperBound, HasLoop);
556 /// Allocate - assign the topological index to the node n.
557 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
558 Node2Index[n] = index;
559 Index2Node[index] = n;
562 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
563 std::vector<SUnit> &sunits)
566 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}