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)
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(MachineBasicBlock *bb,
51 MachineBasicBlock::iterator insertPos) {
53 InsertPos = insertPos;
62 DOUT << "*** Final schedule ***\n";
63 DEBUG(dumpSchedule());
67 /// addPred - This adds the specified edge as a pred of the current node if
68 /// not already. It also adds the current node as a successor of the
70 void SUnit::addPred(const SDep &D) {
71 // If this node already has this depenence, don't add a redundant one.
72 for (SmallVector<SDep, 4>::const_iterator I = Preds.begin(), E = Preds.end();
76 // Now add a corresponding succ to N.
79 SUnit *N = D.getSUnit();
80 // Update the bookkeeping.
81 if (D.getKind() == SDep::Data) {
90 N->Succs.push_back(P);
91 if (P.getLatency() != 0) {
92 this->setDepthDirty();
97 /// removePred - This removes the specified edge as a pred of the current
98 /// node if it exists. It also removes the current node as a successor of
99 /// the specified node.
100 void SUnit::removePred(const SDep &D) {
101 // Find the matching predecessor.
102 for (SmallVector<SDep, 4>::iterator I = Preds.begin(), E = Preds.end();
105 bool FoundSucc = false;
106 // Find the corresponding successor in N.
109 SUnit *N = D.getSUnit();
110 for (SmallVector<SDep, 4>::iterator II = N->Succs.begin(),
111 EE = N->Succs.end(); II != EE; ++II)
117 assert(FoundSucc && "Mismatching preds / succs lists!");
119 // Update the bookkeeping.
120 if (P.getKind() == SDep::Data) {
128 if (P.getLatency() != 0) {
129 this->setDepthDirty();
136 void SUnit::setDepthDirty() {
137 if (!isDepthCurrent) return;
138 SmallVector<SUnit*, 8> WorkList;
139 WorkList.push_back(this);
141 SUnit *SU = WorkList.pop_back_val();
142 SU->isDepthCurrent = false;
143 for (SUnit::const_succ_iterator I = SU->Succs.begin(),
144 E = SU->Succs.end(); I != E; ++I) {
145 SUnit *SuccSU = I->getSUnit();
146 if (SuccSU->isDepthCurrent)
147 WorkList.push_back(SuccSU);
149 } while (!WorkList.empty());
152 void SUnit::setHeightDirty() {
153 if (!isHeightCurrent) return;
154 SmallVector<SUnit*, 8> WorkList;
155 WorkList.push_back(this);
157 SUnit *SU = WorkList.pop_back_val();
158 SU->isHeightCurrent = false;
159 for (SUnit::const_pred_iterator I = SU->Preds.begin(),
160 E = SU->Preds.end(); I != E; ++I) {
161 SUnit *PredSU = I->getSUnit();
162 if (PredSU->isHeightCurrent)
163 WorkList.push_back(PredSU);
165 } while (!WorkList.empty());
168 /// setDepthToAtLeast - Update this node's successors to reflect the
169 /// fact that this node's depth just increased.
171 void SUnit::setDepthToAtLeast(unsigned NewDepth) {
172 if (NewDepth <= getDepth())
176 isDepthCurrent = true;
179 /// setHeightToAtLeast - Update this node's predecessors to reflect the
180 /// fact that this node's height just increased.
182 void SUnit::setHeightToAtLeast(unsigned NewHeight) {
183 if (NewHeight <= getHeight())
187 isHeightCurrent = true;
190 /// ComputeDepth - Calculate the maximal path from the node to the exit.
192 void SUnit::ComputeDepth() {
193 SmallVector<SUnit*, 8> WorkList;
194 WorkList.push_back(this);
196 SUnit *Cur = WorkList.back();
199 unsigned MaxPredDepth = 0;
200 for (SUnit::const_pred_iterator I = Cur->Preds.begin(),
201 E = Cur->Preds.end(); I != E; ++I) {
202 SUnit *PredSU = I->getSUnit();
203 if (PredSU->isDepthCurrent)
204 MaxPredDepth = std::max(MaxPredDepth,
205 PredSU->Depth + I->getLatency());
208 WorkList.push_back(PredSU);
214 if (MaxPredDepth != Cur->Depth) {
215 Cur->setDepthDirty();
216 Cur->Depth = MaxPredDepth;
218 Cur->isDepthCurrent = true;
220 } while (!WorkList.empty());
223 /// ComputeHeight - Calculate the maximal path from the node to the entry.
225 void SUnit::ComputeHeight() {
226 SmallVector<SUnit*, 8> WorkList;
227 WorkList.push_back(this);
229 SUnit *Cur = WorkList.back();
232 unsigned MaxSuccHeight = 0;
233 for (SUnit::const_succ_iterator I = Cur->Succs.begin(),
234 E = Cur->Succs.end(); I != E; ++I) {
235 SUnit *SuccSU = I->getSUnit();
236 if (SuccSU->isHeightCurrent)
237 MaxSuccHeight = std::max(MaxSuccHeight,
238 SuccSU->Height + I->getLatency());
241 WorkList.push_back(SuccSU);
247 if (MaxSuccHeight != Cur->Height) {
248 Cur->setHeightDirty();
249 Cur->Height = MaxSuccHeight;
251 Cur->isHeightCurrent = true;
253 } while (!WorkList.empty());
256 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
257 /// a group of nodes flagged together.
258 void SUnit::dump(const ScheduleDAG *G) const {
259 cerr << "SU(" << NodeNum << "): ";
263 void SUnit::dumpAll(const ScheduleDAG *G) const {
266 cerr << " # preds left : " << NumPredsLeft << "\n";
267 cerr << " # succs left : " << NumSuccsLeft << "\n";
268 cerr << " Latency : " << Latency << "\n";
269 cerr << " Depth : " << Depth << "\n";
270 cerr << " Height : " << Height << "\n";
272 if (Preds.size() != 0) {
273 cerr << " Predecessors:\n";
274 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
277 switch (I->getKind()) {
278 case SDep::Data: cerr << "val "; break;
279 case SDep::Anti: cerr << "anti"; break;
280 case SDep::Output: cerr << "out "; break;
281 case SDep::Order: cerr << "ch "; break;
284 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
285 if (I->isArtificial())
290 if (Succs.size() != 0) {
291 cerr << " Successors:\n";
292 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
295 switch (I->getKind()) {
296 case SDep::Data: cerr << "val "; break;
297 case SDep::Anti: cerr << "anti"; break;
298 case SDep::Output: cerr << "out "; break;
299 case SDep::Order: cerr << "ch "; break;
302 cerr << I->getSUnit() << " - SU(" << I->getSUnit()->NodeNum << ")";
303 if (I->isArtificial())
312 /// VerifySchedule - Verify that all SUnits were scheduled and that
313 /// their state is consistent.
315 void ScheduleDAG::VerifySchedule(bool isBottomUp) {
316 bool AnyNotSched = false;
317 unsigned DeadNodes = 0;
319 for (unsigned i = 0, e = SUnits.size(); i != e; ++i) {
320 if (!SUnits[i].isScheduled) {
321 if (SUnits[i].NumPreds == 0 && SUnits[i].NumSuccs == 0) {
326 cerr << "*** Scheduling failed! ***\n";
327 SUnits[i].dump(this);
328 cerr << "has not been scheduled!\n";
331 if (SUnits[i].isScheduled &&
332 (isBottomUp ? SUnits[i].getHeight() : SUnits[i].getHeight()) >
335 cerr << "*** Scheduling failed! ***\n";
336 SUnits[i].dump(this);
337 cerr << "has an unexpected "
338 << (isBottomUp ? "Height" : "Depth") << " value!\n";
342 if (SUnits[i].NumSuccsLeft != 0) {
344 cerr << "*** Scheduling failed! ***\n";
345 SUnits[i].dump(this);
346 cerr << "has successors left!\n";
350 if (SUnits[i].NumPredsLeft != 0) {
352 cerr << "*** Scheduling failed! ***\n";
353 SUnits[i].dump(this);
354 cerr << "has predecessors left!\n";
359 for (unsigned i = 0, e = Sequence.size(); i != e; ++i)
362 assert(!AnyNotSched);
363 assert(Sequence.size() + DeadNodes - Noops == SUnits.size() &&
364 "The number of nodes scheduled doesn't match the expected number!");
368 /// InitDAGTopologicalSorting - create the initial topological
369 /// ordering from the DAG to be scheduled.
371 /// The idea of the algorithm is taken from
372 /// "Online algorithms for managing the topological order of
373 /// a directed acyclic graph" by David J. Pearce and Paul H.J. Kelly
374 /// This is the MNR algorithm, which was first introduced by
375 /// A. Marchetti-Spaccamela, U. Nanni and H. Rohnert in
376 /// "Maintaining a topological order under edge insertions".
378 /// Short description of the algorithm:
380 /// Topological ordering, ord, of a DAG maps each node to a topological
381 /// index so that for all edges X->Y it is the case that ord(X) < ord(Y).
383 /// This means that if there is a path from the node X to the node Z,
384 /// then ord(X) < ord(Z).
386 /// This property can be used to check for reachability of nodes:
387 /// if Z is reachable from X, then an insertion of the edge Z->X would
390 /// The algorithm first computes a topological ordering for the DAG by
391 /// initializing the Index2Node and Node2Index arrays and then tries to keep
392 /// the ordering up-to-date after edge insertions by reordering the DAG.
394 /// On insertion of the edge X->Y, the algorithm first marks by calling DFS
395 /// the nodes reachable from Y, and then shifts them using Shift to lie
396 /// immediately after X in Index2Node.
397 void ScheduleDAGTopologicalSort::InitDAGTopologicalSorting() {
398 unsigned DAGSize = SUnits.size();
399 std::vector<SUnit*> WorkList;
400 WorkList.reserve(DAGSize);
402 Index2Node.resize(DAGSize);
403 Node2Index.resize(DAGSize);
405 // Initialize the data structures.
406 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
407 SUnit *SU = &SUnits[i];
408 int NodeNum = SU->NodeNum;
409 unsigned Degree = SU->Succs.size();
410 // Temporarily use the Node2Index array as scratch space for degree counts.
411 Node2Index[NodeNum] = Degree;
413 // Is it a node without dependencies?
415 assert(SU->Succs.empty() && "SUnit should have no successors");
416 // Collect leaf nodes.
417 WorkList.push_back(SU);
422 while (!WorkList.empty()) {
423 SUnit *SU = WorkList.back();
425 Allocate(SU->NodeNum, --Id);
426 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
428 SUnit *SU = I->getSUnit();
429 if (!--Node2Index[SU->NodeNum])
430 // If all dependencies of the node are processed already,
431 // then the node can be computed now.
432 WorkList.push_back(SU);
436 Visited.resize(DAGSize);
439 // Check correctness of the ordering
440 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
441 SUnit *SU = &SUnits[i];
442 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
444 assert(Node2Index[SU->NodeNum] > Node2Index[I->getSUnit()->NodeNum] &&
445 "Wrong topological sorting");
451 /// AddPred - Updates the topological ordering to accomodate an edge
452 /// to be added from SUnit X to SUnit Y.
453 void ScheduleDAGTopologicalSort::AddPred(SUnit *Y, SUnit *X) {
454 int UpperBound, LowerBound;
455 LowerBound = Node2Index[Y->NodeNum];
456 UpperBound = Node2Index[X->NodeNum];
457 bool HasLoop = false;
458 // Is Ord(X) < Ord(Y) ?
459 if (LowerBound < UpperBound) {
460 // Update the topological order.
462 DFS(Y, UpperBound, HasLoop);
463 assert(!HasLoop && "Inserted edge creates a loop!");
464 // Recompute topological indexes.
465 Shift(Visited, LowerBound, UpperBound);
469 /// RemovePred - Updates the topological ordering to accomodate an
470 /// an edge to be removed from the specified node N from the predecessors
471 /// of the current node M.
472 void ScheduleDAGTopologicalSort::RemovePred(SUnit *M, SUnit *N) {
473 // InitDAGTopologicalSorting();
476 /// DFS - Make a DFS traversal to mark all nodes reachable from SU and mark
477 /// all nodes affected by the edge insertion. These nodes will later get new
478 /// topological indexes by means of the Shift method.
479 void ScheduleDAGTopologicalSort::DFS(const SUnit *SU, int UpperBound,
481 std::vector<const SUnit*> WorkList;
482 WorkList.reserve(SUnits.size());
484 WorkList.push_back(SU);
486 SU = WorkList.back();
488 Visited.set(SU->NodeNum);
489 for (int I = SU->Succs.size()-1; I >= 0; --I) {
490 int s = SU->Succs[I].getSUnit()->NodeNum;
491 if (Node2Index[s] == UpperBound) {
495 // Visit successors if not already and in affected region.
496 if (!Visited.test(s) && Node2Index[s] < UpperBound) {
497 WorkList.push_back(SU->Succs[I].getSUnit());
500 } while (!WorkList.empty());
503 /// Shift - Renumber the nodes so that the topological ordering is
505 void ScheduleDAGTopologicalSort::Shift(BitVector& Visited, int LowerBound,
511 for (i = LowerBound; i <= UpperBound; ++i) {
512 // w is node at topological index i.
513 int w = Index2Node[i];
514 if (Visited.test(w)) {
520 Allocate(w, i - shift);
524 for (unsigned j = 0; j < L.size(); ++j) {
525 Allocate(L[j], i - shift);
531 /// WillCreateCycle - Returns true if adding an edge from SU to TargetSU will
533 bool ScheduleDAGTopologicalSort::WillCreateCycle(SUnit *SU, SUnit *TargetSU) {
534 if (IsReachable(TargetSU, SU))
536 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
538 if (I->isAssignedRegDep() &&
539 IsReachable(TargetSU, I->getSUnit()))
544 /// IsReachable - Checks if SU is reachable from TargetSU.
545 bool ScheduleDAGTopologicalSort::IsReachable(const SUnit *SU,
546 const SUnit *TargetSU) {
547 // If insertion of the edge SU->TargetSU would create a cycle
548 // then there is a path from TargetSU to SU.
549 int UpperBound, LowerBound;
550 LowerBound = Node2Index[TargetSU->NodeNum];
551 UpperBound = Node2Index[SU->NodeNum];
552 bool HasLoop = false;
553 // Is Ord(TargetSU) < Ord(SU) ?
554 if (LowerBound < UpperBound) {
556 // There may be a path from TargetSU to SU. Check for it.
557 DFS(TargetSU, UpperBound, HasLoop);
562 /// Allocate - assign the topological index to the node n.
563 void ScheduleDAGTopologicalSort::Allocate(int n, int index) {
564 Node2Index[n] = index;
565 Index2Node[index] = n;
568 ScheduleDAGTopologicalSort::ScheduleDAGTopologicalSort(
569 std::vector<SUnit> &sunits)
572 ScheduleHazardRecognizer::~ScheduleHazardRecognizer() {}